context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2015 Tim Stair // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Support.UI { public partial class RGBColorSelectDialog : Form { private int m_nPreviousColorIndex = -1; bool m_bEventsEnabled = true; private Color m_lastColor = Color.Black; readonly Bitmap m_BitmapHue; private const int PREVIOUS_COLOR_WIDTH = 16; private static readonly List<Color> s_listPreviousColors = new List<Color>(); private static bool s_bZeroXChecked = true; // A delegate type for hooking up change notifications. public delegate void ColorPreviewEvent(object sender, Color zColor); public event ColorPreviewEvent PreviewEvent; private readonly PictureBoxSelectable[] m_arrayPictureBoxes; public RGBColorSelectDialog() { InitializeComponent(); m_BitmapHue = new Bitmap(pictureColorHue.ClientSize.Width, pictureColorHue.ClientSize.Height); pictureColorHue.Image = m_BitmapHue; pictureColorHue.SelectionIndicator = PictureBoxSelectable.IndicatorType.Both; var m_bitmapRedToPurple = new Bitmap(pictureRedToPurple.ClientSize.Width, 255); var m_bitmapPurpleToBlue = new Bitmap(pictureRedToPurple.ClientSize.Width, 255); var m_bitmapBlueToTeal = new Bitmap(pictureRedToPurple.ClientSize.Width, 255); var m_bitmapTealToGreen = new Bitmap(pictureRedToPurple.ClientSize.Width, 255); var m_bitmapGreenToYellow = new Bitmap(pictureRedToPurple.ClientSize.Width, 255); var m_bitmapYellowToRed = new Bitmap(pictureRedToPurple.ClientSize.Width, 255); GenerateColorBar(m_bitmapRedToPurple, Color.FromArgb(255, 0, 0), Color.FromArgb(255, 0, 255)); GenerateColorBar(m_bitmapPurpleToBlue, Color.FromArgb(255, 0, 255), Color.FromArgb(0, 0, 255)); GenerateColorBar(m_bitmapBlueToTeal, Color.FromArgb(0, 0, 255), Color.FromArgb(0, 255, 255)); GenerateColorBar(m_bitmapTealToGreen, Color.FromArgb(0, 255, 255), Color.FromArgb(0, 255, 0)); GenerateColorBar(m_bitmapGreenToYellow, Color.FromArgb(0, 255, 0), Color.FromArgb(255, 255, 0)); GenerateColorBar(m_bitmapYellowToRed, Color.FromArgb(255, 255, 0), Color.FromArgb(255, 0, 0)); pictureRedToPurple.Image = m_bitmapRedToPurple; picturePurpleToBlue.Image = m_bitmapPurpleToBlue; pictureBlueToTeal.Image = m_bitmapBlueToTeal; pictureTealToGreen.Image = m_bitmapTealToGreen; pictureGreenToYellow.Image = m_bitmapGreenToYellow; pictureYellowToRed.Image = m_bitmapYellowToRed; pictureRedToPurple.Tag = m_bitmapRedToPurple; picturePurpleToBlue.Tag = m_bitmapPurpleToBlue; pictureBlueToTeal.Tag = m_bitmapBlueToTeal; pictureTealToGreen.Tag = m_bitmapTealToGreen; pictureGreenToYellow.Tag = m_bitmapGreenToYellow; pictureYellowToRed.Tag = m_bitmapYellowToRed; pictureRedToPurple.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine; picturePurpleToBlue.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine; pictureBlueToTeal.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine; pictureTealToGreen.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine; pictureGreenToYellow.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine; pictureYellowToRed.SelectionIndicator = PictureBoxSelectable.IndicatorType.HLine; m_arrayPictureBoxes = new [] { pictureRedToPurple, picturePurpleToBlue, pictureBlueToTeal, pictureTealToGreen, pictureGreenToYellow, pictureYellowToRed }; // populate the previous colors if (0 < s_listPreviousColors.Count) { var zBmp = new Bitmap(panelPreviousColors.ClientRectangle.Width, panelPreviousColors.ClientRectangle.Height); var zGraphics = Graphics.FromImage(zBmp); var nXOffset = 0; foreach (var prevColor in s_listPreviousColors) { zGraphics.FillRectangle(new SolidBrush(prevColor), nXOffset, 0, PREVIOUS_COLOR_WIDTH, panelPreviousColors.Height); nXOffset += PREVIOUS_COLOR_WIDTH; } panelPreviousColors.BackgroundImage = zBmp; } UpdateHue(Color.Red); } #if false public void SetColor(Color zColor) { UpdateColorBox(zColor); panelColor.BackColor = zColor; int nRed = 0; int nGreen = 0; int nBlue = 0; if (zColor.R > zColor.B) { nRed = zColor.R; if (zColor.G > zColor.B) { nGreen = zColor.G; } else { nBlue = zColor.B; } } else { nBlue = zColor.B; if (zColor.G > zColor.B) { nGreen = zColor.G; } else { nBlue = zColor.B; } } //Color colorSeek = Color.FromArgb(255, nRed, nGreen, nBlue); //for (int nIdx = 0; nIdx < m_BitmapColors.Height; nIdx++) //{ // Color pixelColor = m_BitmapColors.GetPixel(0, nIdx); // Console.WriteLine(pixelColor + "::" + colorSeek); // if (colorSeek == pixelColor) // { // pictureRedToPurple.Yposition = nIdx; // break; // } //} } #endif public void UpdateColorBox(Color colorCurrent) { m_bEventsEnabled = false; numericRed.Value = colorCurrent.R; numericGreen.Value = colorCurrent.G; numericBlue.Value = colorCurrent.B; m_lastColor = colorCurrent; UpdateColorHexText(); panelColor.BackColor = colorCurrent; m_bEventsEnabled = true; PreviewEvent?.Invoke(this, colorCurrent); } private void UpdateColorHexText() { txtHexColor.Text = (checkBoxAddZeroX.Checked ? "0x" : string.Empty) + m_lastColor.R.ToString("X").PadLeft(2, '0') + m_lastColor.G.ToString("X").PadLeft(2, '0') + m_lastColor.B.ToString("X").PadLeft(2, '0'); } public Color Color => Color.FromArgb((int)numericRed.Value, (int)numericGreen.Value, (int)numericBlue.Value); public void SetHueColor() { UpdateColorBox(m_BitmapHue.GetPixel(pictureColorHue.Xposition, pictureColorHue.Yposition)); } private void GenerateColorBar(Bitmap zBmp, Color colorFrom, Color colorTo) { var zGraphics = Graphics.FromImage(zBmp); var zLinear = new LinearGradientBrush(new Rectangle(0, 0, zBmp.Width, zBmp.Height), colorFrom, colorTo, 90); zGraphics.FillRectangle(zLinear, new Rectangle(0, 0, zBmp.Width, zBmp.Height)); } private void UpdateHue(Color zColor) { var zGraphics = Graphics.FromImage(m_BitmapHue); int nRedMax = zColor.R; int nGreenMax = zColor.G; int nBlueMax = zColor.B; var fRedInterval = (float)(255 - nRedMax) / (float)255; var fGreenInterval = (float)(255 - nGreenMax) / (float)255; var fBlueInterval = (float)(255 - nBlueMax) / (float)255; for (int nRow = 0; nRow < m_BitmapHue.Height; nRow++) { var nRed = (int)((float)nRedMax + (float)nRow * fRedInterval); var nGreen = (int)((float)nGreenMax + (float)nRow * fGreenInterval); var nBlue = (int)((float)nBlueMax + (float)nRow * fBlueInterval); if ((m_BitmapHue.Height - 1) == nRow) { nRed = 255; nGreen = 255; nBlue = 255; } nRed = GetWithinRange(nRed, 0, 255); nGreen = GetWithinRange(nGreen, 0, 255); nBlue = GetWithinRange(nBlue, 0, 255); zGraphics.FillRectangle( new LinearGradientBrush(new Point(0, 0), new Point(m_BitmapHue.Width -1, 0), Color.Black, Color.FromArgb(nRed, nGreen, nBlue)), new Rectangle(0, nRow, m_BitmapHue.Width, 1)); } pictureColorHue.Invalidate(); } public int GetWithinRange(int nValue, int nMin, int nMax) { if (nValue > nMax) { return nMax; } if (nValue < nMin) { return nMin; } return nValue; } private void numeric_ValueChanged(object sender, EventArgs e) { if(m_bEventsEnabled) { Color zColor = Color.FromArgb((int)numericRed.Value, (int)numericGreen.Value, (int)numericBlue.Value); UpdateColorBox(zColor); } } private void pictureColor_MouseEnter(object sender, EventArgs e) { Cursor = Cursors.Cross; } private void pictureColor_MouseLeave(object sender, EventArgs e) { Cursor = Cursors.Default; } public void HandleMouseHueColor(object sender, MouseEventArgs e) { switch (e.Button) { case MouseButtons.Left: UpdateColorBox(m_BitmapHue.GetPixel(pictureColorHue.Xposition, pictureColorHue.Yposition)); break; } } public void HandleMouseColor(object sender, MouseEventArgs e) { switch (e.Button) { case MouseButtons.Left: var pictureBox = (PictureBoxSelectable)sender; if ((-1 < e.Y) && (pictureBox.Image.Height > e.Y)) { Color colorSelected = ((Bitmap)pictureBox.Tag).GetPixel(0, e.Y); UpdateHue(colorSelected); SetHueColor(); foreach (PictureBoxSelectable picBox in m_arrayPictureBoxes) { if (picBox != pictureBox) { picBox.Yposition = 0; picBox.Invalidate(); } } } break; } } private void btnOK_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Color colorSelected = Color.FromArgb((int)numericRed.Value, (int)numericGreen.Value, (int)numericBlue.Value); int nMaxPreviousColors = panelPreviousColors.Width / PREVIOUS_COLOR_WIDTH; if (0 == s_listPreviousColors.Count || (0 < s_listPreviousColors.Count && s_listPreviousColors[0] != colorSelected)) { // clean up any existing copies of the selected color int nIdx = 0; while (nIdx < s_listPreviousColors.Count) { if (s_listPreviousColors[nIdx] != colorSelected) nIdx++; else s_listPreviousColors.RemoveAt(nIdx); } // make room for the new "previous" color while (s_listPreviousColors.Count >= nMaxPreviousColors) s_listPreviousColors.RemoveAt(s_listPreviousColors.Count - 1); s_listPreviousColors.Insert(0, colorSelected); } Close(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void panelPreviousColors_MouseDown(object sender, MouseEventArgs e) { if (m_nPreviousColorIndex < s_listPreviousColors.Count) { UpdateColorBox(Color.FromArgb( s_listPreviousColors[m_nPreviousColorIndex].R, s_listPreviousColors[m_nPreviousColorIndex].G, s_listPreviousColors[m_nPreviousColorIndex].B)); } } private void panelPreviousColors_MouseMove(object sender, MouseEventArgs e) { int nColorIndex = e.X / PREVIOUS_COLOR_WIDTH; if (m_nPreviousColorIndex == nColorIndex) return; m_nPreviousColorIndex = nColorIndex; if (m_nPreviousColorIndex < s_listPreviousColors.Count) { toolTipPreviouscolor.SetToolTip(panelPreviousColors, "R:" + s_listPreviousColors[m_nPreviousColorIndex].R.ToString("000") + " " + "G:" + s_listPreviousColors[m_nPreviousColorIndex].G.ToString("000") + " " + "B:" + s_listPreviousColors[m_nPreviousColorIndex].B.ToString("000")); } } private void checkBoxAddZeroX_CheckedChanged(object sender, EventArgs e) { UpdateColorHexText(); } private void RGBColorSelectDialog_FormClosing(object sender, FormClosingEventArgs e) { s_bZeroXChecked = checkBoxAddZeroX.Checked; } private void RGBColorSelectDialog_Load(object sender, EventArgs e) { checkBoxAddZeroX.Checked = s_bZeroXChecked; } } class PictureBoxSelectable : PictureBox { private int m_nPosX; private int m_nPosY; private IndicatorType m_eIndicatorType = IndicatorType.None; public IndicatorType SelectionIndicator { get { return m_eIndicatorType; } set { m_eIndicatorType = value; } } public int Xposition { get { return m_nPosX; } set { m_nPosX = value; } } public int Yposition { get { return m_nPosY; } set { m_nPosY = value; } } public enum IndicatorType { VLine, HLine, Both, None } public PictureBoxSelectable() { MouseMove += PictureBoxSelectable_MouseMove; } void PictureBoxSelectable_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { // clamp the selection to be inside the client if (ClientRectangle.Contains(e.X, 0)) { m_nPosX = e.X; } else if (e.X < ClientRectangle.Left) { m_nPosX = ClientRectangle.Left; } else if (e.X > ClientRectangle.Right - 1) { m_nPosX = ClientRectangle.Right - 1; } if (ClientRectangle.Contains(0, e.Y)) { m_nPosY = e.Y; } else if (e.Y < ClientRectangle.Top) { m_nPosY = ClientRectangle.Top; } else if (e.Y > ClientRectangle.Bottom - 1) { m_nPosY = ClientRectangle.Bottom - 1; } Invalidate(); } } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); switch (m_eIndicatorType) { case IndicatorType.HLine: pe.Graphics.DrawLine(new Pen(Color.FromArgb(255, 255, 255, 255)), new Point(0, m_nPosY), new Point(ClientSize.Width, m_nPosY)); break; case IndicatorType.VLine: pe.Graphics.DrawLine(new Pen(Color.FromArgb(255, 255, 255, 255)), new Point(m_nPosX, 0), new Point(m_nPosX, ClientSize.Height)); break; case IndicatorType.Both: pe.Graphics.DrawLine(new Pen(Color.FromArgb(255, 255, 255, 255)), new Point(0, m_nPosY), new Point(ClientSize.Width, m_nPosY)); pe.Graphics.DrawLine(new Pen(Color.FromArgb(255, 255, 255, 255)), new Point(m_nPosX, 0), new Point(m_nPosX, ClientSize.Height)); break; } } } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.Text; using System.IO; using AutomationTool; using UnrealBuildTool; [Help("custom code to restructure C++ source code for the new stats system.")] class CodeSurgery : BuildCommand { public override void ExecuteBuild() { Log("************************* Reworking stats code"); var Wildcards = new List<string>() { "*.h", "*.cpp", "*.inl" }; // @todo: Add support for STATCAT_ var DeclareStrings = new List<string>() { "DECLARE_CYCLE_STAT", "DECLARE_FLOAT_COUNTER_STAT", "DECLARE_DWORD_COUNTER_STAT", "DECLARE_FLOAT_ACCUMULATOR_STAT", "DECLARE_DWORD_ACCUMULATOR_STAT", "DECLARE_MEMORY_STAT", "DECLARE_MEMORY_STAT_POOL", "DECLARE_STATS_GROUP" }; DirectoryInfo DirInfo = new DirectoryInfo(CmdEnv.LocalRoot); var TopLevelDirs = DirInfo.GetDirectories(); var Dirs = new List<string>(); foreach (var TopLevelDir in TopLevelDirs) { if (DirectoryExists_NoExceptions(CombinePaths(TopLevelDir.FullName, "Source"))) { Dirs.Add(CombinePaths(TopLevelDir.FullName, "Source")); } } var AllFiles = new List<string>(); foreach (var Dir in Dirs) { foreach (var Wildcard in Wildcards) { foreach (var ThisFile in CommandUtils.FindFiles_NoExceptions(Wildcard, true, Dir)) { if ( !ThisFile.Contains(@"Runtime\Core\Public\Stats\Stats2") && !ThisFile.Contains(@"\ThirdParty\") ) { Log("Source File: {0}", ThisFile); AllFiles.Add(ThisFile); } } } } var DeclareFiles = new Dictionary<string, string>(); var DeclareLines = new Dictionary<string, string>(); var EnumFiles = new Dictionary<string, string>(); var EnumLines = new Dictionary<string, string>(); var Broken = new Dictionary<string, string>(); foreach (var ThisFile in AllFiles) { var FileText = ReadAllText(ThisFile); if (FileText.Contains("STAT_") || FileText.Contains("STATGROUP_")) { var Lines = ReadAllLines(ThisFile); foreach (var LineWithWS in Lines) { var Line = LineWithWS.Trim(); if (Line.Contains("STAT_") || Line.Contains("STATGROUP_")) { string TypeString = "STAT_"; if (!Line.Contains(TypeString) || Line.Contains("DECLARE_STATS_GROUP")) { TypeString = "STATGROUP_"; } bool bDeclareLine = false; foreach (var DeclareString in DeclareStrings) { if (Line.Contains(DeclareString)) { bDeclareLine = true; break; } } var Cut = Line; string Exception = "DECLARE_MEMORY_STAT_POOL"; if (Line.StartsWith(Exception)) { Cut = Line.Substring(Exception.Length); } Cut = Cut.Substring(Cut.IndexOf(TypeString)); int End = Cut.IndexOf(","); if (End < 0) { End = Cut.Length; } int EndEq = Cut.IndexOf("="); int EndParen = Cut.IndexOf(")"); int EndParen2 = Cut.IndexOf("("); if (EndEq > 0 && EndEq < End) { End = EndEq; } if (EndParen > 0 && EndParen < End) { End = EndParen; } if (EndParen2 > 0 && EndParen2 < End) { End = EndParen2; } string StatName = Cut.Substring(0, End).Trim(); bool bEnumLine = false; if (!bDeclareLine) { if ((Line.EndsWith(",") || Line == StatName) && Line.StartsWith(TypeString)) { bEnumLine = true; } } if (bEnumLine || bDeclareLine) { Log("{0} {1} Line: {2} : {3}", bEnumLine ? "Enum" : "Declare", TypeString, StatName, Line); if (bEnumLine) { if (EnumFiles.ContainsKey(StatName)) { if (!Broken.ContainsKey(StatName)) { Broken.Add(StatName, Line); } } else { EnumFiles.Add(StatName, ThisFile); EnumLines.Add(StatName, Line); } } else { if (DeclareFiles.ContainsKey(StatName)) { if (!Broken.ContainsKey(StatName)) { Broken.Add(StatName, Line); } } else { DeclareFiles.Add(StatName, ThisFile); DeclareLines.Add(StatName, Line); } } } } } } } var AllGoodStats = new List<string>(); var AllGoodGroups = new List<string>(); foreach (var DeclareLine in DeclareLines) { if (!Broken.ContainsKey(DeclareLine.Key)) { if (EnumFiles.ContainsKey(DeclareLine.Key)) { if (DeclareLine.Key.StartsWith("STATGROUP_")) { AllGoodGroups.Add(DeclareLine.Key); } else { AllGoodStats.Add(DeclareLine.Key); } } else { Broken.Add(DeclareLine.Key, DeclareLine.Value); } } } var ToCheckOuts = new HashSet<string>(); Log("Stats *************************"); foreach (var AllGoodStat in AllGoodStats) { Log("{0}", AllGoodStat); ToCheckOuts.Add(DeclareFiles[AllGoodStat]); ToCheckOuts.Add(EnumFiles[AllGoodStat]); } Log("Groups *************************"); foreach (var AllGoodGroup in AllGoodGroups) { Log("{0}", AllGoodGroup); ToCheckOuts.Add(DeclareFiles[AllGoodGroup]); ToCheckOuts.Add(EnumFiles[AllGoodGroup]); } Log("Broken *************************"); foreach (var BrokenItem in Broken) { Log("{0}", BrokenItem.Key); } Log("*************************"); int WorkingCL = -1; if (P4Enabled) { WorkingCL = P4.CreateChange(P4Env.Client, "Stat code surgery"); Log("Working in {0}", WorkingCL); } else { throw new AutomationException("this command needs to run with P4."); } var CheckedOuts = new HashSet<string>(); foreach (var ToCheckOut in ToCheckOuts) { if (P4.Edit_NoExceptions(WorkingCL, ToCheckOut)) { CheckedOuts.Add(ToCheckOut); } } Log("Checked Out *************************"); foreach (var CheckedOut in CheckedOuts) { Log("{0}", CheckedOut); } Log("Failed to check out *************************"); foreach (var ToCheckOut in ToCheckOuts) { if (!CheckedOuts.Contains(ToCheckOut)) { Log("{0}", ToCheckOut); } } Log("*************************"); foreach (var AllGoodStat in AllGoodStats) { if (EnumFiles[AllGoodStat].EndsWith(".cpp", StringComparison.InvariantCultureIgnoreCase)) { var DeclareFileText = ReadAllText(DeclareFiles[AllGoodStat]); DeclareFileText = DeclareFileText.Replace(DeclareLines[AllGoodStat], ""); WriteAllText(DeclareFiles[AllGoodStat], DeclareFileText); var EnumFileText = ReadAllText(EnumFiles[AllGoodStat]); EnumFileText = EnumFileText.Replace(EnumLines[AllGoodStat], DeclareLines[AllGoodStat]); WriteAllText(EnumFiles[AllGoodStat], EnumFileText); } else { var DeclareFileText = ReadAllText(DeclareFiles[AllGoodStat]); DeclareFileText = DeclareFileText.Replace(DeclareLines[AllGoodStat], "DEFINE_STAT(" + AllGoodStat + ");"); WriteAllText(DeclareFiles[AllGoodStat], DeclareFileText); var EnumFileText = ReadAllText(EnumFiles[AllGoodStat]); var ExternDeclare = DeclareLines[AllGoodStat]; int Paren = ExternDeclare.IndexOf("("); ExternDeclare = ExternDeclare.Substring(0, Paren) + "_EXTERN" + ExternDeclare.Substring(Paren); Paren = ExternDeclare.LastIndexOf(")"); ExternDeclare = ExternDeclare.Substring(0, Paren) + ", " + ExternDeclare.Substring(Paren); EnumFileText = EnumFileText.Replace(EnumLines[AllGoodStat], ExternDeclare); WriteAllText(EnumFiles[AllGoodStat], EnumFileText); } } foreach (var AllGoodGroup in AllGoodGroups) { var DeclareFileText = ReadAllText(DeclareFiles[AllGoodGroup]); DeclareFileText = DeclareFileText.Replace(DeclareLines[AllGoodGroup], ""); WriteAllText(DeclareFiles[AllGoodGroup], DeclareFileText); var EnumFileText = ReadAllText(EnumFiles[AllGoodGroup]); EnumFileText = EnumFileText.Replace(EnumLines[AllGoodGroup], DeclareLines[AllGoodGroup]); WriteAllText(EnumFiles[AllGoodGroup], EnumFileText); } Log("*************************"); } } [Help("custom code to modify the copyright in the code.")] class UpdateCopyright : BuildCommand { public override void ExecuteBuild() { Log("************************* UpdateCopyright"); var Wildcards = new List<string>() { "*.h", "*.cpp", "*.inl", "*.cs" }; var Dirs = new List<string>(); Dirs.Add(CombinePaths(CmdEnv.LocalRoot, "Engine", "Plugins")); { DirectoryInfo DirInfo = new DirectoryInfo(CmdEnv.LocalRoot); var TopLevelDirs = DirInfo.GetDirectories(); foreach (var TopLevelDir in TopLevelDirs) { if (DirectoryExists_NoExceptions(CombinePaths(TopLevelDir.FullName, "Source"))) { Dirs.Add(CombinePaths(TopLevelDir.FullName, "Source")); Dirs.Add(CombinePaths(TopLevelDir.FullName, "Build", "Scripts")); } } } { DirectoryInfo DirInfo = new DirectoryInfo(CombinePaths(CmdEnv.LocalRoot, "Samples", "SampleGames")); var TopLevelDirs = DirInfo.GetDirectories(); foreach (var TopLevelDir in TopLevelDirs) { if (DirectoryExists_NoExceptions(CombinePaths(TopLevelDir.FullName, "Source"))) { Dirs.Add(CombinePaths(TopLevelDir.FullName, "Source")); Dirs.Add(CombinePaths(TopLevelDir.FullName, "Build", "Scripts")); } } } { DirectoryInfo DirInfo = new DirectoryInfo(CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases")); var TopLevelDirs = DirInfo.GetDirectories(); foreach (var TopLevelDir in TopLevelDirs) { if (DirectoryExists_NoExceptions(CombinePaths(TopLevelDir.FullName, "Source"))) { Dirs.Add(CombinePaths(TopLevelDir.FullName, "Source")); Dirs.Add(CombinePaths(TopLevelDir.FullName, "Build", "Scripts")); } } } { DirectoryInfo DirInfo = new DirectoryInfo(CombinePaths(CmdEnv.LocalRoot, "Templates")); var TopLevelDirs = DirInfo.GetDirectories(); foreach (var TopLevelDir in TopLevelDirs) { if (DirectoryExists_NoExceptions(CombinePaths(TopLevelDir.FullName, "Source"))) { Dirs.Add(CombinePaths(TopLevelDir.FullName, "Source")); Dirs.Add(CombinePaths(TopLevelDir.FullName, "Build", "Scripts")); } } } var AllFiles = new List<string>(); foreach (var Dir in Dirs) { foreach (var Wildcard in Wildcards) { foreach (var ThisFile in CommandUtils.FindFiles_NoExceptions(Wildcard, true, Dir)) { if (!ThisFile.Contains(@"\ThirdParty\")) { Log("Source File: {0}", ThisFile); AllFiles.Add(ThisFile); } } } } int WorkingCL = -1; if (P4Enabled) { WorkingCL = P4.CreateChange(P4Env.Client, "Stat code surgery"); Log("Working in {0}", WorkingCL); } else { throw new AutomationException("this command needs to run with P4."); } foreach (var ToCheckOut in AllFiles) { if (P4.Edit_NoExceptions(WorkingCL, ToCheckOut)) { Log("Checked out {0}", ToCheckOut); } else if (ToCheckOut.Contains("CodeSurgery")) { Log("Couldn't check out {0}", ToCheckOut); } else { P4.RevertAll(WorkingCL); throw new AutomationException("Couldn't check out {0}", ToCheckOut); } } var Normal = new HashSet<string>(); var Missing = new HashSet<string>(); foreach (var ThisFile in AllFiles) { var FileText = ReadAllText(ThisFile); if (FileText.Contains("2013 Epic Games, Inc. All Rights Reserved.")) { FileText = FileText.Replace("2013 Epic Games, Inc. All Rights Reserved.", "2014 Epic Games, Inc. All Rights Reserved."); WriteAllText(ThisFile, FileText); Normal.Add(ThisFile); } else { var Lines = new List<string>(ReadAllLines(ThisFile)); Lines.Insert(0, "// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved."); WriteAllLines(ThisFile, Lines.ToArray()); Missing.Add(ThisFile); } } Log("Normal Copyright *************************"); foreach (var ThisFile in Normal) { Log(" {0}", ThisFile); } Log("Missing Copyright *************************"); foreach (var ThisFile in Missing) { Log(" {0}", ThisFile); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Internal; using System.Net; using System.Text; using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands { /// <summary> /// Class comment. /// </summary> [Cmdlet(VerbsData.ConvertTo, "Html", DefaultParameterSetName = "Page", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113290", RemotingCapability = RemotingCapability.None)] public sealed class ConvertToHtmlCommand : PSCmdlet { /// <summary>The incoming object</summary> /// <value></value> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { get { return _inputObject; } set { _inputObject = value; } } private PSObject _inputObject; /// <summary> /// The list of properties to display. /// These take the form of a PSPropertyExpression. /// </summary> /// <value></value> [Parameter(Position = 0)] public object[] Property { get { return _property; } set { _property = value; } } private object[] _property; /// <summary> /// Text to go after the opening body tag and before the table. /// </summary> /// <value></value> [Parameter(ParameterSetName = "Page", Position = 3)] public string[] Body { get { return _body; } set { _body = value; } } private string[] _body; /// <summary> /// Text to go into the head section of the html doc. /// </summary> /// <value></value> [Parameter(ParameterSetName = "Page", Position = 1)] public string[] Head { get { return _head; } set { _head = value; } } private string[] _head; /// <summary> /// The string for the title tag /// The title is also placed in the body of the document /// before the table between h3 tags /// If the -Head parameter is used, this parameter has no /// effect. /// </summary> /// <value></value> [Parameter(ParameterSetName = "Page", Position = 2)] [ValidateNotNullOrEmpty] public string Title { get { return _title; } set { _title = value; } } private string _title = "HTML TABLE"; /// <summary> /// This specifies whether the objects should /// be rendered as an HTML TABLE or /// HTML LIST. /// </summary> /// <value></value> [Parameter] [ValidateNotNullOrEmpty] [ValidateSet("Table", "List")] public string As { get { return _as; } set { _as = value; } } private string _as = "Table"; /// <summary> /// This specifies a full or partial URI /// for the CSS information. /// The HTML should reference the CSS file specified. /// </summary> [Parameter(ParameterSetName = "Page")] [Alias("cu", "uri")] [ValidateNotNullOrEmpty] public Uri CssUri { get { return _cssuri; } set { _cssuri = value; _cssuriSpecified = true; } } private Uri _cssuri; private bool _cssuriSpecified; /// <summary> /// When this switch is specified generate only the /// HTML representation of the incoming object /// without the HTML,HEAD,TITLE,BODY,etc tags. /// </summary> [Parameter(ParameterSetName = "Fragment")] [ValidateNotNullOrEmpty] public SwitchParameter Fragment { get { return _fragment; } set { _fragment = value; } } private SwitchParameter _fragment; /// <summary> /// Specifies the text to include prior the closing body tag of the HTML output. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] PostContent { get { return _postContent; } set { _postContent = value; } } private string[] _postContent; /// <summary> /// Specifies the text to include after the body tag of the HTML output. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] PreContent { get { return _preContent; } set { _preContent = value; } } private string[] _preContent; /// <summary> /// Sets and Gets the meta property of the HTML head. /// </summary> /// <returns></returns> [Parameter(ParameterSetName = "Page")] [ValidateNotNullOrEmpty] public Hashtable Meta { get { return _meta; } set { _meta = value; _metaSpecified = true; } } private Hashtable _meta; private bool _metaSpecified = false; /// <summary> /// Specifies the charset encoding for the HTML document. /// </summary> [Parameter(ParameterSetName = "Page")] [ValidateNotNullOrEmpty] [ValidatePattern("^[A-Za-z0-9]\\w+\\S+[A-Za-z0-9]$")] public string Charset { get { return _charset; } set { _charset = value; _charsetSpecified = true; } } private string _charset; private bool _charsetSpecified = false; /// <summary> /// When this switch statement is specified, /// it will change the DOCTYPE to XHTML Transitional DTD. /// </summary> /// <returns></returns> [Parameter(ParameterSetName = "Page")] [ValidateNotNullOrEmpty] public SwitchParameter Transitional { get { return _transitional; } set { _transitional = true; } } private bool _transitional = false; /// <summary> /// Definitions for hash table keys. /// </summary> internal static class ConvertHTMLParameterDefinitionKeys { internal const string LabelEntryKey = "label"; internal const string AlignmentEntryKey = "alignment"; internal const string WidthEntryKey = "width"; } /// <summary> /// This allows for @{e='foo';label='bar';alignment='center';width='20'}. /// </summary> internal class ConvertHTMLExpressionParameterDefinition : CommandParameterDefinition { protected override void SetEntries() { this.hashEntries.Add(new ExpressionEntryDefinition()); this.hashEntries.Add(new LabelEntryDefinition()); this.hashEntries.Add(new HashtableEntryDefinition(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, new[] { typeof(string) })); // Note: We accept "width" as either string or int. this.hashEntries.Add(new HashtableEntryDefinition(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, new[] { typeof(string), typeof(int) })); } } /// <summary> /// Create a list of MshParameter from properties. /// </summary> /// <param name="properties">Can be a string, ScriptBlock, or Hashtable.</param> /// <returns></returns> private List<MshParameter> ProcessParameter(object[] properties) { TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); ParameterProcessor processor = new ParameterProcessor(new ConvertHTMLExpressionParameterDefinition()); if (properties == null) { properties = new object[] { "*" }; } return processor.ProcessParameters(properties, invocationContext); } /// <summary> /// Resolve all wildcards in user input Property into resolvedNameMshParameters. /// </summary> private void InitializeResolvedNameMshParameters() { // temp list of properties with wildcards resolved ArrayList resolvedNameProperty = new ArrayList(); foreach (MshParameter p in _propertyMshParameterList) { string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string; string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string; // Accept the width both as a string and as an int. string width; int? widthNum = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as int?; width = widthNum != null ? widthNum.Value.ToString() : p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string; PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; List<PSPropertyExpression> resolvedNames = ex.ResolveNames(_inputObject); foreach (PSPropertyExpression resolvedName in resolvedNames) { Hashtable ht = CreateAuxPropertyHT(label, alignment, width); if (resolvedName.Script != null) { // The argument is a calculated property whose value is calculated by a script block. ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.Script); } else { ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.ToString()); } resolvedNameProperty.Add(ht); } } _resolvedNameMshParameters = ProcessParameter(resolvedNameProperty.ToArray()); } private static Hashtable CreateAuxPropertyHT( string label, string alignment, string width) { Hashtable ht = new Hashtable(); if (label != null) { ht.Add(ConvertHTMLParameterDefinitionKeys.LabelEntryKey, label); } if (alignment != null) { ht.Add(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, alignment); } if (width != null) { ht.Add(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, width); } return ht; } /// <summary> /// Calls ToString. If an exception occurs, eats it and return string.Empty. /// </summary> /// <param name="obj"></param> /// <returns></returns> private static string SafeToString(object obj) { if (obj == null) { return string.Empty; } try { return obj.ToString(); } catch (Exception) { // eats exception if safe } return string.Empty; } /// <summary> /// </summary> protected override void BeginProcessing() { // ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim()))) { ArgumentException ex = new ArgumentException(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri")); ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri"); ThrowTerminatingError(er); } _propertyMshParameterList = ProcessParameter(_property); if (!string.IsNullOrEmpty(_title)) { WebUtility.HtmlEncode(_title); } // This first line ensures w3c validation will succeed. However we are not specifying // an encoding in the HTML because we don't know where the text will be written and // if a particular encoding will be used. if (!_fragment) { if (!_transitional) { WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); } else { WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); } WriteObject("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); WriteObject("<head>"); if (_charsetSpecified) { WriteObject("<meta charset=\"" + _charset + "\">"); } if (_metaSpecified) { List<string> useditems = new List<string>(); foreach (string s in _meta.Keys) { if (!useditems.Contains(s)) { switch (s.ToLower()) { case "content-type": case "default-style": case "x-ua-compatible": WriteObject("<meta http-equiv=\"" + s + "\" content=\"" + _meta[s] + "\">"); break; case "application-name": case "author": case "description": case "generator": case "keywords": case "viewport": WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">"); break; default: MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]); WarningRecord record = new WarningRecord(Message); InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; if (invocationInfo != null) { record.SetInvocationInfo(invocationInfo); } mshCommandRuntime.WriteWarning(record); WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">"); break; } useditems.Add(s); } } } WriteObject(_head ?? new string[] { "<title>" + _title + "</title>" }, true); if (_cssuriSpecified) { WriteObject("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + _cssuri + "\" />"); } WriteObject("</head><body>"); if (_body != null) { WriteObject(_body, true); } } if (_preContent != null) { WriteObject(_preContent, true); } WriteObject("<table>"); _isTHWritten = false; } /// <summary> /// Reads Width and Alignment from Property and write Col tags. /// </summary> /// <param name="mshParams"></param> private void WriteColumns(List<MshParameter> mshParams) { StringBuilder COLTag = new StringBuilder(); COLTag.Append("<colgroup>"); foreach (MshParameter p in mshParams) { COLTag.Append("<col"); string width = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string; if (width != null) { COLTag.Append(" width = \""); COLTag.Append(width); COLTag.Append("\""); } string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string; if (alignment != null) { COLTag.Append(" align = \""); COLTag.Append(alignment); COLTag.Append("\""); } COLTag.Append("/>"); } COLTag.Append("</colgroup>"); // The columngroup and col nodes will be printed in a single line. WriteObject(COLTag.ToString()); } /// <summary> /// Writes the list entries when the As parameter has value List. /// </summary> private void WriteListEntry() { foreach (MshParameter p in _resolvedNameMshParameters) { StringBuilder Listtag = new StringBuilder(); Listtag.Append("<tr><td>"); // for writing the property name WritePropertyName(Listtag, p); Listtag.Append(":"); Listtag.Append("</td>"); // for writing the property value Listtag.Append("<td>"); WritePropertyValue(Listtag, p); Listtag.Append("</td></tr>"); WriteObject(Listtag.ToString()); } } /// <summary> /// To write the Property name. /// </summary> private void WritePropertyName(StringBuilder Listtag, MshParameter p) { // for writing the property name string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string; if (label != null) { Listtag.Append(label); } else { PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; Listtag.Append(ex.ToString()); } } /// <summary> /// To write the Property value. /// </summary> private void WritePropertyValue(StringBuilder Listtag, MshParameter p) { PSPropertyExpression exValue = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; // get the value of the property List<PSPropertyExpressionResult> resultList = exValue.GetValues(_inputObject); foreach (PSPropertyExpressionResult result in resultList) { // create comma sep list for multiple results if (result.Result != null) { string htmlEncodedResult = WebUtility.HtmlEncode(SafeToString(result.Result)); Listtag.Append(htmlEncodedResult); } Listtag.Append(", "); } if (Listtag.ToString().EndsWith(", ", StringComparison.Ordinal)) { Listtag.Remove(Listtag.Length - 2, 2); } } /// <summary> /// To write the Table header for the object property names. /// </summary> private void WriteTableHeader(StringBuilder THtag, List<MshParameter> resolvedNameMshParameters) { // write the property names foreach (MshParameter p in resolvedNameMshParameters) { THtag.Append("<th>"); WritePropertyName(THtag, p); THtag.Append("</th>"); } } /// <summary> /// To write the Table row for the object property values. /// </summary> private void WriteTableRow(StringBuilder TRtag, List<MshParameter> resolvedNameMshParameters) { // write the property values foreach (MshParameter p in resolvedNameMshParameters) { TRtag.Append("<td>"); WritePropertyValue(TRtag, p); TRtag.Append("</td>"); } } // count of the objects private int _numberObjects = 0; /// <summary> /// </summary> protected override void ProcessRecord() { // writes the table headers // it is not in BeginProcessing because the first inputObject is needed for // the number of columns and column name if (_inputObject == null || _inputObject == AutomationNull.Value) { return; } _numberObjects++; if (!_isTHWritten) { InitializeResolvedNameMshParameters(); if (_resolvedNameMshParameters == null || _resolvedNameMshParameters.Count == 0) { return; } // if the As parameter is given as List if (_as.Equals("List", StringComparison.OrdinalIgnoreCase)) { // if more than one object,write the horizontal rule to put visual separator if (_numberObjects > 1) WriteObject("<tr><td><hr></td></tr>"); WriteListEntry(); } else // if the As parameter is Table, first we have to write the property names { WriteColumns(_resolvedNameMshParameters); StringBuilder THtag = new StringBuilder("<tr>"); // write the table header WriteTableHeader(THtag, _resolvedNameMshParameters); THtag.Append("</tr>"); WriteObject(THtag.ToString()); _isTHWritten = true; } } // if the As parameter is Table, write the property values if (_as.Equals("Table", StringComparison.OrdinalIgnoreCase)) { StringBuilder TRtag = new StringBuilder("<tr>"); // write the table row WriteTableRow(TRtag, _resolvedNameMshParameters); TRtag.Append("</tr>"); WriteObject(TRtag.ToString()); } } /// <summary> /// </summary> protected override void EndProcessing() { // if fragment,end with table WriteObject("</table>"); if (_postContent != null) WriteObject(_postContent, true); // if not fragment end with body and html also if (!_fragment) { WriteObject("</body></html>"); } } #region private /// <summary> /// List of incoming objects to compare. /// </summary> private bool _isTHWritten; private List<MshParameter> _propertyMshParameterList; private List<MshParameter> _resolvedNameMshParameters; // private string ResourcesBaseName = "ConvertHTMLStrings"; #endregion private } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Ssl { internal const int SSL_TLSEXT_ERR_OK = 0; internal const int OPENSSL_NPN_NEGOTIATED = 1; internal const int SSL_TLSEXT_ERR_ALERT_FATAL = 2; internal const int SSL_TLSEXT_ERR_NOACK = 3; internal delegate int SslCtxSetVerifyCallback(int preverify_ok, IntPtr x509_ctx); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureLibSslInitialized")] internal static extern void EnsureLibSslInitialized(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")] internal static extern IntPtr SslV2_3Method(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")] internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] internal static extern SslErrorCode SslGetError(SafeSslHandle ssl, int ret); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] internal static extern SslErrorCode SslGetError(IntPtr ssl, int ret); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetQuietShutdown")] internal static extern void SslSetQuietShutdown(SafeSslHandle ssl, int mode); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDestroy")] internal static extern void SslDestroy(IntPtr ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetConnectState")] internal static extern void SslSetConnectState(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAcceptState")] internal static extern void SslSetAcceptState(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")] internal static extern IntPtr SslGetVersion(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetTlsExtHostName")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SslSetTlsExtHostName(SafeSslHandle ssl, string host); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGet0AlpnSelected")] internal static extern void SslGetAlpnSelected(SafeSslHandle ssl, out IntPtr protocol, out int len); internal static byte[] SslGetAlpnSelected(SafeSslHandle ssl) { IntPtr protocol; int len; SslGetAlpnSelected(ssl, out protocol, out len); if (len == 0) return null; byte[] result = new byte[len]; Marshal.Copy(protocol, result, 0, len); return result; } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetSslConnectionInfo")] internal static extern bool GetSslConnectionInfo( SafeSslHandle ssl, out int dataCipherAlg, out int keyExchangeAlg, out int dataHashAlg, out int dataKeySize, out int hashKeySize); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite")] internal static extern unsafe int SslWrite(SafeSslHandle ssl, byte* buf, int num); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead")] internal static extern unsafe int SslRead(SafeSslHandle ssl, byte* buf, int num); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")] internal static extern int SslShutdown(IntPtr ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")] internal static extern int SslShutdown(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")] internal static extern void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake")] internal static extern int SslDoHandshake(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslStateOK")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsSslStateOK(SafeSslHandle ssl); // NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs. [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")] internal static extern unsafe int BioWrite(SafeBioHandle b, byte* data, int len); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")] internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertChain")] internal static extern SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerFinished")] internal static extern int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetFinished")] internal static extern int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSessionReused")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SslSessionReused(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")] internal static extern bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetClientCAList")] private static extern SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl); internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl) { Crypto.CheckValidOpenSslHandle(ssl); SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl); if (!handle.IsInvalid) { handle.SetParent(ssl); } return handle; } internal static bool AddExtraChainCertificates(SafeSslHandle sslContext, X509Chain chain) { Debug.Assert(chain != null, "X509Chain should not be null"); Debug.Assert(chain.ChainElements.Count > 0, "chain.Build should have already been called"); // Don't count the last item (the root) int stop = chain.ChainElements.Count - 1; // Don't include the first item (the cert whose private key we have) for (int i = 1; i < stop; i++) { SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain.ChainElements[i].Certificate.Handle); Crypto.CheckValidOpenSslHandle(dupCertHandle); if (!SslAddExtraChainCert(sslContext, dupCertHandle)) { Crypto.ErrClearError(); dupCertHandle.Dispose(); // we still own the safe handle; clean it up return false; } dupCertHandle.SetHandleAsInvalid(); // ownership has been transferred to sslHandle; do not free via this safe handle } return true; } internal static class SslMethods { internal static readonly IntPtr SSLv23_method = SslV2_3Method(); } internal enum SslErrorCode { SSL_ERROR_NONE = 0, SSL_ERROR_SSL = 1, SSL_ERROR_WANT_READ = 2, SSL_ERROR_WANT_WRITE = 3, SSL_ERROR_SYSCALL = 5, SSL_ERROR_ZERO_RETURN = 6, // NOTE: this SslErrorCode value doesn't exist in OpenSSL, but // we use it to distinguish when a renegotiation is pending. // Choosing an arbitrarily large value that shouldn't conflict // with any actual OpenSSL error codes SSL_ERROR_RENEGOTIATE = 29304 } } } namespace Microsoft.Win32.SafeHandles { internal sealed class SafeSslHandle : SafeHandle { private SafeBioHandle _readBio; private SafeBioHandle _writeBio; private bool _isServer; private bool _handshakeCompleted = false; public GCHandle AlpnHandle; public bool IsServer { get { return _isServer; } } public SafeBioHandle InputBio { get { return _readBio; } } public SafeBioHandle OutputBio { get { return _writeBio; } } internal void MarkHandshakeCompleted() { _handshakeCompleted = true; } public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer) { SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio(); SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio(); SafeSslHandle handle = Interop.Ssl.SslCreate(context); if (readBio.IsInvalid || writeBio.IsInvalid || handle.IsInvalid) { readBio.Dispose(); writeBio.Dispose(); handle.Dispose(); // will make IsInvalid==true if it's not already return handle; } handle._isServer = isServer; // SslSetBio will transfer ownership of the BIO handles to the SSL context try { readBio.TransferOwnershipToParent(handle); writeBio.TransferOwnershipToParent(handle); handle._readBio = readBio; handle._writeBio = writeBio; Interop.Ssl.SslSetBio(handle, readBio, writeBio); } catch (Exception exc) { // The only way this should be able to happen without thread aborts is if we hit OOMs while // manipulating the safe handles, in which case we may leak the bio handles. Debug.Fail("Unexpected exception while transferring SafeBioHandle ownership to SafeSslHandle", exc.ToString()); throw; } if (isServer) { Interop.Ssl.SslSetAcceptState(handle); } else { Interop.Ssl.SslSetConnectState(handle); } return handle; } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override void Dispose(bool disposing) { if (disposing) { _readBio?.Dispose(); _writeBio?.Dispose(); } if (AlpnHandle.IsAllocated) { AlpnHandle.Free(); } base.Dispose(disposing); } protected override bool ReleaseHandle() { if (_handshakeCompleted) { Disconnect(); } IntPtr h = handle; SetHandle(IntPtr.Zero); Interop.Ssl.SslDestroy(h); // will free the handles underlying _readBio and _writeBio return true; } private void Disconnect() { Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect"); int retVal = Interop.Ssl.SslShutdown(handle); // Here, we are ignoring checking for <0 return values from Ssl_Shutdown, // since the underlying memory bio is already disposed, we are not // interested in reading or writing to it. if (retVal == 0) { // Do a bi-directional shutdown. retVal = Interop.Ssl.SslShutdown(handle); } if (retVal < 0) { // Clean up the errors Interop.Crypto.ErrClearError(); } } private SafeSslHandle() : base(IntPtr.Zero, true) { } internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { handle = validSslPointer; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Outlining; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class ITextViewExtensions { /// <summary> /// Collects the content types in the view's buffer graph. /// </summary> public static ISet<IContentType> GetContentTypes(this ITextView textView) { return new HashSet<IContentType>( textView.BufferGraph.GetTextBuffers(_ => true).Select(b => b.ContentType)); } public static bool IsReadOnlyOnSurfaceBuffer(this ITextView textView, SnapshotSpan span) { var spansInView = textView.BufferGraph.MapUpToBuffer(span, SpanTrackingMode.EdgeInclusive, textView.TextBuffer); return spansInView.Any(spanInView => textView.TextBuffer.IsReadOnly(spanInView.Span)); } public static SnapshotPoint? GetCaretPoint(this ITextView textView, ITextBuffer subjectBuffer) { var caret = textView.Caret.Position; return textView.BufferGraph.MapUpOrDownToBuffer(caret.BufferPosition, subjectBuffer); } public static SnapshotPoint? GetCaretPoint(this ITextView textView, Predicate<ITextSnapshot> match) { var caret = textView.Caret.Position; var span = textView.BufferGraph.MapUpOrDownToFirstMatch(new SnapshotSpan(caret.BufferPosition, 0), match); if (span.HasValue) { return span.Value.Start; } else { return null; } } public static VirtualSnapshotPoint? GetVirtualCaretPoint(this ITextView textView, ITextBuffer subjectBuffer) { if (subjectBuffer == textView.TextBuffer) { return textView.Caret.Position.VirtualBufferPosition; } var mappedPoint = textView.BufferGraph.MapDownToBuffer( textView.Caret.Position.VirtualBufferPosition.Position, PointTrackingMode.Negative, subjectBuffer, PositionAffinity.Predecessor); return mappedPoint.HasValue ? new VirtualSnapshotPoint(mappedPoint.Value) : default(VirtualSnapshotPoint); } public static ITextBuffer GetBufferContainingCaret(this ITextView textView, string contentType = ContentTypeNames.RoslynContentType) { var point = GetCaretPoint(textView, s => s.ContentType.IsOfType(contentType)); return point.HasValue ? point.Value.Snapshot.TextBuffer : null; } public static SnapshotPoint? GetPositionInView(this ITextView textView, SnapshotPoint point) { return textView.BufferGraph.MapUpToSnapshot(point, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); } public static NormalizedSnapshotSpanCollection GetSpanInView(this ITextView textView, SnapshotSpan span) { return textView.BufferGraph.MapUpToSnapshot(span, SpanTrackingMode.EdgeInclusive, textView.TextSnapshot); } public static void SetSelection( this ITextView textView, VirtualSnapshotPoint anchorPoint, VirtualSnapshotPoint activePoint) { var isReversed = activePoint < anchorPoint; var start = isReversed ? activePoint : anchorPoint; var end = isReversed ? anchorPoint : activePoint; SetSelection(textView, new SnapshotSpan(start.Position, end.Position), isReversed); } public static void SetSelection( this ITextView textView, SnapshotSpan span, bool isReversed = false) { var spanInView = textView.GetSpanInView(span).Single(); textView.Selection.Select(spanInView, isReversed); textView.Caret.MoveTo(isReversed ? spanInView.Start : spanInView.End); } public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, SnapshotPoint point, IOutliningManagerService outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None) { return textView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(point), outliningManagerService, ensureSpanVisibleOptions); } public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, VirtualSnapshotPoint point, IOutliningManagerService outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None) { if (textView.IsClosed) { return false; } var pointInView = textView.GetPositionInView(point.Position); if (!pointInView.HasValue) { return false; } // If we were given an outlining service, we need to expand any outlines first, or else // the Caret.MoveTo won't land in the correct location if our target is inside a // collapsed outline. if (outliningManagerService != null) { var outliningManager = outliningManagerService.GetOutliningManager(textView); if (outliningManager != null) { outliningManager.ExpandAll(new SnapshotSpan(pointInView.Value, length: 0), match: _ => true); } } var newPosition = textView.Caret.MoveTo(new VirtualSnapshotPoint(pointInView.Value, point.VirtualSpaces)); // We use the caret's position in the view's current snapshot here in case something // changed text in response to a caret move (e.g. line commit) var spanInView = new SnapshotSpan(newPosition.BufferPosition, 0); textView.ViewScroller.EnsureSpanVisible(spanInView, ensureSpanVisibleOptions); return true; } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, Func<TTextView, TProperty> valueCreator) where TTextView : ITextView { return textView.GetOrCreateAutoClosingProperty(typeof(TProperty), valueCreator); } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, object key, Func<TTextView, TProperty> valueCreator) where TTextView : ITextView { TProperty value; GetOrCreateAutoClosingProperty(textView, key, valueCreator, out value); return value; } /// <summary> /// Gets or creates a view property that would go away when view gets closed /// </summary> public static bool GetOrCreateAutoClosingProperty<TProperty, TTextView>( this TTextView textView, object key, Func<TTextView, TProperty> valueCreator, out TProperty value) where TTextView : ITextView { return AutoClosingViewProperty<TProperty, TTextView>.GetOrCreateValue(textView, key, valueCreator, out value); } /// <summary> /// Gets or creates a per subject buffer property. /// </summary> public static TProperty GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, Func<TTextView, ITextBuffer, TProperty> valueCreator) where TTextView : class, ITextView { TProperty value; GetOrCreatePerSubjectBufferProperty(textView, subjectBuffer, key, valueCreator, out value); return value; } /// <summary> /// Gets or creates a per subject buffer property, returning true if it needed to create it. /// </summary> public static bool GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, Func<TTextView, ITextBuffer, TProperty> valueCreator, out TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); Contract.ThrowIfNull(valueCreator); return PerSubjectBufferProperty<TProperty, TTextView>.GetOrCreateValue(textView, subjectBuffer, key, valueCreator, out value); } public static bool TryGetPerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, out TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); return PerSubjectBufferProperty<TProperty, TTextView>.TryGetValue(textView, subjectBuffer, key, out value); } public static void AddPerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key, TProperty value) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); PerSubjectBufferProperty<TProperty, TTextView>.AddValue(textView, subjectBuffer, key, value); } public static void RemovePerSubjectBufferProperty<TProperty, TTextView>( this TTextView textView, ITextBuffer subjectBuffer, object key) where TTextView : class, ITextView { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(subjectBuffer); PerSubjectBufferProperty<TProperty, TTextView>.RemoveValue(textView, subjectBuffer, key); } public static bool TypeCharWasHandledStrangely( this ITextView textView, ITextBuffer subjectBuffer, char ch) { var finalCaretPositionOpt = textView.GetCaretPoint(subjectBuffer); if (finalCaretPositionOpt == null) { // Caret moved outside of our buffer. Don't want to handle this typed character. return true; } var previousPosition = finalCaretPositionOpt.Value.Position - 1; var inRange = previousPosition >= 0 && previousPosition < subjectBuffer.CurrentSnapshot.Length; if (!inRange) { // The character before the caret isn't even in the buffer we care about. Don't // handle this. return true; } if (subjectBuffer.CurrentSnapshot[previousPosition] != ch) { // The character that was typed is not in the buffer at the typed location. Don't // handle this character. return true; } return false; } public static int? GetDesiredIndentation(this ITextView textView, ISmartIndentationService smartIndentService, ITextSnapshotLine line) { var pointInView = textView.BufferGraph.MapUpToSnapshot( line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot); if (!pointInView.HasValue) { return null; } var lineInView = textView.TextSnapshot.GetLineFromPosition(pointInView.Value.Position); return smartIndentService.GetDesiredIndentation(textView, lineInView); } public static bool TryGetSurfaceBufferSpan( this ITextView textView, VirtualSnapshotSpan virtualSnapshotSpan, out VirtualSnapshotSpan surfaceBufferSpan) { // If we are already on the surface buffer, then there's no reason to attempt mappings // as we'll lose virtualness if (virtualSnapshotSpan.Snapshot.TextBuffer == textView.TextBuffer) { surfaceBufferSpan = virtualSnapshotSpan; return true; } // We have to map. We'll lose virtualness in this process because // mapping virtual points through projections is poorly defined. var targetSpan = textView.BufferGraph.MapUpToSnapshot( virtualSnapshotSpan.SnapshotSpan, SpanTrackingMode.EdgeExclusive, textView.TextSnapshot).FirstOrNullable(); if (targetSpan.HasValue) { surfaceBufferSpan = new VirtualSnapshotSpan(targetSpan.Value); return true; } surfaceBufferSpan = default(VirtualSnapshotSpan); return false; } /// <summary> /// Returns the span of the lines in subjectBuffer that is currently visible in the provided /// view. "extraLines" can be provided to get a span that encompasses some number of lines /// before and after the actual visible lines. /// </summary> public static SnapshotSpan? GetVisibleLinesSpan(this ITextView textView, ITextBuffer subjectBuffer, int extraLines = 0) { // If we're being called while the textview is actually in the middle of a layout, then // we can't proceed. Much of the text view state is unsafe to access (and will throw). if (textView.InLayout) { return null; } // Determine the range of text that is visible in the view. Then map this down to the // bufffer passed in. From that, determine the start/end line for the buffer that is in // view. var visibleSpan = textView.TextViewLines.FormattedSpan; var visibleSpansInBuffer = textView.BufferGraph.MapDownToBuffer(visibleSpan, SpanTrackingMode.EdgeInclusive, subjectBuffer); if (visibleSpansInBuffer.Count == 0) { return null; } var visibleStart = visibleSpansInBuffer.First().Start; var visibleEnd = visibleSpansInBuffer.Last().End; var snapshot = subjectBuffer.CurrentSnapshot; var startLine = visibleStart.GetContainingLine().LineNumber; var endLine = visibleEnd.GetContainingLine().LineNumber; startLine = Math.Max(startLine - extraLines, 0); endLine = Math.Min(endLine + extraLines, snapshot.LineCount - 1); var start = snapshot.GetLineFromLineNumber(startLine).Start; var end = snapshot.GetLineFromLineNumber(endLine).EndIncludingLineBreak; var span = new SnapshotSpan(snapshot, Span.FromBounds(start, end)); return span; } } }
/* * * 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 System.Collections.Generic; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Queries; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Util; using NUnit.Framework; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Tests.Queries { public class TermFilterTest : LuceneTestCase { [Test] public void TestCachability() { TermFilter a = TermFilter(@"field1", @"a"); var cachedFilters = new JCG.HashSet<Filter>(); cachedFilters.Add(a); assertTrue(@"Must be cached", cachedFilters.Contains(TermFilter(@"field1", @"a"))); assertFalse(@"Must not be cached", cachedFilters.Contains(TermFilter(@"field1", @"b"))); assertFalse(@"Must not be cached", cachedFilters.Contains(TermFilter(@"field2", @"a"))); } [Test] public void TestMissingTermAndField() { string fieldName = @"field1"; Directory rd = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, rd); Document doc = new Document(); doc.Add(NewStringField(fieldName, @"value1", Field.Store.NO)); w.AddDocument(doc); IndexReader reader = SlowCompositeReaderWrapper.Wrap(w.GetReader()); assertTrue(reader.Context is AtomicReaderContext); var context = (AtomicReaderContext)reader.Context; w.Dispose(); DocIdSet idSet = TermFilter(fieldName, @"value1").GetDocIdSet(context, context.AtomicReader.LiveDocs); assertNotNull(@"must not be null", idSet); DocIdSetIterator iter = idSet.GetIterator(); assertEquals(iter.NextDoc(), 0); assertEquals(iter.NextDoc(), DocIdSetIterator.NO_MORE_DOCS); idSet = TermFilter(fieldName, @"value2").GetDocIdSet(context, context.AtomicReader.LiveDocs); assertNull(@"must be null", idSet); idSet = TermFilter(@"field2", @"value1").GetDocIdSet(context, context.AtomicReader.LiveDocs); assertNull(@"must be null", idSet); reader.Dispose(); rd.Dispose(); } [Test] public void TestRandom() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); int num = AtLeast(100); var terms = new List<Term>(); for (int i = 0; i < num; i++) { string field = @"field" + i; string str = TestUtil.RandomRealisticUnicodeString(Random); terms.Add(new Term(field, str)); Document doc = new Document(); doc.Add(NewStringField(field, str, Field.Store.NO)); w.AddDocument(doc); } IndexReader reader = w.GetReader(); w.Dispose(); IndexSearcher searcher = NewSearcher(reader); int numQueries = AtLeast(10); for (int i = 0; i < numQueries; i++) { Term term = terms[Random.nextInt(num)]; TopDocs queryResult = searcher.Search(new TermQuery(term), reader.MaxDoc); MatchAllDocsQuery matchAll = new MatchAllDocsQuery(); TermFilter filter = TermFilter(term); TopDocs filterResult = searcher.Search(matchAll, filter, reader.MaxDoc); assertEquals(filterResult.TotalHits, queryResult.TotalHits); ScoreDoc[] scoreDocs = filterResult.ScoreDocs; for (int j = 0; j < scoreDocs.Length; j++) { assertEquals(scoreDocs[j].Doc, queryResult.ScoreDocs[j].Doc); } } reader.Dispose(); dir.Dispose(); } [Test] public void TestHashCodeAndEquals() { int num = AtLeast(100); for (int i = 0; i < num; i++) { string field1 = @"field" + i; string field2 = @"field" + i + num; string value1 = TestUtil.RandomRealisticUnicodeString(Random); string value2 = value1 + @"x"; TermFilter filter1 = TermFilter(field1, value1); TermFilter filter2 = TermFilter(field1, value2); TermFilter filter3 = TermFilter(field2, value1); TermFilter filter4 = TermFilter(field2, value2); var filters = new TermFilter[] { filter1, filter2, filter3, filter4 }; for (int j = 0; j < filters.Length; j++) { TermFilter termFilter = filters[j]; for (int k = 0; k < filters.Length; k++) { TermFilter otherTermFilter = filters[k]; if (j == k) { assertEquals(termFilter, otherTermFilter); assertEquals(termFilter.GetHashCode(), otherTermFilter.GetHashCode()); assertTrue(termFilter.Equals(otherTermFilter)); } else { assertFalse(termFilter.Equals(otherTermFilter)); } } } TermFilter filter5 = TermFilter(field2, value2); assertEquals(filter5, filter4); assertEquals(filter5.GetHashCode(), filter4.GetHashCode()); assertTrue(filter5.Equals(filter4)); assertEquals(filter5, filter4); assertTrue(filter5.Equals(filter4)); } } [Test] public void TestNoTerms() { try { new TermFilter(null); Assert.Fail(@"must fail - no term!"); } #pragma warning disable 168 catch (ArgumentException e) #pragma warning restore 168 { } try { new TermFilter(new Term(null)); Assert.Fail(@"must fail - no field!"); } #pragma warning disable 168 catch (ArgumentException e) #pragma warning restore 168 { } } [Test] public void TestToString() { var termsFilter = new TermFilter(new Term("field1", "a")); assertEquals(@"field1:a", termsFilter.ToString()); } private TermFilter TermFilter(string field, string value) { return TermFilter(new Term(field, value)); } private TermFilter TermFilter(Term term) { return new TermFilter(term); } } }
using System; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Events; using Umbraco.Core.Models; using umbraco; using umbraco.cms.businesslogic.web; namespace Umbraco.Web.Cache { /// <summary> /// Extension methods for <see cref="DistributedCache"/> /// </summary> internal static class DistributedCacheExtensions { #region Public access public static void RefreshPublicAccess(this DistributedCache dc) { dc.RefreshAll(DistributedCache.PublicAccessCacheRefresherGuid); } #endregion #region Application tree cache public static void RefreshAllApplicationTreeCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.ApplicationTreeCacheRefresherGuid); } #endregion #region Application cache public static void RefreshAllApplicationCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.ApplicationCacheRefresherGuid); } #endregion #region User type cache public static void RemoveUserTypeCache(this DistributedCache dc, int userTypeId) { dc.Remove(DistributedCache.UserTypeCacheRefresherGuid, userTypeId); } public static void RefreshUserTypeCache(this DistributedCache dc, int userTypeId) { dc.Refresh(DistributedCache.UserTypeCacheRefresherGuid, userTypeId); } public static void RefreshAllUserTypeCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.UserTypeCacheRefresherGuid); } #endregion #region User cache public static void RemoveUserCache(this DistributedCache dc, int userId) { dc.Remove(DistributedCache.UserCacheRefresherGuid, userId); } public static void RefreshUserCache(this DistributedCache dc, int userId) { dc.Refresh(DistributedCache.UserCacheRefresherGuid, userId); } public static void RefreshAllUserCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.UserCacheRefresherGuid); } #endregion #region User permissions cache public static void RemoveUserPermissionsCache(this DistributedCache dc, int userId) { dc.Remove(DistributedCache.UserPermissionsCacheRefresherGuid, userId); } public static void RefreshUserPermissionsCache(this DistributedCache dc, int userId) { dc.Refresh(DistributedCache.UserPermissionsCacheRefresherGuid, userId); } public static void RefreshAllUserPermissionsCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.UserPermissionsCacheRefresherGuid); } #endregion #region Template cache public static void RefreshTemplateCache(this DistributedCache dc, int templateId) { dc.Refresh(DistributedCache.TemplateRefresherGuid, templateId); } public static void RemoveTemplateCache(this DistributedCache dc, int templateId) { dc.Remove(DistributedCache.TemplateRefresherGuid, templateId); } #endregion #region Dictionary cache public static void RefreshDictionaryCache(this DistributedCache dc, int dictionaryItemId) { dc.Refresh(DistributedCache.DictionaryCacheRefresherGuid, dictionaryItemId); } public static void RemoveDictionaryCache(this DistributedCache dc, int dictionaryItemId) { dc.Remove(DistributedCache.DictionaryCacheRefresherGuid, dictionaryItemId); } #endregion #region Data type cache public static void RefreshDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType) { if (dataType == null) return; dc.RefreshByJson(DistributedCache.DataTypeCacheRefresherGuid, DataTypeCacheRefresher.SerializeToJsonPayload(dataType)); } public static void RemoveDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType) { if (dataType == null) return; dc.RefreshByJson(DistributedCache.DataTypeCacheRefresherGuid, DataTypeCacheRefresher.SerializeToJsonPayload(dataType)); } #endregion #region Page cache public static void RefreshAllPageCache(this DistributedCache dc) { dc.RefreshAll(DistributedCache.PageCacheRefresherGuid); } public static void RefreshPageCache(this DistributedCache dc, int documentId) { dc.Refresh(DistributedCache.PageCacheRefresherGuid, documentId); } public static void RefreshPageCache(this DistributedCache dc, params IContent[] content) { dc.Refresh(DistributedCache.PageCacheRefresherGuid, x => x.Id, content); } public static void RemovePageCache(this DistributedCache dc, params IContent[] content) { dc.Remove(DistributedCache.PageCacheRefresherGuid, x => x.Id, content); } public static void RemovePageCache(this DistributedCache dc, int documentId) { dc.Remove(DistributedCache.PageCacheRefresherGuid, documentId); } public static void RefreshUnpublishedPageCache(this DistributedCache dc, params IContent[] content) { dc.Refresh(DistributedCache.UnpublishedPageCacheRefresherGuid, x => x.Id, content); } public static void RemoveUnpublishedPageCache(this DistributedCache dc, params IContent[] content) { dc.Remove(DistributedCache.UnpublishedPageCacheRefresherGuid, x => x.Id, content); } public static void RemoveUnpublishedCachePermanently(this DistributedCache dc, params int[] contentIds) { dc.RefreshByJson(DistributedCache.UnpublishedPageCacheRefresherGuid, UnpublishedPageCacheRefresher.SerializeToJsonPayloadForPermanentDeletion(contentIds)); } #endregion #region Member cache public static void RefreshMemberCache(this DistributedCache dc, params IMember[] members) { dc.Refresh(DistributedCache.MemberCacheRefresherGuid, x => x.Id, members); } public static void RemoveMemberCache(this DistributedCache dc, params IMember[] members) { dc.Remove(DistributedCache.MemberCacheRefresherGuid, x => x.Id, members); } [Obsolete("Use the RefreshMemberCache with strongly typed IMember objects instead")] public static void RefreshMemberCache(this DistributedCache dc, int memberId) { dc.Refresh(DistributedCache.MemberCacheRefresherGuid, memberId); } [Obsolete("Use the RemoveMemberCache with strongly typed IMember objects instead")] public static void RemoveMemberCache(this DistributedCache dc, int memberId) { dc.Remove(DistributedCache.MemberCacheRefresherGuid, memberId); } #endregion #region Member group cache public static void RefreshMemberGroupCache(this DistributedCache dc, int memberGroupId) { dc.Refresh(DistributedCache.MemberGroupCacheRefresherGuid, memberGroupId); } public static void RemoveMemberGroupCache(this DistributedCache dc, int memberGroupId) { dc.Remove(DistributedCache.MemberGroupCacheRefresherGuid, memberGroupId); } #endregion #region Media Cache public static void RefreshMediaCache(this DistributedCache dc, params IMedia[] media) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayload(MediaCacheRefresher.OperationType.Saved, media)); } public static void RefreshMediaCacheAfterMoving(this DistributedCache dc, params MoveEventInfo<IMedia>[] media) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayloadForMoving(MediaCacheRefresher.OperationType.Saved, media)); } // clearing by Id will never work for load balanced scenarios for media since we require a Path // to clear all of the cache but the media item will be removed before the other servers can // look it up. Only here for legacy purposes. [Obsolete("Ensure to clear with other RemoveMediaCache overload")] public static void RemoveMediaCache(this DistributedCache dc, int mediaId) { dc.Remove(new Guid(DistributedCache.MediaCacheRefresherId), mediaId); } public static void RemoveMediaCacheAfterRecycling(this DistributedCache dc, params MoveEventInfo<IMedia>[] media) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayloadForMoving(MediaCacheRefresher.OperationType.Trashed, media)); } public static void RemoveMediaCachePermanently(this DistributedCache dc, params int[] mediaIds) { dc.RefreshByJson(DistributedCache.MediaCacheRefresherGuid, MediaCacheRefresher.SerializeToJsonPayloadForPermanentDeletion(mediaIds)); } #endregion #region Macro Cache public static void ClearAllMacroCacheOnCurrentServer(this DistributedCache dc) { // NOTE: The 'false' ensure that it will only refresh on the current server, not post to all servers dc.RefreshAll(DistributedCache.MacroCacheRefresherGuid, false); } public static void RefreshMacroCache(this DistributedCache dc, IMacro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RemoveMacroCache(this DistributedCache dc, IMacro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RefreshMacroCache(this DistributedCache dc, global::umbraco.cms.businesslogic.macro.Macro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RemoveMacroCache(this DistributedCache dc, global::umbraco.cms.businesslogic.macro.Macro macro) { if (macro == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } public static void RemoveMacroCache(this DistributedCache dc, macro macro) { if (macro == null || macro.Model == null) return; dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); } #endregion #region Document type cache public static void RefreshContentTypeCache(this DistributedCache dc, IContentType contentType) { if (contentType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(false, contentType)); } public static void RemoveContentTypeCache(this DistributedCache dc, IContentType contentType) { if (contentType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(true, contentType)); } #endregion #region Media type cache public static void RefreshMediaTypeCache(this DistributedCache dc, IMediaType mediaType) { if (mediaType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(false, mediaType)); } public static void RemoveMediaTypeCache(this DistributedCache dc, IMediaType mediaType) { if (mediaType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(true, mediaType)); } #endregion #region Media type cache public static void RefreshMemberTypeCache(this DistributedCache dc, IMemberType memberType) { if (memberType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(false, memberType)); } public static void RemoveMemberTypeCache(this DistributedCache dc, IMemberType memberType) { if (memberType == null) return; dc.RefreshByJson(DistributedCache.ContentTypeCacheRefresherGuid, ContentTypeCacheRefresher.SerializeToJsonPayload(true, memberType)); } #endregion #region Stylesheet Cache public static void RefreshStylesheetPropertyCache(this DistributedCache dc, global::umbraco.cms.businesslogic.web.StylesheetProperty styleSheetProperty) { if (styleSheetProperty == null) return; dc.Refresh(DistributedCache.StylesheetPropertyCacheRefresherGuid, styleSheetProperty.Id); } public static void RemoveStylesheetPropertyCache(this DistributedCache dc, global::umbraco.cms.businesslogic.web.StylesheetProperty styleSheetProperty) { if (styleSheetProperty == null) return; dc.Remove(DistributedCache.StylesheetPropertyCacheRefresherGuid, styleSheetProperty.Id); } public static void RefreshStylesheetCache(this DistributedCache dc, StyleSheet styleSheet) { if (styleSheet == null) return; dc.Refresh(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } public static void RemoveStylesheetCache(this DistributedCache dc, StyleSheet styleSheet) { if (styleSheet == null) return; dc.Remove(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } public static void RefreshStylesheetCache(this DistributedCache dc, Umbraco.Core.Models.Stylesheet styleSheet) { if (styleSheet == null) return; dc.Refresh(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } public static void RemoveStylesheetCache(this DistributedCache dc, Umbraco.Core.Models.Stylesheet styleSheet) { if (styleSheet == null) return; dc.Remove(DistributedCache.StylesheetCacheRefresherGuid, styleSheet.Id); } #endregion #region Domain Cache public static void RefreshDomainCache(this DistributedCache dc, IDomain domain) { if (domain == null) return; dc.Refresh(DistributedCache.DomainCacheRefresherGuid, domain.Id); } public static void RemoveDomainCache(this DistributedCache dc, IDomain domain) { if (domain == null) return; dc.Remove(DistributedCache.DomainCacheRefresherGuid, domain.Id); } #endregion #region Language Cache public static void RefreshLanguageCache(this DistributedCache dc, ILanguage language) { if (language == null) return; dc.Refresh(DistributedCache.LanguageCacheRefresherGuid, language.Id); } public static void RemoveLanguageCache(this DistributedCache dc, ILanguage language) { if (language == null) return; dc.Remove(DistributedCache.LanguageCacheRefresherGuid, language.Id); } public static void RefreshLanguageCache(this DistributedCache dc, global::umbraco.cms.businesslogic.language.Language language) { if (language == null) return; dc.Refresh(DistributedCache.LanguageCacheRefresherGuid, language.id); } public static void RemoveLanguageCache(this DistributedCache dc, global::umbraco.cms.businesslogic.language.Language language) { if (language == null) return; dc.Remove(DistributedCache.LanguageCacheRefresherGuid, language.id); } #endregion #region Xslt Cache public static void ClearXsltCacheOnCurrentServer(this DistributedCache dc) { if (UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration <= 0) return; ApplicationContext.Current.ApplicationCache.ClearCacheObjectTypes("MS.Internal.Xml.XPath.XPathSelectionIterator"); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AVFoundation; using AVKit; using Foundation; using UIKit; using Producer.Domain; using Producer.Shared; namespace Producer.iOS { public partial class ContentTvc : UITableViewController { bool saved => segmentControl.SelectedSegment == 1; MusicAsset activeAsset; NSIndexPath indexPathCache; List<MusicAsset> allAssets = new List<MusicAsset> (); List<MusicAsset> savedAssets = new List<MusicAsset> (); AVPlayerViewController playerViewController; public ContentTvc (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); NavigationItem.RightBarButtonItem = ProducerClient.Shared.UserRole.CanWrite () ? composeButton : null; NavigationController.SetToolbarHidden (true, false); ProducerClient.Shared.CurrentUserChanged += handleCurrentUserChanged; //AssetPlaybackManager.Shared.ReadyToPlay += handlePlaybackManagerReadyToPlay; AssetPersistenceManager.Shared.DidRestore += handlePersistanceManagerDidRestore; AssetPlaybackManager.Shared.CurrentItemChanged += handlePlaybackManagerCurrentItemChanged; AssetPersistenceManager.Shared.AssetDownloadStateChanged += handlePersistanceManagerAssetDownloadStateChanged; AssetPersistenceManager.Shared.AssetDownloadProgressChanged += handlePersistanceManagerAssetDownloadProgressChanged; } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); if (NavigationController.ToolbarHidden && AssetPlaybackManager.Shared.IsPlaying) { NavigationController.SetToolbarHidden (false, false); } // dismissing the AVPlayerViewController. if (playerViewController != null) { AssetPlaybackManager.Shared.TogglePlayback (null); playerViewController.Player = null; playerViewController = null; } } void handleCurrentUserChanged (object sender, User e) { Log.Debug (e?.ToString ()); BeginInvokeOnMainThread (() => NavigationItem.RightBarButtonItem = (e?.UserRole ?? UserRoles.General).CanWrite () ? composeButton : null); } void handleAvContentChanged (object sender, UserRoles e) => updateMusicAssets (); nfloat yCache; [Export ("scrollViewDidScroll:")] public void Scrolled (UIScrollView scrollView) { bool hide; var y = scrollView.ContentOffset.Y; hide = y > 0 && yCache > 0 && y - yCache > 0; if (hide && !NavigationController.ToolbarHidden && y - yCache > 12) { NavigationController.SetToolbarHidden (true, true); } else if (!hide && NavigationController.ToolbarHidden && y - yCache < -12) { if (AssetPlaybackManager.Shared.IsPlaying) { NavigationController.SetToolbarHidden (false, true); } } yCache = y; } partial void profileButtonClicked (NSObject sender) { if (ProducerClient.Shared.User == null) { var loginNc = Storyboard.Instantiate<LoginNc> (); PresentViewController (loginNc, true, null); } else { var userNc = Storyboard.Instantiate<UserNc> (); PresentViewController (userNc, true, null); } Log.Debug (RefreshControl?.ToString ()); } #region UITableViewDataSource & UITableViewDelegate public override nint RowsInSection (UITableView tableView, nint section) => saved ? savedAssets.Count : allAssets.Count; public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.Dequeue<ContentMusicTvCell> (indexPath); var asset = saved ? savedAssets [indexPath.Row] : allAssets [indexPath.Row]; cell.Tag = indexPath.Row; cell.SetData (asset.Music, AssetPersistenceManager.Shared.DownloadState (asset), ContentClient.Shared.Initialized); return cell; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { if (tableView.CellAt (indexPath) is ContentMusicTvCell cell) { tableView.DeselectRow (indexPath, true); var asset = saved ? savedAssets [indexPath.Row] : allAssets [indexPath.Row]; if (asset != null && (ContentClient.Shared.Initialized || AssetPersistenceManager.Shared.DownloadState (asset) == MusicAssetDownloadState.Downloaded)) { if (asset.Music.ContentType == AvContentTypes.Video) { playerViewController = new AVPlayerViewController (); PresentViewController (playerViewController, true, null); } // we're already on the main tread, this prevents hanging while playback starts BeginInvokeOnMainThread (() => { var playing = AssetPlaybackManager.Shared.TogglePlayback (asset); if (playing && indexPathCache != indexPath) Track.Play (asset.Music); if (indexPathCache != null && indexPathCache != indexPath && tableView.IndexPathsForVisibleRows.Contains (indexPathCache) && tableView.CellAt (indexPathCache) is ContentMusicTvCell oldCell) { oldCell.SetPlaying (false); } indexPathCache = indexPath; if (asset.Music.ContentType == AvContentTypes.Audio) { if (NavigationController.ToolbarHidden) { NavigationController.SetToolbarHidden (false, true); } cell.SetPlaying (playing); var items = ToolbarItems; items [0] = playing ? pauseButton : playButton; //items [2].Title = asset.Music.DisplayName; titleButton.Title = asset.Music.DisplayName; SetToolbarItems (items, true); } else if (!NavigationController.ToolbarHidden) { NavigationController.SetToolbarHidden (true, false); } }); } } } public override UITableViewRowAction [] EditActionsForRow (UITableView tableView, NSIndexPath indexPath) { var defaultAction = UITableViewRowAction.Create (UITableViewRowActionStyle.Normal, Strings.EmptyActionTitle, handleTableActionSave); defaultAction.BackgroundColor = UIColor.FromPatternImage (Images.TableActionSave); var moreAction = UITableViewRowAction.Create (UITableViewRowActionStyle.Normal, Strings.EmptyActionTitle, handleTableActionMore); moreAction.BackgroundColor = UIColor.FromPatternImage (Images.TableActionMore); return new UITableViewRowAction [] { defaultAction, moreAction }; } partial void accessoryButtonClicked (NSObject sender) { var button = sender as UIButton; if (button?.Tag >= 0 && allAssets.Count > button.Tag) { var asset = saved ? savedAssets [(int) button.Tag] : allAssets [(int) button.Tag]; if (asset != null) { //AssetPersistenceManager.Shared.MockDownloadAsset (asset); AssetPersistenceManager.Shared.DownloadAsset (asset); } } } partial void refreshValueChanged (NSObject sender) { Task.Run (() => ContentClient.Shared.GetAllAvContent ()); } partial void segmentControlValueChanged (NSObject sender) { TableView.ReloadData (); if (TableView.NumberOfRowsInSection (0) > 0) { var topIndex = NSIndexPath.FromRowSection (0, 0); TableView.ScrollToRow (topIndex, UITableViewScrollPosition.Top, false); } if (Editing) { SetEditing (false, false); } NavigationItem.RightBarButtonItem = saved ? EditButtonItem : ProducerClient.Shared.UserRole.CanWrite () ? composeButton : null; } partial void togglePlayClicked (NSObject sender) { if (indexPathCache != null) { RowSelected (TableView, indexPathCache); } } #endregion #region TableCell Action Handlers void handleTableActionSave (UITableViewRowAction action, NSIndexPath indexPath) { var asset = saved ? savedAssets [indexPath.Row] : allAssets [indexPath.Row]; Log.Debug ($"Save: {asset?.Music?.DisplayName}"); } void handleTableActionMore (UITableViewRowAction action, NSIndexPath indexPath) { activeAsset = saved ? savedAssets [indexPath.Row] : allAssets [indexPath.Row]; Log.Debug ($"More: {activeAsset?.Music?.DisplayName}"); var alertController = UIAlertController.Create (activeAsset.Music.DisplayName, null, UIAlertControllerStyle.ActionSheet); var downloadState = AssetPersistenceManager.Shared.DownloadState (activeAsset); alertController.AddAction (UIAlertAction.Create ("Share", UIAlertActionStyle.Default, handleAlertControllerActionShare)); switch (downloadState) { case MusicAssetDownloadState.NotDownloaded: alertController.AddAction (UIAlertAction.Create ("Download", UIAlertActionStyle.Default, handleAlertControllerActionDownload)); break; case MusicAssetDownloadState.Downloading: alertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Destructive, handleAlertControllerActionCancel)); break; case MusicAssetDownloadState.Downloaded: alertController.AddAction (UIAlertAction.Create ("Delete", UIAlertActionStyle.Destructive, handleAlertControllerActionDelete)); break; } alertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, handleAlertControllerActionDismiss)); PresentViewController (alertController, true, null); } void handleAlertControllerActionDismiss (UIAlertAction obj) => DismissViewController (true, null); void handleAlertControllerActionShare (UIAlertAction obj) => throw new NotImplementedException (); void handleAlertControllerActionDownload (UIAlertAction obj) { if (activeAsset != null) { Log.Debug ($"Starting Download | {activeAsset.Music.DisplayName}"); AssetPersistenceManager.Shared.DownloadAsset (activeAsset); } } void handleAlertControllerActionCancel (UIAlertAction obj) { if (activeAsset != null) { Log.Debug ($"Cancelling Download | {activeAsset.Music.DisplayName}"); AssetPersistenceManager.Shared.CancelDownload (activeAsset); } } void handleAlertControllerActionDelete (UIAlertAction obj) { if (activeAsset != null) { Log.Debug ($"Deleting Download | {activeAsset.Music.DisplayName}"); AssetPersistenceManager.Shared.DeleteAsset (activeAsset); } } #endregion #region PersistanceManager Handlers void updateMusicAssets () { Log.Debug ("Load Content"); if (allAssets?.Count == 0 && ContentClient.Shared.AvContent.Count > 0) { allAssets = ContentClient.Shared.AvContent [UserRoles.General].Where (m => m.HasId && m.HasRemoteAssetUri) .Select (s => AssetPersistenceManager.Shared.GetMusicAsset (s)) .ToList (); } else { var newAssets = ContentClient.Shared.AvContent [UserRoles.General].Where (m => m.HasId && m.HasRemoteAssetUri && !allAssets.Any (ma => ma.Id == m.Id)) .Select (s => AssetPersistenceManager.Shared.GetMusicAsset (s)); allAssets.AddRange (newAssets); allAssets.RemoveAll (ma => !ContentClient.Shared.AvContent [UserRoles.General].Any (a => a.Id == ma.Id)); } allAssets?.Sort ((x, y) => y.Music.Timestamp.CompareTo (x.Music.Timestamp)); BeginInvokeOnMainThread (() => { TableView.ReloadData (); if (RefreshControl?.Refreshing ?? false) { RefreshControl.EndRefreshing (); } }); } void handlePersistanceManagerDidRestore (object sender, EventArgs e) { updateMusicAssets (); ContentClient.Shared.AvContentChanged += handleAvContentChanged; } void handlePersistanceManagerAssetDownloadStateChanged (object sender, MusicAssetDownloadStateChangeArgs e) { Log.Debug ($"{e.Music.DisplayName} | {e.State}"); BeginInvokeOnMainThread (() => { var cell = TableView.VisibleCells.FirstOrDefault (c => c.TextLabel.Text == e.Music.DisplayName); if (cell != null) { TableView.ReloadRows (new NSIndexPath [] { TableView.IndexPathForCell (cell) }, UITableViewRowAnimation.Automatic); } }); } void handlePersistanceManagerAssetDownloadProgressChanged (object sender, MusicAssetDownloadProgressChangeArgs e) { Log.Debug ($"{e.Music.DisplayName} | {e.Progress}"); BeginInvokeOnMainThread (() => { var cell = TableView.VisibleCells.FirstOrDefault (c => c.TextLabel.Text == e.Music.DisplayName) as ContentMusicTvCell; cell?.UpdateDownloadProgress ((nfloat) e.Progress); }); } #endregion #region PlaybackManager Handlers void handlePlaybackManagerCurrentItemChanged (object sender, AVPlayer player) { Log.Debug ($"{sender}"); var playbackManager = sender as AssetPlaybackManager; if (playerViewController != null && player.CurrentItem != null && playbackManager?.CurrentAsset.Music.ContentType == AvContentTypes.Video) { playerViewController.Player = player; } } #endregion public override UIStatusBarStyle PreferredStatusBarStyle () => UIStatusBarStyle.LightContent; } }
// // 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.Sql; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Management.Sql { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public static partial class ServerDisasterRecoveryConfigurationOperationsExtensions { /// <summary> /// Begins creating a new or updating an existing Azure SQL Server /// disaster recovery configuration. To determine the status of the /// operation call /// GetServerDisasterRecoveryConfigurationOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL Server disaster recovery /// configuration to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Server /// disaster recovery configuration. /// </param> /// <returns> /// Response for long running Azure Sql server disaster recovery /// configuration operation. /// </returns> public static ServerDisasterRecoveryConfigurationCreateOrUpdateResponse BeginCreateOrUpdate(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, ServerDisasterRecoveryConfigurationCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IServerDisasterRecoveryConfigurationOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins creating a new or updating an existing Azure SQL Server /// disaster recovery configuration. To determine the status of the /// operation call /// GetServerDisasterRecoveryConfigurationOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL Server disaster recovery /// configuration to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Server /// disaster recovery configuration. /// </param> /// <returns> /// Response for long running Azure Sql server disaster recovery /// configuration operation. /// </returns> public static Task<ServerDisasterRecoveryConfigurationCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, ServerDisasterRecoveryConfigurationCreateOrUpdateParameters parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, parameters, CancellationToken.None); } /// <summary> /// Creates a new or updates an existing Azure SQL Server disaster /// recovery configuration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL Server disaster recovery /// configuration to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Server /// disaster recovery configuration. /// </param> /// <returns> /// Response for long running Azure Sql server disaster recovery /// configuration operation. /// </returns> public static ServerDisasterRecoveryConfigurationCreateOrUpdateResponse CreateOrUpdate(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, ServerDisasterRecoveryConfigurationCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IServerDisasterRecoveryConfigurationOperations)s).CreateOrUpdateAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new or updates an existing Azure SQL Server disaster /// recovery configuration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL Server disaster recovery /// configuration to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Server /// disaster recovery configuration. /// </param> /// <returns> /// Response for long running Azure Sql server disaster recovery /// configuration operation. /// </returns> public static Task<ServerDisasterRecoveryConfigurationCreateOrUpdateResponse> CreateOrUpdateAsync(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, ServerDisasterRecoveryConfigurationCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, parameters, CancellationToken.None); } /// <summary> /// Deletes the Azure SQL server disaster recovery configuration with /// the given name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to be deleted. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName) { return Task.Factory.StartNew((object s) => { return ((IServerDisasterRecoveryConfigurationOperations)s).DeleteAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the Azure SQL server disaster recovery configuration with /// the given name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to be deleted. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName) { return operations.DeleteAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, CancellationToken.None); } /// <summary> /// Begins failover for the Azure SQL server disaster recovery /// configuration with the given name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to start failover. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Failover(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName) { return Task.Factory.StartNew((object s) => { return ((IServerDisasterRecoveryConfigurationOperations)s).FailoverAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins failover for the Azure SQL server disaster recovery /// configuration with the given name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to start failover. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> FailoverAsync(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName) { return operations.FailoverAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, CancellationToken.None); } /// <summary> /// Begins failover for the Azure SQL server disaster recovery /// configuration with the given name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to start failover. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse FailoverAllowDataLoss(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName) { return Task.Factory.StartNew((object s) => { return ((IServerDisasterRecoveryConfigurationOperations)s).FailoverAllowDataLossAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins failover for the Azure SQL server disaster recovery /// configuration with the given name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to start failover. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> FailoverAllowDataLossAsync(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName) { return operations.FailoverAllowDataLossAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, CancellationToken.None); } /// <summary> /// Returns information about an Azure SQL Server disaster recovery /// configurations. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to be retrieved. /// </param> /// <returns> /// Represents the response to a get server disaster recovery /// configuration request. /// </returns> public static ServerDisasterRecoveryConfigurationGetResponse Get(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName) { return Task.Factory.StartNew((object s) => { return ((IServerDisasterRecoveryConfigurationOperations)s).GetAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns information about an Azure SQL Server disaster recovery /// configurations. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to be retrieved. /// </param> /// <returns> /// Represents the response to a get server disaster recovery /// configuration request. /// </returns> public static Task<ServerDisasterRecoveryConfigurationGetResponse> GetAsync(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName) { return operations.GetAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, CancellationToken.None); } /// <summary> /// Gets the status of an Azure Sql Server disaster recovery /// configuration create or update operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <returns> /// Response for long running Azure Sql server disaster recovery /// configuration operation. /// </returns> public static ServerDisasterRecoveryConfigurationCreateOrUpdateResponse GetServerDisasterRecoveryConfigurationOperationStatus(this IServerDisasterRecoveryConfigurationOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IServerDisasterRecoveryConfigurationOperations)s).GetServerDisasterRecoveryConfigurationOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of an Azure Sql Server disaster recovery /// configuration create or update operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <returns> /// Response for long running Azure Sql server disaster recovery /// configuration operation. /// </returns> public static Task<ServerDisasterRecoveryConfigurationCreateOrUpdateResponse> GetServerDisasterRecoveryConfigurationOperationStatusAsync(this IServerDisasterRecoveryConfigurationOperations operations, string operationStatusLink) { return operations.GetServerDisasterRecoveryConfigurationOperationStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Returns information about Azure SQL Server disaster recovery /// configurations. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <returns> /// Represents the response to a List Azure Sql Server disaster /// recovery configuration request. /// </returns> public static ServerDisasterRecoveryConfigurationListResponse List(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName) { return Task.Factory.StartNew((object s) => { return ((IServerDisasterRecoveryConfigurationOperations)s).ListAsync(resourceGroupName, serverName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns information about Azure SQL Server disaster recovery /// configurations. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerDisasterRecoveryConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <returns> /// Represents the response to a List Azure Sql Server disaster /// recovery configuration request. /// </returns> public static Task<ServerDisasterRecoveryConfigurationListResponse> ListAsync(this IServerDisasterRecoveryConfigurationOperations operations, string resourceGroupName, string serverName) { return operations.ListAsync(resourceGroupName, serverName, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Collections; namespace System.DirectoryServices.ActiveDirectory { public class ActiveDirectorySiteLinkCollection : CollectionBase { internal DirectoryEntry de = null; internal bool initialized = false; internal DirectoryContext context = null; internal ActiveDirectorySiteLinkCollection() { } public ActiveDirectorySiteLink this[int index] { get => (ActiveDirectorySiteLink)InnerList[index]; set { ActiveDirectorySiteLink link = (ActiveDirectorySiteLink)value; if (link == null) throw new ArgumentNullException(nameof(value)); if (!link.existing) throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, link.Name)); if (!Contains(link)) List[index] = link; else throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, link), nameof(value)); } } public int Add(ActiveDirectorySiteLink link) { if (link == null) throw new ArgumentNullException(nameof(link)); if (!link.existing) throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, link.Name)); if (!Contains(link)) return List.Add(link); else throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, link), nameof(link)); } public void AddRange(ActiveDirectorySiteLink[] links) { if (links == null) throw new ArgumentNullException(nameof(links)); for (int i = 0; i < links.Length; i = i + 1) this.Add(links[i]); } public void AddRange(ActiveDirectorySiteLinkCollection links) { if (links == null) throw new ArgumentNullException(nameof(links)); int count = links.Count; for (int i = 0; i < count; i++) this.Add(links[i]); } public bool Contains(ActiveDirectorySiteLink link) { if (link == null) throw new ArgumentNullException(nameof(link)); if (!link.existing) throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, link.Name)); string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName); for (int i = 0; i < InnerList.Count; i++) { ActiveDirectorySiteLink tmp = (ActiveDirectorySiteLink)InnerList[i]; string tmpDn = (string)PropertyManager.GetPropertyValue(tmp.context, tmp.cachedEntry, PropertyManager.DistinguishedName); if (Utils.Compare(tmpDn, dn) == 0) { return true; } } return false; } public void CopyTo(ActiveDirectorySiteLink[] array, int index) { List.CopyTo(array, index); } public int IndexOf(ActiveDirectorySiteLink link) { if (link == null) throw new ArgumentNullException(nameof(link)); if (!link.existing) throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, link.Name)); string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName); for (int i = 0; i < InnerList.Count; i++) { ActiveDirectorySiteLink tmp = (ActiveDirectorySiteLink)InnerList[i]; string tmpDn = (string)PropertyManager.GetPropertyValue(tmp.context, tmp.cachedEntry, PropertyManager.DistinguishedName); if (Utils.Compare(tmpDn, dn) == 0) { return i; } } return -1; } public void Insert(int index, ActiveDirectorySiteLink link) { if (link == null) throw new ArgumentNullException("value"); if (!link.existing) throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, link.Name)); if (!Contains(link)) List.Insert(index, link); else throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, link), nameof(link)); } public void Remove(ActiveDirectorySiteLink link) { if (link == null) throw new ArgumentNullException(nameof(link)); if (!link.existing) throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, link.Name)); string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName); for (int i = 0; i < InnerList.Count; i++) { ActiveDirectorySiteLink tmp = (ActiveDirectorySiteLink)InnerList[i]; string tmpDn = (string)PropertyManager.GetPropertyValue(tmp.context, tmp.cachedEntry, PropertyManager.DistinguishedName); if (Utils.Compare(tmpDn, dn) == 0) { List.Remove(tmp); return; } } // something that does not exist in the collectio throw new ArgumentException(SR.Format(SR.NotFoundInCollection, link), nameof(link)); } protected override void OnClearComplete() { // if the property exists, clear it out if (initialized) { try { if (de.Properties.Contains("siteLinkList")) de.Properties["siteLinkList"].Clear(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } protected override void OnInsertComplete(int index, object value) { if (initialized) { ActiveDirectorySiteLink link = (ActiveDirectorySiteLink)value; string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName); try { de.Properties["siteLinkList"].Add(dn); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } protected override void OnRemoveComplete(int index, object value) { ActiveDirectorySiteLink link = (ActiveDirectorySiteLink)value; string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName); try { de.Properties["siteLinkList"].Remove(dn); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } protected override void OnSetComplete(int index, object oldValue, object newValue) { ActiveDirectorySiteLink newLink = (ActiveDirectorySiteLink)newValue; string newdn = (string)PropertyManager.GetPropertyValue(newLink.context, newLink.cachedEntry, PropertyManager.DistinguishedName); try { de.Properties["siteLinkList"][index] = newdn; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } protected override void OnValidate(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (!(value is ActiveDirectorySiteLink)) throw new ArgumentException(nameof(value)); if (!((ActiveDirectorySiteLink)value).existing) throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, ((ActiveDirectorySiteLink)value).Name)); } } }
//! \file ImageAG.cs //! \date Sun May 10 23:53:34 2015 //! \brief Masys Enhanced Game Unit image format. // // Copyright (C) 2015 by morkt // // 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.ComponentModel.Composition; using System.Windows.Media; using System.IO; using GameRes.Utility; namespace GameRes.Formats.Megu { [Export(typeof(ImageFormat))] public class AgFormat : ImageFormat { public override string Tag { get { return "ACG"; } } public override string Description { get { return "Masys image format"; } } public override uint Signature { get { return 0x00644741u; } } // 'AGd' public override ImageMetaData ReadMetaData (Stream stream) { using (var file = new ArcView.Reader (stream)) { file.ReadUInt32(); var info = new ImageMetaData(); info.Width = file.ReadUInt32(); info.Height = file.ReadUInt32(); file.BaseStream.Position = 0x38; int alpha_size = file.ReadInt32(); info.BPP = 0 == alpha_size ? 24 : 32; return info; } } public override ImageData Read (Stream stream, ImageMetaData info) { var reader = new AgReader (stream, info); reader.Unpack(); return ImageData.Create (info, reader.Format, null, reader.Data); } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("AgFormat.Write not implemented"); } } internal class AgReader { byte[] in1; byte[] in2; byte[] in3; byte[] in4; byte[] in5; byte[] m_alpha; byte[] m_output; int m_width; int m_height; int m_pixel_size; byte[] m_first = new byte[3]; public byte[] Data { get { return m_output; } } public PixelFormat Format { get; private set; } public AgReader (Stream stream, ImageMetaData info) { m_width = (int)info.Width; m_height = (int)info.Height; stream.Position = 0x0c; using (var input = new ArcView.Reader (stream)) { uint offset1 = input.ReadUInt32(); int size1 = input.ReadInt32(); uint offset2 = input.ReadUInt32(); int size2 = input.ReadInt32(); uint offset3 = input.ReadUInt32(); int size3 = input.ReadInt32(); uint offset4 = input.ReadUInt32(); int size4 = input.ReadInt32(); uint offset5 = input.ReadUInt32(); int size5 = input.ReadInt32(); uint offset6 = input.ReadUInt32(); int size6 = input.ReadInt32(); input.Read (m_first, 0, 3); if (size1 != 0) in1 = ReadSection (stream, offset1, size1); if (size2 != 0) in2 = ReadSection (stream, offset2, size2); if (size3 != 0) in3 = ReadSection (stream, offset3, size3); if (size4 != 0) in4 = ReadSection (stream, offset4, size4); if (size5 != 0) in5 = ReadSection (stream, offset5, size5); if (size6 != 0) { input.BaseStream.Position = offset6; m_alpha = new byte[m_height*m_width]; RleDecode (input, m_alpha); Format = PixelFormats.Bgra32; m_pixel_size = 4; } else { Format = PixelFormats.Bgr24; m_pixel_size = 3; } m_output = new byte[m_width*m_height*m_pixel_size]; } } static private byte[] ReadSection (Stream input, long offset, int size) { input.Position = offset; var buf = new byte[size + 4]; if (size != input.Read (buf, 0, size)) throw new InvalidFormatException ("Unexpected end of file"); return buf; } public void Unpack () { int v20 = 1; int src1 = 0; uint v25 = LittleEndian.ToUInt32 (in1, src1); src1 += 4; int v5 = 1; int src2 = 0; uint v24 = LittleEndian.ToUInt32 (in2, src2); src2 += 4; int v4 = 1; int src3 = 0; uint v23 = LittleEndian.ToUInt32 (in3, src3); src3 += 4; int v3 = 0; int src4 = 0; uint v22 = LittleEndian.ToUInt32 (in4, src4); src4 += 4; int v19 = 0; int src5 = 0; uint v21 = LittleEndian.ToUInt32 (in5, src5); src5 += 4; byte B; byte G; byte R; int stride = m_width * m_pixel_size; for (int y = 0; y < m_height; ++y) { int dst = y * stride; for (int x = 0; x < stride; x += m_pixel_size) { if (0 != (v20 & v25)) { B = (byte)(v21 >> v19); v19 += 8; if (32 == v19) { v21 = LittleEndian.ToUInt32 (in5, src5); src5 += 4; v19 = 0; } } else { if (0 != (v4 & v23)) { B = m_first[0]; } else { B = (byte)((v22 >> v3) & 0xF); v3 += 4; if (32 == v3) { v22 = LittleEndian.ToUInt32 (in4, src4); src4 += 4; v3 = 0; } ++B; if (0 != (v5 & v24)) B = (byte)(m_first[0] - B); else B += m_first[0]; v5 <<= 1; if (0 == v5) { v5 = 1; v24 = LittleEndian.ToUInt32 (in2, src2); src2 += 4; } } v4 <<= 1; if (0 == v4) { v4 = 1; v23 = LittleEndian.ToUInt32 (in3, src3); src3 += 4; } } v20 <<= 1; if (0 == v20) { v25 = LittleEndian.ToUInt32 (in1, src1); src1 += 4; v20 = 1; } if (0 != (v20 & v25)) { G = (byte)(v21 >> v19); v19 += 8; if (32 == v19) { v21 = LittleEndian.ToUInt32 (in5, src5); src5 += 4; v19 = 0; } } else { if (0 != (v4 & v23)) { G = m_first[1]; } else { G = (byte)((v22 >> v3) & 0xF); v3 += 4; if (32 == v3) { v22 = LittleEndian.ToUInt32 (in4, src4); src4 += 4; v3 = 0; } ++G; if (0 != (v5 & v24)) G = (byte)(m_first[1] - G); else G += m_first[1]; v5 <<= 1; if (0 == v5) { v5 = 1; v24 = LittleEndian.ToUInt32 (in2, src2); src2 += 4; } } v4 <<= 1; if (0 == v4) { v4 = 1; v23 = LittleEndian.ToUInt32 (in3, src3); src3 += 4; } } v20 <<= 1; if (0 == v20) { v25 = LittleEndian.ToUInt32 (in1, src1); src1 += 4; v20 = 1; } if (0 != (v20 & v25)) { R = (byte)(v21 >> v19); v19 += 8; if (32 == v19) { v21 = LittleEndian.ToUInt32 (in5, src5); src5 += 4; v19 = 0; } } else { if (0 != (v4 & v23)) { R = m_first[2]; } else { R = (byte)((v22 >> v3) & 0xF); v3 += 4; if (32 == v3) { v22 = LittleEndian.ToUInt32 (in4, src4); src4 += 4; v3 = 0; } ++R; if (0 != (v5 & v24)) R = (byte)(m_first[2] - R); else R += m_first[2]; v5 <<= 1; if (0 == v5) { v5 = 1; v24 = LittleEndian.ToUInt32 (in2, src2); src2 += 4; } } v4 <<= 1; if (0 == v4) { v4 = 1; v23 = LittleEndian.ToUInt32 (in3, src3); src3 += 4; } } v20 <<= 1; if (0 == v20) { v25 = LittleEndian.ToUInt32 (in1, src1); src1 += 4; v20 = 1; } m_output[dst+x] = B; m_output[dst+x+1] = G; m_output[dst+x+2] = R; m_first[0] = B; m_first[1] = G; m_first[2] = R; } m_first[0] = m_output[dst]; m_first[1] = m_output[dst+1]; m_first[2] = m_output[dst+2]; } if (m_alpha != null) ApplyAlpha(); } private void ApplyAlpha () { int src = 0; for (int i = 3; i < m_output.Length; i += 4) { int alpha = Math.Min (m_alpha[src++]*0xff/0x40, 0xff); m_output[i] = (byte)alpha; } } private static void RleDecode (BinaryReader src, byte[] dst_buf) { int remaining = dst_buf.Length; int dst = 0; while (remaining > 0) { byte v = src.ReadByte(); int count; if (0 != (v & 0x80)) { v &= 0x7F; count = src.ReadUInt16(); for (int j = 0; j < count; ++j) { dst_buf[dst++] = v; } } else { dst_buf[dst++] = v; count = 1; } remaining -= count; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { 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 Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// ExpressRouteCircuitPeeringsOperations operations. /// </summary> internal partial class ExpressRouteCircuitPeeringsOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteCircuitPeeringsOperations { /// <summary> /// Initializes a new instance of the ExpressRouteCircuitPeeringsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ExpressRouteCircuitPeeringsOperations(NetworkManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// The delete peering operation deletes the specified peering from the /// ExpressRouteCircuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse response = await BeginDeleteWithHttpMessagesAsync( resourceGroupName, circuitName, peeringName, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(response, customHeaders, cancellationToken); } /// <summary> /// The delete peering operation deletes the specified peering from the /// ExpressRouteCircuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (peeringName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "peeringName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("peeringName", peeringName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{circuitName}", Uri.EscapeDataString(circuitName)); url = url.Replace("{peeringName}", Uri.EscapeDataString(peeringName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("DELETE"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200 && (int)statusCode != 202 && (int)statusCode != 204) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The GET peering operation retrieves the specified authorization from the /// ExpressRouteCircuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (peeringName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "peeringName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("peeringName", peeringName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Get", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{circuitName}", Uri.EscapeDataString(circuitName)); url = url.Replace("{peeringName}", Uri.EscapeDataString(peeringName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ExpressRouteCircuitPeering>(); 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) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The Put Pering operation creates/updates an peering in the specified /// ExpressRouteCircuits /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='peeringParameters'> /// Parameters supplied to the create/update ExpressRouteCircuit Peering /// operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ExpressRouteCircuitPeering> response = await BeginCreateOrUpdateWithHttpMessagesAsync( resourceGroupName, circuitName, peeringName, peeringParameters, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync<ExpressRouteCircuitPeering>(response, customHeaders, cancellationToken); } /// <summary> /// The Put Pering operation creates/updates an peering in the specified /// ExpressRouteCircuits /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='peeringParameters'> /// Parameters supplied to the create/update ExpressRouteCircuit Peering /// operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (peeringName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "peeringName"); } if (peeringParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "peeringParameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("peeringName", peeringName); tracingParameters.Add("peeringParameters", peeringParameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{circuitName}", Uri.EscapeDataString(circuitName)); url = url.Replace("{peeringName}", Uri.EscapeDataString(peeringName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 = JsonConvert.SerializeObject(peeringParameters, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200 && (int)statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ExpressRouteCircuitPeering>(); 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) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(responseContent, this.Client.DeserializationSettings); } // Deserialize Response if ((int)statusCode == 201) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The List peering operation retrieves all the peerings in an /// ExpressRouteCircuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the curcuit. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "List", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{circuitName}", Uri.EscapeDataString(circuitName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>(); 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) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The List peering operation retrieves all the peerings in an /// ExpressRouteCircuit. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "ListNext", tracingParameters); } // Construct URL string url = "{nextLink}"; url = url.Replace("{nextLink}", nextPageLink); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>(); 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) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
using System; using SubSonic.Schema; using SubSonic.DataProviders; using System.Data; namespace Solution.DataAccess.DataModel { /// <summary> /// Table: OutWork_D /// Primary Key: Id /// </summary> public class OutWork_DStructs: DatabaseTable { public OutWork_DStructs(IDataProvider provider):base("OutWork_D",provider){ ClassName = "OutWork_D"; SchemaName = "dbo"; Columns.Add(new DatabaseColumn("Id", this) { IsPrimaryKey = true, DataType = DbType.Int64, IsNullable = false, AutoIncrement = true, IsForeignKey = false, MaxLength = 0, PropertyName = "Id" }); Columns.Add(new DatabaseColumn("bill_id", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 20, PropertyName = "bill_id" }); Columns.Add(new DatabaseColumn("emp_id", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 12, PropertyName = "emp_id" }); Columns.Add(new DatabaseColumn("join_id", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "join_id" }); Columns.Add(new DatabaseColumn("depart_id", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 30, PropertyName = "depart_id" }); Columns.Add(new DatabaseColumn("bill_date", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "bill_date" }); Columns.Add(new DatabaseColumn("begin_time", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "begin_time" }); Columns.Add(new DatabaseColumn("end_time", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "end_time" }); Columns.Add(new DatabaseColumn("work_type", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 10, PropertyName = "work_type" }); Columns.Add(new DatabaseColumn("work_days", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "work_days" }); Columns.Add(new DatabaseColumn("status_id", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "status_id" }); Columns.Add(new DatabaseColumn("leave_id", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 10, PropertyName = "leave_id" }); Columns.Add(new DatabaseColumn("rate", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "rate" }); Columns.Add(new DatabaseColumn("checker", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 16, PropertyName = "checker" }); Columns.Add(new DatabaseColumn("check_date", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "check_date" }); Columns.Add(new DatabaseColumn("op_user", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "op_user" }); Columns.Add(new DatabaseColumn("op_date", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "op_date" }); Columns.Add(new DatabaseColumn("audit", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "audit" }); Columns.Add(new DatabaseColumn("memo", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "memo" }); Columns.Add(new DatabaseColumn("outwork_type", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "outwork_type" }); Columns.Add(new DatabaseColumn("outwork_addr", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "outwork_addr" }); Columns.Add(new DatabaseColumn("transportation", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 20, PropertyName = "transportation" }); Columns.Add(new DatabaseColumn("Re_date", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "Re_date" }); Columns.Add(new DatabaseColumn("Start_ag", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "Start_ag" }); Columns.Add(new DatabaseColumn("re_ag", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "re_ag" }); Columns.Add(new DatabaseColumn("peers", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "peers" }); Columns.Add(new DatabaseColumn("Hostel", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "Hostel" }); Columns.Add(new DatabaseColumn("hotel", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "hotel" }); Columns.Add(new DatabaseColumn("hotel_type", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "hotel_type" }); Columns.Add(new DatabaseColumn("reply", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "reply" }); Columns.Add(new DatabaseColumn("work_hrs", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "work_hrs" }); Columns.Add(new DatabaseColumn("is_input", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "is_input" }); Columns.Add(new DatabaseColumn("refuse_reason", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "refuse_reason" }); Columns.Add(new DatabaseColumn("CHECKER2", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "CHECKER2" }); Columns.Add(new DatabaseColumn("audit2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "audit2" }); Columns.Add(new DatabaseColumn("IsHotel", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "IsHotel" }); Columns.Add(new DatabaseColumn("IsCar", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "IsCar" }); Columns.Add(new DatabaseColumn("Itinerary", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "Itinerary" }); Columns.Add(new DatabaseColumn("Destination", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "Destination" }); Columns.Add(new DatabaseColumn("IDate", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "IDate" }); Columns.Add(new DatabaseColumn("Nights", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "Nights" }); Columns.Add(new DatabaseColumn("reply2", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "reply2" }); Columns.Add(new DatabaseColumn("itinerary2", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "itinerary2" }); Columns.Add(new DatabaseColumn("itinerary3", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "itinerary3" }); Columns.Add(new DatabaseColumn("itinerary4", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "itinerary4" }); Columns.Add(new DatabaseColumn("IDate2", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "IDate2" }); Columns.Add(new DatabaseColumn("IDate3", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "IDate3" }); Columns.Add(new DatabaseColumn("IDate4", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "IDate4" }); Columns.Add(new DatabaseColumn("Destination2", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "Destination2" }); Columns.Add(new DatabaseColumn("Destination3", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "Destination3" }); Columns.Add(new DatabaseColumn("Destination4", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "Destination4" }); Columns.Add(new DatabaseColumn("Nights2", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "Nights2" }); Columns.Add(new DatabaseColumn("Nights3", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "Nights3" }); Columns.Add(new DatabaseColumn("Nights4", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 255, PropertyName = "Nights4" }); Columns.Add(new DatabaseColumn("check_date2", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "check_date2" }); } public IColumn Id{ get{ return this.GetColumn("Id"); } } public IColumn bill_id{ get{ return this.GetColumn("bill_id"); } } public IColumn emp_id{ get{ return this.GetColumn("emp_id"); } } public IColumn join_id{ get{ return this.GetColumn("join_id"); } } public IColumn depart_id{ get{ return this.GetColumn("depart_id"); } } public IColumn bill_date{ get{ return this.GetColumn("bill_date"); } } public IColumn begin_time{ get{ return this.GetColumn("begin_time"); } } public IColumn end_time{ get{ return this.GetColumn("end_time"); } } public IColumn work_type{ get{ return this.GetColumn("work_type"); } } public IColumn work_days{ get{ return this.GetColumn("work_days"); } } public IColumn status_id{ get{ return this.GetColumn("status_id"); } } public IColumn leave_id{ get{ return this.GetColumn("leave_id"); } } public IColumn rate{ get{ return this.GetColumn("rate"); } } public IColumn checker{ get{ return this.GetColumn("checker"); } } public IColumn check_date{ get{ return this.GetColumn("check_date"); } } public IColumn op_user{ get{ return this.GetColumn("op_user"); } } public IColumn op_date{ get{ return this.GetColumn("op_date"); } } public IColumn audit{ get{ return this.GetColumn("audit"); } } public IColumn memo{ get{ return this.GetColumn("memo"); } } public IColumn outwork_type{ get{ return this.GetColumn("outwork_type"); } } public IColumn outwork_addr{ get{ return this.GetColumn("outwork_addr"); } } public IColumn transportation{ get{ return this.GetColumn("transportation"); } } public IColumn Re_date{ get{ return this.GetColumn("Re_date"); } } public IColumn Start_ag{ get{ return this.GetColumn("Start_ag"); } } public IColumn re_ag{ get{ return this.GetColumn("re_ag"); } } public IColumn peers{ get{ return this.GetColumn("peers"); } } public IColumn Hostel{ get{ return this.GetColumn("Hostel"); } } public IColumn hotel{ get{ return this.GetColumn("hotel"); } } public IColumn hotel_type{ get{ return this.GetColumn("hotel_type"); } } public IColumn reply{ get{ return this.GetColumn("reply"); } } public IColumn work_hrs{ get{ return this.GetColumn("work_hrs"); } } public IColumn is_input{ get{ return this.GetColumn("is_input"); } } public IColumn refuse_reason{ get{ return this.GetColumn("refuse_reason"); } } public IColumn CHECKER2{ get{ return this.GetColumn("CHECKER2"); } } public IColumn audit2{ get{ return this.GetColumn("audit2"); } } public IColumn IsHotel{ get{ return this.GetColumn("IsHotel"); } } public IColumn IsCar{ get{ return this.GetColumn("IsCar"); } } public IColumn Itinerary{ get{ return this.GetColumn("Itinerary"); } } public IColumn Destination{ get{ return this.GetColumn("Destination"); } } public IColumn IDate{ get{ return this.GetColumn("IDate"); } } public IColumn Nights{ get{ return this.GetColumn("Nights"); } } public IColumn reply2{ get{ return this.GetColumn("reply2"); } } public IColumn itinerary2{ get{ return this.GetColumn("itinerary2"); } } public IColumn itinerary3{ get{ return this.GetColumn("itinerary3"); } } public IColumn itinerary4{ get{ return this.GetColumn("itinerary4"); } } public IColumn IDate2{ get{ return this.GetColumn("IDate2"); } } public IColumn IDate3{ get{ return this.GetColumn("IDate3"); } } public IColumn IDate4{ get{ return this.GetColumn("IDate4"); } } public IColumn Destination2{ get{ return this.GetColumn("Destination2"); } } public IColumn Destination3{ get{ return this.GetColumn("Destination3"); } } public IColumn Destination4{ get{ return this.GetColumn("Destination4"); } } public IColumn Nights2{ get{ return this.GetColumn("Nights2"); } } public IColumn Nights3{ get{ return this.GetColumn("Nights3"); } } public IColumn Nights4{ get{ return this.GetColumn("Nights4"); } } public IColumn check_date2{ get{ return this.GetColumn("check_date2"); } } } }
// created on 10/5/2002 at 23:01 // Npgsql.NpgsqlConnection.cs // // Author: // Francisco Jr. ([email protected]) // // Copyright (C) 2002 The Npgsql Development Team // [email protected] // http://gborg.postgresql.org/project/npgsql/projdisplay.php // // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph and the following two paragraphs appear in all copies. // // IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY // FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, // INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS // DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // // THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS // ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. using System; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Reflection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Transactions; using Mono.Security.Protocol.Tls; using IsolationLevel = System.Data.IsolationLevel; namespace Revenj.DatabasePersistence.Postgres.Npgsql { /// <summary> /// Represents the method that handles the <see cref="Npgsql.NpgsqlConnection.Notification">Notice</see> events. /// </summary> /// <param name="e">A <see cref="Npgsql.NpgsqlNoticeEventArgs">NpgsqlNoticeEventArgs</see> that contains the event data.</param> public delegate void NoticeEventHandler(Object sender, NpgsqlNoticeEventArgs e); /// <summary> /// Represents the method that handles the <see cref="Npgsql.NpgsqlConnection.Notification">Notification</see> events. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">A <see cref="Npgsql.NpgsqlNotificationEventArgs">NpgsqlNotificationEventArgs</see> that contains the event data.</param> public delegate void NotificationEventHandler(Object sender, NpgsqlNotificationEventArgs e); /// <summary> /// This class represents a connection to a /// PostgreSQL server. /// </summary> public sealed class NpgsqlConnection : DbConnection, ICloneable { // Logging related values private static readonly String CLASSNAME = MethodBase.GetCurrentMethod().DeclaringType.Name; // Parsed connection string cache private static readonly Cache<NpgsqlConnectionStringBuilder> cache = new Cache<NpgsqlConnectionStringBuilder>(); /// <summary> /// Occurs on NoticeResponses from the PostgreSQL backend. /// </summary> public event NoticeEventHandler Notice; internal NoticeEventHandler NoticeDelegate; /// <summary> /// Occurs on NotificationResponses from the PostgreSQL backend. /// </summary> public event NotificationEventHandler Notification; internal NotificationEventHandler NotificationDelegate; /// <summary> /// Called to provide client certificates for SSL handshake. /// </summary> public event ProvideClientCertificatesCallback ProvideClientCertificatesCallback; internal ProvideClientCertificatesCallback ProvideClientCertificatesCallbackDelegate; /// <summary> /// Mono.Security.Protocol.Tls.CertificateSelectionCallback delegate. /// </summary> public event CertificateSelectionCallback CertificateSelectionCallback; internal CertificateSelectionCallback CertificateSelectionCallbackDelegate; /// <summary> /// Mono.Security.Protocol.Tls.CertificateValidationCallback delegate. /// </summary> public event CertificateValidationCallback CertificateValidationCallback; internal CertificateValidationCallback CertificateValidationCallbackDelegate; /// <summary> /// Mono.Security.Protocol.Tls.PrivateKeySelectionCallback delegate. /// </summary> public event PrivateKeySelectionCallback PrivateKeySelectionCallback; internal PrivateKeySelectionCallback PrivateKeySelectionCallbackDelegate; // Set this when disposed is called. private bool disposed = false; // Used when we closed the connector due to an error, but are pretending it's open. private bool _fakingOpen; // Strong-typed ConnectionString values private NpgsqlConnectionStringBuilder settings; // Connector being used for the active connection. private NpgsqlConnector connector = null; private NpgsqlPromotableSinglePhaseNotification promotable = null; /// <summary> /// Initializes a new instance of the /// <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see> class. /// </summary> public NpgsqlConnection() : this(String.Empty) { } private static NpgsqlConnectionStringBuilder GetBuilder(string connectionString) { NpgsqlConnectionStringBuilder builder = cache[connectionString]; return builder == null ? new NpgsqlConnectionStringBuilder(connectionString) : builder.Clone(); } /// <summary> /// Initializes a new instance of the /// <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see> class /// and sets the <see cref="Npgsql.NpgsqlConnection.ConnectionString">ConnectionString</see>. /// </summary> /// <param name="ConnectionString">The connection used to open the PostgreSQL database.</param> public NpgsqlConnection(String ConnectionString) : this(GetBuilder(ConnectionString)) { } private NpgsqlConnection(NpgsqlConnectionStringBuilder builder) { this.settings = builder; NoticeDelegate = new NoticeEventHandler(OnNotice); NotificationDelegate = new NotificationEventHandler(OnNotification); ProvideClientCertificatesCallbackDelegate = new ProvideClientCertificatesCallback(DefaultProvideClientCertificatesCallback); CertificateValidationCallbackDelegate = new CertificateValidationCallback(DefaultCertificateValidationCallback); CertificateSelectionCallbackDelegate = new CertificateSelectionCallback(DefaultCertificateSelectionCallback); PrivateKeySelectionCallbackDelegate = new PrivateKeySelectionCallback(DefaultPrivateKeySelectionCallback); // Fix authentication problems. See https://bugzilla.novell.com/show_bug.cgi?id=MONO77559 and // http://pgfoundry.org/forum/message.php?msg_id=1002377 for more info. RSACryptoServiceProvider.UseMachineKeyStore = true; promotable = new NpgsqlPromotableSinglePhaseNotification(this); } /// <summary> /// Gets or sets the string used to connect to a PostgreSQL database. /// Valid values are: /// <ul> /// <li> /// Server: Address/Name of Postgresql Server; /// </li> /// <li> /// Port: Port to connect to; /// </li> /// <li> /// Protocol: Protocol version to use, instead of automatic; Integer 2 or 3; /// </li> /// <li> /// Database: Database name. Defaults to user name if not specified; /// </li> /// <li> /// User Id: User name; /// </li> /// <li> /// Password: Password for clear text authentication; /// </li> /// <li> /// SSL: True or False. Controls whether to attempt a secure connection. Default = False; /// </li> /// <li> /// Pooling: True or False. Controls whether connection pooling is used. Default = True; /// </li> /// <li> /// MinPoolSize: Min size of connection pool; /// </li> /// <li> /// MaxPoolSize: Max size of connection pool; /// </li> /// <li> /// Timeout: Time to wait for connection open in seconds. Default is 15. /// </li> /// <li> /// CommandTimeout: Time to wait for command to finish execution before throw an exception. In seconds. Default is 20. /// </li> /// <li> /// Sslmode: Mode for ssl connection control. Can be Prefer, Require, Allow or Disable. Default is Disable. Check user manual for explanation of values. /// </li> /// <li> /// ConnectionLifeTime: Time to wait before closing unused connections in the pool in seconds. Default is 15. /// </li> /// <li> /// SyncNotification: Specifies if Npgsql should use synchronous notifications. /// </li> /// <li> /// SearchPath: Changes search path to specified and public schemas. /// </li> /// </ul> /// </summary> /// <value>The connection string that includes the server name, /// the database name, and other parameters needed to establish /// the initial connection. The default value is an empty string. /// </value> public override String ConnectionString { get { return settings.ConnectionString; } set { // Connection string is used as the key to the connector. Because of this, // we cannot change it while we own a connector. CheckConnectionClosed(); NpgsqlConnectionStringBuilder builder = cache[value]; if (builder == null) { settings = new NpgsqlConnectionStringBuilder(value); } else { settings = builder.Clone(); } } } /// <summary> /// Backend server host name. /// </summary> [Browsable(true)] public String Host { get { return settings.Host; } } /// <summary> /// Backend server port. /// </summary> [Browsable(true)] public Int32 Port { get { return settings.Port; } } /// <summary> /// If true, the connection will attempt to use SSL. /// </summary> [Browsable(true)] public Boolean SSL { get { return settings.SSL; } } /// <summary> /// Gets the time to wait while trying to establish a connection /// before terminating the attempt and generating an error. /// </summary> /// <value>The time (in seconds) to wait for a connection to open. The default value is 15 seconds.</value> public override Int32 ConnectionTimeout { get { return settings.Timeout; } } /// <summary> /// Gets the time to wait while trying to execute a command /// before terminating the attempt and generating an error. /// </summary> /// <value>The time (in seconds) to wait for a command to complete. The default value is 20 seconds.</value> public Int32 CommandTimeout { get { return settings.CommandTimeout; } } /// <summary> /// Gets the time to wait before closing unused connections in the pool if the count /// of all connections exeeds MinPoolSize. /// </summary> /// <remarks> /// If connection pool contains unused connections for ConnectionLifeTime seconds, /// the half of them will be closed. If there will be unused connections in a second /// later then again the half of them will be closed and so on. /// This strategy provide smooth change of connection count in the pool. /// </remarks> /// <value>The time (in seconds) to wait. The default value is 15 seconds.</value> public Int32 ConnectionLifeTime { get { return settings.ConnectionLifeTime; } } ///<summary> /// Gets the name of the current database or the database to be used after a connection is opened. /// </summary> /// <value>The name of the current database or the name of the database to be /// used after a connection is opened. The default value is the empty string.</value> public override String Database { get { return settings.Database; } } /// <summary> /// Whether datareaders are loaded in their entirety (for compatibility with earlier code). /// </summary> public bool PreloadReader { get { return settings.PreloadReader; } } /// <summary> /// Gets the database server name. /// </summary> public override string DataSource { get { return settings.Host; } } /// <summary> /// Gets flag indicating if we are using Synchronous notification or not. /// The default value is false. /// </summary> public Boolean SyncNotification { get { return settings.SyncNotification; } } /// <summary> /// Gets the current state of the connection. /// </summary> /// <value>A bitwise combination of the <see cref="System.Data.ConnectionState">ConnectionState</see> values. The default is <b>Closed</b>.</value> [Browsable(false)] public ConnectionState FullState { get { if (connector != null && !disposed) { return connector.State; } else { return ConnectionState.Closed; } } } /// <summary> /// Gets whether the current state of the connection is Open or Closed /// </summary> /// <value>ConnectionState.Open or ConnectionState.Closed</value> [Browsable(false)] public override ConnectionState State { get { return (FullState & ConnectionState.Open) == ConnectionState.Open ? ConnectionState.Open : ConnectionState.Closed; } } public Version NpgsqlCompatibilityVersion { get { return settings.Compatible; } } /// <summary> /// Version of the PostgreSQL backend. /// This can only be called when there is an active connection. /// </summary> [Browsable(false)] public Version PostgreSqlVersion { get { CheckConnectionOpen(); return connector.ServerVersion; } } public override string ServerVersion { get { return PostgreSqlVersion.ToString(); } } /// <summary> /// Process id of backend server. /// This can only be called when there is an active connection. /// </summary> [Browsable(false)] public Int32 ProcessID { get { CheckConnectionOpen(); return connector.BackEndKeyData.ProcessID; } } /// <summary> /// Begins a database transaction with the specified isolation level. /// </summary> /// <param name="isolationLevel">The <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param> /// <returns>An <see cref="System.Data.Common.DbTransaction">DbTransaction</see> /// object representing the new transaction.</returns> /// <remarks> /// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend. /// There's no support for nested transactions. /// </remarks> protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { return BeginTransaction(isolationLevel); } /// <summary> /// Begins a database transaction. /// </summary> /// <returns>A <see cref="Npgsql.NpgsqlTransaction">NpgsqlTransaction</see> /// object representing the new transaction.</returns> /// <remarks> /// Currently there's no support for nested transactions. /// </remarks> public new NpgsqlTransaction BeginTransaction() { return this.BeginTransaction(IsolationLevel.ReadCommitted); } /// <summary> /// Begins a database transaction with the specified isolation level. /// </summary> /// <param name="level">The <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param> /// <returns>A <see cref="Npgsql.NpgsqlTransaction">NpgsqlTransaction</see> /// object representing the new transaction.</returns> /// <remarks> /// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend. /// There's no support for nested transactions. /// </remarks> public new NpgsqlTransaction BeginTransaction(IsolationLevel level) { CheckConnectionOpen(); if (connector.Transaction != null) { throw new InvalidOperationException("Nested/Concurrent transactions aren't supported."); } return new NpgsqlTransaction(this, level); } /// <summary> /// Opens a database connection with the property settings specified by the /// <see cref="Npgsql.NpgsqlConnection.ConnectionString">ConnectionString</see>. /// </summary> public override void Open() { CheckConnectionClosed(); // Check if there is any missing argument. if (!settings.ContainsKey(Keywords.Host)) { throw new ArgumentException("Connection string argument missing!", NpgsqlConnectionStringBuilder.GetKeyName(Keywords.Host)); } if (!settings.ContainsKey(Keywords.UserName) && !settings.ContainsKey(Keywords.IntegratedSecurity)) { throw new ArgumentException("Connection string argument missing!", NpgsqlConnectionStringBuilder.GetKeyName(Keywords.UserName)); } // Get a Connector, either from the pool or creating one ourselves. if (Pooling) { connector = NpgsqlConnectorPool.ConnectorPoolMgr.RequestConnector(this); } else { connector = new NpgsqlConnector(this); connector.ProvideClientCertificatesCallback += ProvideClientCertificatesCallbackDelegate; connector.CertificateSelectionCallback += CertificateSelectionCallbackDelegate; connector.CertificateValidationCallback += CertificateValidationCallbackDelegate; connector.PrivateKeySelectionCallback += PrivateKeySelectionCallbackDelegate; connector.Open(); } connector.Notice += NoticeDelegate; connector.Notification += NotificationDelegate; connector.StateChanged += connector_StateChanged; if (SyncNotification) { connector.AddNotificationThread(); } if (Enlist) { Promotable.Enlist(Transaction.Current); } this.OnStateChange(new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open)); } private void connector_StateChanged(object sender, StateChangeEventArgs e) { OnStateChange(e); } /// <summary> /// This method changes the current database by disconnecting from the actual /// database and connecting to the specified. /// </summary> /// <param name="dbName">The name of the database to use in place of the current database.</param> public override void ChangeDatabase(String dbName) { CheckNotDisposed(); if (dbName == null) { throw new ArgumentNullException("dbName"); } if (string.IsNullOrEmpty(dbName)) { throw new ArgumentOutOfRangeException(String.Format("Invalid database name: {0}", dbName), "dbName"); } String oldDatabaseName = Database; Close(); settings = settings.Clone(); settings[Keywords.Database] = dbName; Open(); } internal void EmergencyClose() { _fakingOpen = true; } /// <summary> /// Releases the connection to the database. If the connection is pooled, it will be /// made available for re-use. If it is non-pooled, the actual connection will be shutdown. /// </summary> public override void Close() { if (connector != null) { Promotable.Prepare(); // clear the way for another promotable transaction promotable = null; connector.Notification -= NotificationDelegate; connector.Notice -= NoticeDelegate; connector.StateChanged -= connector_StateChanged; if (SyncNotification) { connector.RemoveNotificationThread(); } if (Pooling) { NpgsqlConnectorPool.ConnectorPoolMgr.ReleaseConnector(this, connector); } else { Connector.ProvideClientCertificatesCallback -= ProvideClientCertificatesCallbackDelegate; Connector.CertificateSelectionCallback -= CertificateSelectionCallbackDelegate; Connector.CertificateValidationCallback -= CertificateValidationCallbackDelegate; Connector.PrivateKeySelectionCallback -= PrivateKeySelectionCallbackDelegate; if (Connector.Transaction != null) { Connector.Transaction.Cancel(); } Connector.Close(); } connector = null; this.OnStateChange(new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed)); } } /// <summary> /// Creates and returns a <see cref="System.Data.Common.DbCommand">DbCommand</see> /// object associated with the <see cref="System.Data.Common.DbConnection">IDbConnection</see>. /// </summary> /// <returns>A <see cref="System.Data.Common.DbCommand">DbCommand</see> object.</returns> protected override DbCommand CreateDbCommand() { return CreateCommand(); } /// <summary> /// Creates and returns a <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> /// object associated with the <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see>. /// </summary> /// <returns>A <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> object.</returns> public new NpgsqlCommand CreateCommand() { CheckNotDisposed(); return new NpgsqlCommand("", this); } /// <summary> /// Releases all resources used by the /// <see cref="Npgsql.NpgsqlConnection">NpgsqlConnection</see>. /// </summary> /// <param name="disposing"><b>true</b> when called from Dispose(); /// <b>false</b> when being called from the finalizer.</param> protected override void Dispose(bool disposing) { if (!disposed) { if (disposing) { Close(); } else { if (FullState != ConnectionState.Closed) { NpgsqlConnectorPool.ConnectorPoolMgr.FixPoolCountBecauseOfConnectionDisposeFalse(this); } } base.Dispose(disposing); disposed = true; } } /// <summary> /// Create a new connection based on this one. /// </summary> /// <returns>A new NpgsqlConnection object.</returns> Object ICloneable.Clone() { return Clone(); } /// <summary> /// Create a new connection based on this one. /// </summary> /// <returns>A new NpgsqlConnection object.</returns> public NpgsqlConnection Clone() { CheckNotDisposed(); NpgsqlConnection C = new NpgsqlConnection(settings); C.Notice += this.Notice; if (connector != null) { C.Open(); } return C; } // // Internal methods and properties // internal void OnNotice(object O, NpgsqlNoticeEventArgs E) { if (Notice != null) { Notice(this, E); } } internal void OnNotification(object O, NpgsqlNotificationEventArgs E) { if (Notification != null) { Notification(this, E); } } /// <summary> /// The connector object connected to the backend. /// </summary> internal NpgsqlConnector Connector { get { return connector; } } /// <summary> /// Gets the NpgsqlConnectionStringBuilder containing the parsed connection string values. /// </summary> internal NpgsqlConnectionStringBuilder ConnectionStringValues { get { return settings; } } /// <summary> /// User name. /// </summary> internal String UserName { get { return settings.UserName; } } public bool UseExtendedTypes { get { bool ext = settings.UseExtendedTypes; return ext; } } /// <summary> /// Password. /// </summary> internal byte[] Password { get { return settings.PasswordAsByteArray; } } /// <summary> /// Determine if connection pooling will be used for this connection. /// </summary> internal Boolean Pooling { get { return (settings.Pooling && (settings.MaxPoolSize > 0)); } } internal Int32 MinPoolSize { get { return settings.MinPoolSize; } } internal Int32 MaxPoolSize { get { return settings.MaxPoolSize; } } internal Int32 Timeout { get { return settings.Timeout; } } internal Boolean Enlist { get { return settings.Enlist; } } // // Event handlers // /// <summary> /// Default SSL CertificateSelectionCallback implementation. /// </summary> internal X509Certificate DefaultCertificateSelectionCallback(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates) { if (CertificateSelectionCallback != null) { return CertificateSelectionCallback(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates); } else { return null; } } /// <summary> /// Default SSL CertificateValidationCallback implementation. /// </summary> internal bool DefaultCertificateValidationCallback(X509Certificate certificate, int[] certificateErrors) { if (CertificateValidationCallback != null) { return CertificateValidationCallback(certificate, certificateErrors); } else { return true; } } /// <summary> /// Default SSL PrivateKeySelectionCallback implementation. /// </summary> internal AsymmetricAlgorithm DefaultPrivateKeySelectionCallback(X509Certificate certificate, string targetHost) { if (PrivateKeySelectionCallback != null) { return PrivateKeySelectionCallback(certificate, targetHost); } else { return null; } } /// <summary> /// Default SSL ProvideClientCertificatesCallback implementation. /// </summary> internal void DefaultProvideClientCertificatesCallback(X509CertificateCollection certificates) { if (ProvideClientCertificatesCallback != null) { ProvideClientCertificatesCallback(certificates); } } // // Private methods and properties // private NpgsqlPromotableSinglePhaseNotification Promotable { get { return promotable ?? (promotable = new NpgsqlPromotableSinglePhaseNotification(this)); } } private void CheckConnectionOpen() { if (disposed) { throw new ObjectDisposedException(CLASSNAME); } if (_fakingOpen) { if (connector != null) { try { Close(); } catch { } } Open(); _fakingOpen = false; } if (connector == null) { throw new InvalidOperationException("Connection is not open"); } } private void CheckConnectionClosed() { if (disposed) { throw new ObjectDisposedException(CLASSNAME); } if (connector != null) { throw new InvalidOperationException("Connection already open"); } } private void CheckNotDisposed() { if (disposed) { throw new ObjectDisposedException(CLASSNAME); } } /// <summary> /// Returns the supported collections /// </summary> public override DataTable GetSchema() { return NpgsqlSchema.GetMetaDataCollections(); } /// <summary> /// Returns the schema collection specified by the collection name. /// </summary> /// <param name="collectionName">The collection name.</param> /// <returns>The collection specified.</returns> public override DataTable GetSchema(string collectionName) { return GetSchema(collectionName, null); } /// <summary> /// Returns the schema collection specified by the collection name filtered by the restrictions. /// </summary> /// <param name="collectionName">The collection name.</param> /// <param name="restrictions"> /// The restriction values to filter the results. A description of the restrictions is contained /// in the Restrictions collection. /// </param> /// <returns>The collection specified.</returns> public override DataTable GetSchema(string collectionName, string[] restrictions) { switch (collectionName) { case "MetaDataCollections": return NpgsqlSchema.GetMetaDataCollections(); case "Restrictions": return NpgsqlSchema.GetRestrictions(); case "DataSourceInformation": return NpgsqlSchema.GetDataSourceInformation(); case "DataTypes": throw new NotSupportedException(); case "ReservedWords": return NpgsqlSchema.GetReservedWords(); // custom collections for npgsql case "Databases": return new NpgsqlSchema(new NpgsqlConnection(ConnectionString)).GetDatabases(restrictions); case "Tables": return new NpgsqlSchema(new NpgsqlConnection(ConnectionString)).GetTables(restrictions); case "Columns": return new NpgsqlSchema(new NpgsqlConnection(ConnectionString)).GetColumns(restrictions); case "Views": return new NpgsqlSchema(new NpgsqlConnection(ConnectionString)).GetViews(restrictions); case "Users": return new NpgsqlSchema(new NpgsqlConnection(ConnectionString)).GetUsers(restrictions); case "Indexes": return new NpgsqlSchema(new NpgsqlConnection(ConnectionString)).GetIndexes(restrictions); case "IndexColumns": return new NpgsqlSchema(new NpgsqlConnection(ConnectionString)).GetIndexColumns(restrictions); case "ForeignKeys": return new NpgsqlSchema(new NpgsqlConnection(ConnectionString)).GetForeignKeys(restrictions); default: throw new NotSupportedException(); } } public void ClearPool() { NpgsqlConnectorPool.ConnectorPoolMgr.ClearPool(this); } public static void ClearAllPools() { NpgsqlConnectorPool.ConnectorPoolMgr.ClearAllPools(); } public override void EnlistTransaction(Transaction transaction) { Promotable.Enlist(transaction); } protected override DbProviderFactory DbProviderFactory { get { return NpgsqlFactory.Instance; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Reflection.Metadata { /// <summary> /// Reads metadata as defined byte the ECMA 335 CLI specification. /// </summary> public sealed partial class MetadataReader { private readonly MetadataReaderOptions _options; internal readonly MetadataStringDecoder utf8Decoder; internal readonly NamespaceCache namespaceCache; private Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>> _lazyNestedTypesMap; internal readonly MemoryBlock Block; // A row id of "mscorlib" AssemblyRef in a WinMD file (each WinMD file must have such a reference). internal readonly int WinMDMscorlibRef; #region Constructors /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// </remarks> public unsafe MetadataReader(byte* metadata, int length) : this(metadata, length, MetadataReaderOptions.Default, null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions)"/> to obtain /// metadata from a PE image. /// </remarks> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options) : this(metadata, length, options, null) { } /// <summary> /// Creates a metadata reader from the metadata stored at the given memory location. /// </summary> /// <remarks> /// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>. /// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain /// metadata from a PE image. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is not positive.</exception> /// <exception cref="ArgumentNullException"><paramref name="metadata"/> is null.</exception> /// <exception cref="ArgumentException">The encoding of <paramref name="utf8Decoder"/> is not <see cref="UTF8Encoding"/>.</exception> /// <exception cref="PlatformNotSupportedException">The current platform is big-endian.</exception> public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder) { // Do not throw here when length is 0. We'll throw BadImageFormatException later on, so that the caller doesn't need to // worry about the image (stream) being empty and can handle all image errors by catching BadImageFormatException. if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } if (utf8Decoder == null) { utf8Decoder = MetadataStringDecoder.DefaultUTF8; } if (!(utf8Decoder.Encoding is UTF8Encoding)) { throw new ArgumentException(SR.MetadataStringDecoderEncodingMustBeUtf8, nameof(utf8Decoder)); } if (!BitConverter.IsLittleEndian) { Throw.LitteEndianArchitectureRequired(); } this.Block = new MemoryBlock(metadata, length); _options = options; this.utf8Decoder = utf8Decoder; var headerReader = new BlobReader(this.Block); this.ReadMetadataHeader(ref headerReader, out _versionString); _metadataKind = GetMetadataKind(_versionString); var streamHeaders = this.ReadStreamHeaders(ref headerReader); // storage header and stream headers: MemoryBlock metadataTableStream; MemoryBlock standalonePdbStream; this.InitializeStreamReaders(ref this.Block, streamHeaders, out _metadataStreamKind, out metadataTableStream, out standalonePdbStream); int[] externalTableRowCountsOpt; if (standalonePdbStream.Length > 0) { ReadStandalonePortablePdbStream(standalonePdbStream, out _debugMetadataHeader, out externalTableRowCountsOpt); } else { externalTableRowCountsOpt = null; } var tableReader = new BlobReader(metadataTableStream); HeapSizes heapSizes; int[] metadataTableRowCounts; this.ReadMetadataTableHeader(ref tableReader, out heapSizes, out metadataTableRowCounts, out _sortedTables); this.InitializeTableReaders(tableReader.GetMemoryBlockAt(0, tableReader.RemainingBytes), heapSizes, metadataTableRowCounts, externalTableRowCountsOpt); // This previously could occur in obfuscated assemblies but a check was added to prevent // it getting to this point Debug.Assert(this.AssemblyTable.NumberOfRows <= 1); // Although the specification states that the module table will have exactly one row, // the native metadata reader would successfully read files containing more than one row. // Such files exist in the wild and may be produced by obfuscators. if (standalonePdbStream.Length == 0 && this.ModuleTable.NumberOfRows < 1) { throw new BadImageFormatException(SR.Format(SR.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows)); } // read this.namespaceCache = new NamespaceCache(this); if (_metadataKind != MetadataKind.Ecma335) { this.WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection(); } } #endregion #region Metadata Headers private readonly string _versionString; private readonly MetadataKind _metadataKind; private readonly MetadataStreamKind _metadataStreamKind; private readonly DebugMetadataHeader _debugMetadataHeader; internal StringStreamReader StringStream; internal BlobStreamReader BlobStream; internal GuidStreamReader GuidStream; internal UserStringStreamReader UserStringStream; /// <summary> /// True if the metadata stream has minimal delta format. Used for EnC. /// </summary> /// <remarks> /// The metadata stream has minimal delta format if "#JTD" stream is present. /// Minimal delta format uses large size (4B) when encoding table/heap references. /// The heaps in minimal delta only contain data of the delta, /// there is no padding at the beginning of the heaps that would align them /// with the original full metadata heaps. /// </remarks> internal bool IsMinimalDelta; /// <summary> /// Looks like this function reads beginning of the header described in /// ECMA-335 24.2.1 Metadata root /// </summary> private void ReadMetadataHeader(ref BlobReader memReader, out string versionString) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofMetadataHeader) { throw new BadImageFormatException(SR.MetadataHeaderTooSmall); } uint signature = memReader.ReadUInt32(); if (signature != COR20Constants.COR20MetadataSignature) { throw new BadImageFormatException(SR.MetadataSignature); } // major version memReader.ReadUInt16(); // minor version memReader.ReadUInt16(); // reserved: memReader.ReadUInt32(); int versionStringSize = memReader.ReadInt32(); if (memReader.RemainingBytes < versionStringSize) { throw new BadImageFormatException(SR.NotEnoughSpaceForVersionString); } int numberOfBytesRead; versionString = memReader.GetMemoryBlockAt(0, versionStringSize).PeekUtf8NullTerminated(0, null, utf8Decoder, out numberOfBytesRead, '\0'); memReader.SkipBytes(versionStringSize); } private MetadataKind GetMetadataKind(string versionString) { // Treat metadata as CLI raw metadata if the client doesn't want to see projections. if ((_options & MetadataReaderOptions.ApplyWindowsRuntimeProjections) == 0) { return MetadataKind.Ecma335; } if (!versionString.Contains("WindowsRuntime")) { return MetadataKind.Ecma335; } else if (versionString.Contains("CLR")) { return MetadataKind.ManagedWindowsMetadata; } else { return MetadataKind.WindowsMetadata; } } /// <summary> /// Reads stream headers described in ECMA-335 24.2.2 Stream header /// </summary> private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader) { // storage header: memReader.ReadUInt16(); int streamCount = memReader.ReadInt16(); var streamHeaders = new StreamHeader[streamCount]; for (int i = 0; i < streamHeaders.Length; i++) { if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader) { throw new BadImageFormatException(SR.StreamHeaderTooSmall); } streamHeaders[i].Offset = memReader.ReadUInt32(); streamHeaders[i].Size = memReader.ReadInt32(); streamHeaders[i].Name = memReader.ReadUtf8NullTerminated(); bool aligned = memReader.TryAlign(4); if (!aligned || memReader.RemainingBytes == 0) { throw new BadImageFormatException(SR.NotEnoughSpaceForStreamHeaderName); } } return streamHeaders; } private void InitializeStreamReaders( ref MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MetadataStreamKind metadataStreamKind, out MemoryBlock metadataTableStream, out MemoryBlock standalonePdbStream) { metadataTableStream = default(MemoryBlock); standalonePdbStream = default(MemoryBlock); metadataStreamKind = MetadataStreamKind.Illegal; foreach (StreamHeader streamHeader in streamHeaders) { switch (streamHeader.Name) { case COR20Constants.StringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForStringStream); } this.StringStream = new StringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.BlobStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.BlobStream = new BlobStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.GUIDStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForGUIDStream); } this.GuidStream = new GuidStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.UserStringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream); } this.UserStringStream = new UserStringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size)); break; case COR20Constants.CompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } metadataStreamKind = MetadataStreamKind.Compressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.UncompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } metadataStreamKind = MetadataStreamKind.Uncompressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.MinimalDeltaMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } // the content of the stream is ignored this.IsMinimalDelta = true; break; case COR20Constants.StandalonePdbStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream); } standalonePdbStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; default: // Skip unknown streams. Some obfuscators insert invalid streams. continue; } } if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed) { throw new BadImageFormatException(SR.InvalidMetadataStreamFormat); } } #endregion #region Tables and Heaps private readonly TableMask _sortedTables; /// <summary> /// A row count for each possible table. May be indexed by <see cref="TableIndex"/>. /// </summary> internal int[] TableRowCounts; internal ModuleTableReader ModuleTable; internal TypeRefTableReader TypeRefTable; internal TypeDefTableReader TypeDefTable; internal FieldPtrTableReader FieldPtrTable; internal FieldTableReader FieldTable; internal MethodPtrTableReader MethodPtrTable; internal MethodTableReader MethodDefTable; internal ParamPtrTableReader ParamPtrTable; internal ParamTableReader ParamTable; internal InterfaceImplTableReader InterfaceImplTable; internal MemberRefTableReader MemberRefTable; internal ConstantTableReader ConstantTable; internal CustomAttributeTableReader CustomAttributeTable; internal FieldMarshalTableReader FieldMarshalTable; internal DeclSecurityTableReader DeclSecurityTable; internal ClassLayoutTableReader ClassLayoutTable; internal FieldLayoutTableReader FieldLayoutTable; internal StandAloneSigTableReader StandAloneSigTable; internal EventMapTableReader EventMapTable; internal EventPtrTableReader EventPtrTable; internal EventTableReader EventTable; internal PropertyMapTableReader PropertyMapTable; internal PropertyPtrTableReader PropertyPtrTable; internal PropertyTableReader PropertyTable; internal MethodSemanticsTableReader MethodSemanticsTable; internal MethodImplTableReader MethodImplTable; internal ModuleRefTableReader ModuleRefTable; internal TypeSpecTableReader TypeSpecTable; internal ImplMapTableReader ImplMapTable; internal FieldRVATableReader FieldRvaTable; internal EnCLogTableReader EncLogTable; internal EnCMapTableReader EncMapTable; internal AssemblyTableReader AssemblyTable; internal AssemblyProcessorTableReader AssemblyProcessorTable; // unused internal AssemblyOSTableReader AssemblyOSTable; // unused internal AssemblyRefTableReader AssemblyRefTable; internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; // unused internal AssemblyRefOSTableReader AssemblyRefOSTable; // unused internal FileTableReader FileTable; internal ExportedTypeTableReader ExportedTypeTable; internal ManifestResourceTableReader ManifestResourceTable; internal NestedClassTableReader NestedClassTable; internal GenericParamTableReader GenericParamTable; internal MethodSpecTableReader MethodSpecTable; internal GenericParamConstraintTableReader GenericParamConstraintTable; // debug tables internal DocumentTableReader DocumentTable; internal MethodDebugInformationTableReader MethodDebugInformationTable; internal LocalScopeTableReader LocalScopeTable; internal LocalVariableTableReader LocalVariableTable; internal LocalConstantTableReader LocalConstantTable; internal ImportScopeTableReader ImportScopeTable; internal StateMachineMethodTableReader StateMachineMethodTable; internal CustomDebugInformationTableReader CustomDebugInformationTable; private void ReadMetadataTableHeader(ref BlobReader reader, out HeapSizes heapSizes, out int[] metadataTableRowCounts, out TableMask sortedTables) { if (reader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader) { throw new BadImageFormatException(SR.MetadataTableHeaderTooSmall); } // reserved (shall be ignored): reader.ReadUInt32(); // major version (shall be ignored): reader.ReadByte(); // minor version (shall be ignored): reader.ReadByte(); // heap sizes: heapSizes = (HeapSizes)reader.ReadByte(); // reserved (shall be ignored): reader.ReadByte(); ulong presentTables = reader.ReadUInt64(); sortedTables = (TableMask)reader.ReadUInt64(); // According to ECMA-335, MajorVersion and MinorVersion have fixed values and, // based on recommendation in 24.1 Fixed fields: When writing these fields it // is best that they be set to the value indicated, on reading they should be ignored. // We will not be checking version values. We will continue checking that the set of // present tables is within the set we understand. ulong validTables = (ulong)(TableMask.TypeSystemTables | TableMask.DebugTables); if ((presentTables & ~validTables) != 0) { throw new BadImageFormatException(SR.Format(SR.UnknownTables, presentTables)); } if (_metadataStreamKind == MetadataStreamKind.Compressed) { // In general Ptr tables and EnC tables are not allowed in a compressed stream. // However when asked for a snapshot of the current metadata after an EnC change has been applied // the CLR includes the EnCLog table into the snapshot. We need to be able to read the image, // so we'll allow the table here but pretend it's empty later. if ((presentTables & (ulong)(TableMask.PtrTables | TableMask.EnCMap)) != 0) { throw new BadImageFormatException(SR.IllegalTablesInCompressedMetadataStream); } } metadataTableRowCounts = ReadMetadataTableRowCounts(ref reader, presentTables); if ((heapSizes & HeapSizes.ExtraData) == HeapSizes.ExtraData) { // Skip "extra data" used by some obfuscators. Although it is not mentioned in the CLI spec, // it is honored by the native metadata reader. reader.ReadUInt32(); } } private static int[] ReadMetadataTableRowCounts(ref BlobReader memReader, ulong presentTableMask) { ulong currentTableBit = 1; var rowCounts = new int[MetadataTokens.TableCount]; for (int i = 0; i < rowCounts.Length; i++) { if ((presentTableMask & currentTableBit) != 0) { if (memReader.RemainingBytes < sizeof(uint)) { throw new BadImageFormatException(SR.TableRowCountSpaceTooSmall); } uint rowCount = memReader.ReadUInt32(); if (rowCount > TokenTypeIds.RIDMask) { throw new BadImageFormatException(SR.Format(SR.InvalidRowCount, rowCount)); } rowCounts[i] = (int)rowCount; } currentTableBit <<= 1; } return rowCounts; } // internal for testing internal static void ReadStandalonePortablePdbStream(MemoryBlock block, out DebugMetadataHeader debugMetadataHeader, out int[] externalTableRowCounts) { var reader = new BlobReader(block); const int PdbIdSize = 20; byte[] pdbId = reader.ReadBytes(PdbIdSize); // ECMA-335 15.4.1.2: // The entry point to an application shall be static. // This entry point method can be a global method or it can appear inside a type. // The entry point method shall either accept no arguments or a vector of strings. // The return type of the entry point method shall be void, int32, or unsigned int32. // The entry point method cannot be defined in a generic class. uint entryPointToken = reader.ReadUInt32(); int entryPointRowId = (int)(entryPointToken & TokenTypeIds.RIDMask); if (entryPointToken != 0 && ((entryPointToken & TokenTypeIds.TypeMask) != TokenTypeIds.MethodDef || entryPointRowId == 0)) { throw new BadImageFormatException(string.Format(SR.InvalidEntryPointToken, entryPointToken)); } ulong externalTableMask = reader.ReadUInt64(); // EnC & Ptr tables can't be referenced from standalone PDB metadata: const ulong validTables = (ulong)TableMask.ValidPortablePdbExternalTables; if ((externalTableMask & ~validTables) != 0) { throw new BadImageFormatException(string.Format(SR.UnknownTables, (TableMask)externalTableMask)); } externalTableRowCounts = ReadMetadataTableRowCounts(ref reader, externalTableMask); debugMetadataHeader = new DebugMetadataHeader( ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref pdbId), MethodDefinitionHandle.FromRowId(entryPointRowId)); } private const int SmallIndexSize = 2; private const int LargeIndexSize = 4; private int GetReferenceSize(int[] rowCounts, TableIndex index) { return (rowCounts[(int)index] < MetadataStreamConstants.LargeTableRowCount && !IsMinimalDelta) ? SmallIndexSize : LargeIndexSize; } private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, HeapSizes heapSizes, int[] rowCounts, int[] externalRowCountsOpt) { // Size of reference tags in each table. this.TableRowCounts = rowCounts; // TODO (https://github.com/dotnet/corefx/issues/2061): // Shouldn't XxxPtr table be always the same size or smaller than the corresponding Xxx table? // Compute ref sizes for tables that can have pointer tables int fieldRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.FieldPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Field); int methodRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.MethodPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.MethodDef); int paramRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.ParamPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Param); int eventRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.EventPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Event); int propertyRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.PropertyPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Property); // Compute the coded token ref sizes int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCounts, TypeDefOrRefTag.TablesReferenced); int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCounts, HasConstantTag.TablesReferenced); int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCounts, HasCustomAttributeTag.TablesReferenced); int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCounts, HasFieldMarshalTag.TablesReferenced); int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCounts, HasDeclSecurityTag.TablesReferenced); int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCounts, MemberRefParentTag.TablesReferenced); int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCounts, HasSemanticsTag.TablesReferenced); int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCounts, MethodDefOrRefTag.TablesReferenced); int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCounts, MemberForwardedTag.TablesReferenced); int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCounts, ImplementationTag.TablesReferenced); int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCounts, CustomAttributeTypeTag.TablesReferenced); int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCounts, ResolutionScopeTag.TablesReferenced); int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCounts, TypeOrMethodDefTag.TablesReferenced); // Compute HeapRef Sizes int stringHeapRefSize = (heapSizes & HeapSizes.StringHeapLarge) == HeapSizes.StringHeapLarge ? LargeIndexSize : SmallIndexSize; int guidHeapRefSize = (heapSizes & HeapSizes.GuidHeapLarge) == HeapSizes.GuidHeapLarge ? LargeIndexSize : SmallIndexSize; int blobHeapRefSize = (heapSizes & HeapSizes.BlobHeapLarge) == HeapSizes.BlobHeapLarge ? LargeIndexSize : SmallIndexSize; // Populate the Table blocks int totalRequiredSize = 0; this.ModuleTable = new ModuleTableReader(rowCounts[(int)TableIndex.Module], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleTable.Block.Length; this.TypeRefTable = new TypeRefTableReader(rowCounts[(int)TableIndex.TypeRef], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeRefTable.Block.Length; this.TypeDefTable = new TypeDefTableReader(rowCounts[(int)TableIndex.TypeDef], fieldRefSizeSorted, methodRefSizeSorted, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeDefTable.Block.Length; this.FieldPtrTable = new FieldPtrTableReader(rowCounts[(int)TableIndex.FieldPtr], GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldPtrTable.Block.Length; this.FieldTable = new FieldTableReader(rowCounts[(int)TableIndex.Field], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldTable.Block.Length; this.MethodPtrTable = new MethodPtrTableReader(rowCounts[(int)TableIndex.MethodPtr], GetReferenceSize(rowCounts, TableIndex.MethodDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodPtrTable.Block.Length; this.MethodDefTable = new MethodTableReader(rowCounts[(int)TableIndex.MethodDef], paramRefSizeSorted, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodDefTable.Block.Length; this.ParamPtrTable = new ParamPtrTableReader(rowCounts[(int)TableIndex.ParamPtr], GetReferenceSize(rowCounts, TableIndex.Param), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamPtrTable.Block.Length; this.ParamTable = new ParamTableReader(rowCounts[(int)TableIndex.Param], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ParamTable.Block.Length; this.InterfaceImplTable = new InterfaceImplTableReader(rowCounts[(int)TableIndex.InterfaceImpl], IsDeclaredSorted(TableMask.InterfaceImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.InterfaceImplTable.Block.Length; this.MemberRefTable = new MemberRefTableReader(rowCounts[(int)TableIndex.MemberRef], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MemberRefTable.Block.Length; this.ConstantTable = new ConstantTableReader(rowCounts[(int)TableIndex.Constant], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ConstantTable.Block.Length; this.CustomAttributeTable = new CustomAttributeTableReader(rowCounts[(int)TableIndex.CustomAttribute], IsDeclaredSorted(TableMask.CustomAttribute), hasCustomAttributeRefSize, customAttributeTypeRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.CustomAttributeTable.Block.Length; this.FieldMarshalTable = new FieldMarshalTableReader(rowCounts[(int)TableIndex.FieldMarshal], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldMarshalTable.Block.Length; this.DeclSecurityTable = new DeclSecurityTableReader(rowCounts[(int)TableIndex.DeclSecurity], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.DeclSecurityTable.Block.Length; this.ClassLayoutTable = new ClassLayoutTableReader(rowCounts[(int)TableIndex.ClassLayout], IsDeclaredSorted(TableMask.ClassLayout), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ClassLayoutTable.Block.Length; this.FieldLayoutTable = new FieldLayoutTableReader(rowCounts[(int)TableIndex.FieldLayout], IsDeclaredSorted(TableMask.FieldLayout), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldLayoutTable.Block.Length; this.StandAloneSigTable = new StandAloneSigTableReader(rowCounts[(int)TableIndex.StandAloneSig], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.StandAloneSigTable.Block.Length; this.EventMapTable = new EventMapTableReader(rowCounts[(int)TableIndex.EventMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), eventRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventMapTable.Block.Length; this.EventPtrTable = new EventPtrTableReader(rowCounts[(int)TableIndex.EventPtr], GetReferenceSize(rowCounts, TableIndex.Event), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventPtrTable.Block.Length; this.EventTable = new EventTableReader(rowCounts[(int)TableIndex.Event], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EventTable.Block.Length; this.PropertyMapTable = new PropertyMapTableReader(rowCounts[(int)TableIndex.PropertyMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), propertyRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyMapTable.Block.Length; this.PropertyPtrTable = new PropertyPtrTableReader(rowCounts[(int)TableIndex.PropertyPtr], GetReferenceSize(rowCounts, TableIndex.Property), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyPtrTable.Block.Length; this.PropertyTable = new PropertyTableReader(rowCounts[(int)TableIndex.Property], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.PropertyTable.Block.Length; this.MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[(int)TableIndex.MethodSemantics], IsDeclaredSorted(TableMask.MethodSemantics), GetReferenceSize(rowCounts, TableIndex.MethodDef), hasSemanticsRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSemanticsTable.Block.Length; this.MethodImplTable = new MethodImplTableReader(rowCounts[(int)TableIndex.MethodImpl], IsDeclaredSorted(TableMask.MethodImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), methodDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodImplTable.Block.Length; this.ModuleRefTable = new ModuleRefTableReader(rowCounts[(int)TableIndex.ModuleRef], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ModuleRefTable.Block.Length; this.TypeSpecTable = new TypeSpecTableReader(rowCounts[(int)TableIndex.TypeSpec], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.TypeSpecTable.Block.Length; this.ImplMapTable = new ImplMapTableReader(rowCounts[(int)TableIndex.ImplMap], IsDeclaredSorted(TableMask.ImplMap), GetReferenceSize(rowCounts, TableIndex.ModuleRef), memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ImplMapTable.Block.Length; this.FieldRvaTable = new FieldRVATableReader(rowCounts[(int)TableIndex.FieldRva], IsDeclaredSorted(TableMask.FieldRva), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FieldRvaTable.Block.Length; this.EncLogTable = new EnCLogTableReader(rowCounts[(int)TableIndex.EncLog], metadataTablesMemoryBlock, totalRequiredSize, _metadataStreamKind); totalRequiredSize += this.EncLogTable.Block.Length; this.EncMapTable = new EnCMapTableReader(rowCounts[(int)TableIndex.EncMap], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.EncMapTable.Block.Length; this.AssemblyTable = new AssemblyTableReader(rowCounts[(int)TableIndex.Assembly], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyTable.Block.Length; this.AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[(int)TableIndex.AssemblyProcessor], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyProcessorTable.Block.Length; this.AssemblyOSTable = new AssemblyOSTableReader(rowCounts[(int)TableIndex.AssemblyOS], metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyOSTable.Block.Length; this.AssemblyRefTable = new AssemblyRefTableReader(rowCounts[(int)TableIndex.AssemblyRef], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize, _metadataKind); totalRequiredSize += this.AssemblyRefTable.Block.Length; this.AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[(int)TableIndex.AssemblyRefProcessor], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefProcessorTable.Block.Length; this.AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[(int)TableIndex.AssemblyRefOS], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.AssemblyRefOSTable.Block.Length; this.FileTable = new FileTableReader(rowCounts[(int)TableIndex.File], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.FileTable.Block.Length; this.ExportedTypeTable = new ExportedTypeTableReader(rowCounts[(int)TableIndex.ExportedType], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ExportedTypeTable.Block.Length; this.ManifestResourceTable = new ManifestResourceTableReader(rowCounts[(int)TableIndex.ManifestResource], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ManifestResourceTable.Block.Length; this.NestedClassTable = new NestedClassTableReader(rowCounts[(int)TableIndex.NestedClass], IsDeclaredSorted(TableMask.NestedClass), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.NestedClassTable.Block.Length; this.GenericParamTable = new GenericParamTableReader(rowCounts[(int)TableIndex.GenericParam], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamTable.Block.Length; this.MethodSpecTable = new MethodSpecTableReader(rowCounts[(int)TableIndex.MethodSpec], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodSpecTable.Block.Length; this.GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[(int)TableIndex.GenericParamConstraint], IsDeclaredSorted(TableMask.GenericParamConstraint), GetReferenceSize(rowCounts, TableIndex.GenericParam), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.GenericParamConstraintTable.Block.Length; // debug tables: // Type-system metadata tables may be stored in a separate (external) metadata file. // We need to use the row counts of the external tables when referencing them. // Debug tables are local to the current metadata image and type system metadata tables are external and precede all debug tables. var combinedRowCounts = (externalRowCountsOpt != null) ? CombineRowCounts(rowCounts, externalRowCountsOpt, firstLocalTableIndex: TableIndex.Document) : rowCounts; int methodRefSizeCombined = GetReferenceSize(combinedRowCounts, TableIndex.MethodDef); int hasCustomDebugInformationRefSizeCombined = ComputeCodedTokenSize(HasCustomDebugInformationTag.LargeRowSize, combinedRowCounts, HasCustomDebugInformationTag.TablesReferenced); this.DocumentTable = new DocumentTableReader(rowCounts[(int)TableIndex.Document], guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.DocumentTable.Block.Length; this.MethodDebugInformationTable = new MethodDebugInformationTableReader(rowCounts[(int)TableIndex.MethodDebugInformation], GetReferenceSize(rowCounts, TableIndex.Document), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.MethodDebugInformationTable.Block.Length; this.LocalScopeTable = new LocalScopeTableReader(rowCounts[(int)TableIndex.LocalScope], IsDeclaredSorted(TableMask.LocalScope), methodRefSizeCombined, GetReferenceSize(rowCounts, TableIndex.ImportScope), GetReferenceSize(rowCounts, TableIndex.LocalVariable), GetReferenceSize(rowCounts, TableIndex.LocalConstant), metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalScopeTable.Block.Length; this.LocalVariableTable = new LocalVariableTableReader(rowCounts[(int)TableIndex.LocalVariable], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalVariableTable.Block.Length; this.LocalConstantTable = new LocalConstantTableReader(rowCounts[(int)TableIndex.LocalConstant], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.LocalConstantTable.Block.Length; this.ImportScopeTable = new ImportScopeTableReader(rowCounts[(int)TableIndex.ImportScope], GetReferenceSize(rowCounts, TableIndex.ImportScope), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.ImportScopeTable.Block.Length; this.StateMachineMethodTable = new StateMachineMethodTableReader(rowCounts[(int)TableIndex.StateMachineMethod], IsDeclaredSorted(TableMask.StateMachineMethod), methodRefSizeCombined, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.StateMachineMethodTable.Block.Length; this.CustomDebugInformationTable = new CustomDebugInformationTableReader(rowCounts[(int)TableIndex.CustomDebugInformation], IsDeclaredSorted(TableMask.CustomDebugInformation), hasCustomDebugInformationRefSizeCombined, guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize); totalRequiredSize += this.CustomDebugInformationTable.Block.Length; if (totalRequiredSize > metadataTablesMemoryBlock.Length) { throw new BadImageFormatException(SR.MetadataTablesTooSmall); } } private static int[] CombineRowCounts(int[] local, int[] external, TableIndex firstLocalTableIndex) { Debug.Assert(local.Length == external.Length); var rowCounts = new int[local.Length]; for (int i = 0; i < (int)firstLocalTableIndex; i++) { rowCounts[i] = external[i]; } for (int i = (int)firstLocalTableIndex; i < rowCounts.Length; i++) { rowCounts[i] = local[i]; } return rowCounts; } private int ComputeCodedTokenSize(int largeRowSize, int[] rowCounts, TableMask tablesReferenced) { if (IsMinimalDelta) { return LargeIndexSize; } bool isAllReferencedTablesSmall = true; ulong tablesReferencedMask = (ulong)tablesReferenced; for (int tableIndex = 0; tableIndex < MetadataTokens.TableCount; tableIndex++) { if ((tablesReferencedMask & 1) != 0) { isAllReferencedTablesSmall = isAllReferencedTablesSmall && (rowCounts[tableIndex] < largeRowSize); } tablesReferencedMask >>= 1; } return isAllReferencedTablesSmall ? SmallIndexSize : LargeIndexSize; } private bool IsDeclaredSorted(TableMask index) { return (_sortedTables & index) != 0; } #endregion #region Helpers // internal for testing internal NamespaceCache NamespaceCache { get { return namespaceCache; } } internal bool UseFieldPtrTable { get { return this.FieldPtrTable.NumberOfRows > 0; } } internal bool UseMethodPtrTable { get { return this.MethodPtrTable.NumberOfRows > 0; } } internal bool UseParamPtrTable { get { return this.ParamPtrTable.NumberOfRows > 0; } } internal bool UseEventPtrTable { get { return this.EventPtrTable.NumberOfRows > 0; } } internal bool UsePropertyPtrTable { get { return this.PropertyPtrTable.NumberOfRows > 0; } } internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId) { int typeDefRowId = typeDef.RowId; firstFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId); if (firstFieldRowId == 0) { firstFieldRowId = 1; lastFieldRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastFieldRowId = (this.UseFieldPtrTable) ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows; } else { lastFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1; } } internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId) { int typeDefRowId = typeDef.RowId; firstMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId); if (firstMethodRowId == 0) { firstMethodRowId = 1; lastMethodRowId = 0; } else if (typeDefRowId == this.TypeDefTable.NumberOfRows) { lastMethodRowId = (this.UseMethodPtrTable) ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows; } else { lastMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1; } } internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId) { int eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef); if (eventMapRowId == 0) { firstEventRowId = 1; lastEventRowId = 0; return; } firstEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId); if (eventMapRowId == this.EventMapTable.NumberOfRows) { lastEventRowId = this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows; } else { lastEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1; } } internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId) { int propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef); if (propertyMapRowId == 0) { firstPropertyRowId = 1; lastPropertyRowId = 0; return; } firstPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId); if (propertyMapRowId == this.PropertyMapTable.NumberOfRows) { lastPropertyRowId = (this.UsePropertyPtrTable) ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows; } else { lastPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1; } } internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId) { int rid = methodDef.RowId; firstParamRowId = this.MethodDefTable.GetParamStart(rid); if (firstParamRowId == 0) { firstParamRowId = 1; lastParamRowId = 0; } else if (rid == this.MethodDefTable.NumberOfRows) { lastParamRowId = (this.UseParamPtrTable ? this.ParamPtrTable.NumberOfRows : this.ParamTable.NumberOfRows); } else { lastParamRowId = this.MethodDefTable.GetParamStart(rid + 1) - 1; } } internal void GetLocalVariableRange(LocalScopeHandle scope, out int firstVariableRowId, out int lastVariableRowId) { int scopeRowId = scope.RowId; firstVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId); if (firstVariableRowId == 0) { firstVariableRowId = 1; lastVariableRowId = 0; } else if (scopeRowId == this.LocalScopeTable.NumberOfRows) { lastVariableRowId = this.LocalVariableTable.NumberOfRows; } else { lastVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId + 1) - 1; } } internal void GetLocalConstantRange(LocalScopeHandle scope, out int firstConstantRowId, out int lastConstantRowId) { int scopeRowId = scope.RowId; firstConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId); if (firstConstantRowId == 0) { firstConstantRowId = 1; lastConstantRowId = 0; } else if (scopeRowId == this.LocalScopeTable.NumberOfRows) { lastConstantRowId = this.LocalConstantTable.NumberOfRows; } else { lastConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId + 1) - 1; } } #endregion #region Public APIs /// <summary> /// Pointer to the underlying data. /// </summary> public unsafe byte* MetadataPointer => Block.Pointer; /// <summary> /// Length of the underlying data. /// </summary> public int MetadataLength => Block.Length; /// <summary> /// Options passed to the constructor. /// </summary> public MetadataReaderOptions Options => _options; /// <summary> /// Version string read from metadata header. /// </summary> public string MetadataVersion => _versionString; /// <summary> /// Information decoded from #Pdb stream, or null if the stream is not present. /// </summary> public DebugMetadataHeader DebugMetadataHeader => _debugMetadataHeader; /// <summary> /// The kind of the metadata (plain ECMA335, WinMD, etc.). /// </summary> public MetadataKind MetadataKind => _metadataKind; /// <summary> /// Comparer used to compare strings stored in metadata. /// </summary> public MetadataStringComparer StringComparer => new MetadataStringComparer(this); /// <summary> /// Returns true if the metadata represent an assembly. /// </summary> public bool IsAssembly => AssemblyTable.NumberOfRows == 1; public AssemblyReferenceHandleCollection AssemblyReferences => new AssemblyReferenceHandleCollection(this); public TypeDefinitionHandleCollection TypeDefinitions => new TypeDefinitionHandleCollection(TypeDefTable.NumberOfRows); public TypeReferenceHandleCollection TypeReferences => new TypeReferenceHandleCollection(TypeRefTable.NumberOfRows); public CustomAttributeHandleCollection CustomAttributes => new CustomAttributeHandleCollection(this); public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes => new DeclarativeSecurityAttributeHandleCollection(this); public MemberReferenceHandleCollection MemberReferences => new MemberReferenceHandleCollection(MemberRefTable.NumberOfRows); public ManifestResourceHandleCollection ManifestResources => new ManifestResourceHandleCollection(ManifestResourceTable.NumberOfRows); public AssemblyFileHandleCollection AssemblyFiles => new AssemblyFileHandleCollection(FileTable.NumberOfRows); public ExportedTypeHandleCollection ExportedTypes => new ExportedTypeHandleCollection(ExportedTypeTable.NumberOfRows); public MethodDefinitionHandleCollection MethodDefinitions => new MethodDefinitionHandleCollection(this); public FieldDefinitionHandleCollection FieldDefinitions => new FieldDefinitionHandleCollection(this); public EventDefinitionHandleCollection EventDefinitions => new EventDefinitionHandleCollection(this); public PropertyDefinitionHandleCollection PropertyDefinitions => new PropertyDefinitionHandleCollection(this); public DocumentHandleCollection Documents => new DocumentHandleCollection(this); public MethodDebugInformationHandleCollection MethodDebugInformation => new MethodDebugInformationHandleCollection(this); public LocalScopeHandleCollection LocalScopes => new LocalScopeHandleCollection(this, 0); public LocalVariableHandleCollection LocalVariables => new LocalVariableHandleCollection(this, default(LocalScopeHandle)); public LocalConstantHandleCollection LocalConstants => new LocalConstantHandleCollection(this, default(LocalScopeHandle)); public ImportScopeCollection ImportScopes => new ImportScopeCollection(this); public CustomDebugInformationHandleCollection CustomDebugInformation => new CustomDebugInformationHandleCollection(this); public AssemblyDefinition GetAssemblyDefinition() { if (!IsAssembly) { throw new InvalidOperationException(SR.MetadataImageDoesNotRepresentAnAssembly); } return new AssemblyDefinition(this); } public string GetString(StringHandle handle) { return StringStream.GetString(handle, utf8Decoder); } public string GetString(NamespaceDefinitionHandle handle) { if (handle.HasFullName) { return StringStream.GetString(handle.GetFullName(), utf8Decoder); } return namespaceCache.GetFullName(handle); } public byte[] GetBlobBytes(BlobHandle handle) { return BlobStream.GetBytes(handle); } public ImmutableArray<byte> GetBlobContent(BlobHandle handle) { // TODO: We can skip a copy for virtual blobs. byte[] bytes = GetBlobBytes(handle); return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes); } public BlobReader GetBlobReader(BlobHandle handle) { return BlobStream.GetBlobReader(handle); } public string GetUserString(UserStringHandle handle) { return UserStringStream.GetString(handle); } public Guid GetGuid(GuidHandle handle) { return GuidStream.GetGuid(handle); } public ModuleDefinition GetModuleDefinition() { if (_debugMetadataHeader != null) { throw new InvalidOperationException(SR.StandaloneDebugMetadataImageDoesNotContainModuleTable); } return new ModuleDefinition(this); } public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle) { return new AssemblyReference(this, handle.Value); } public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle)); } public NamespaceDefinition GetNamespaceDefinitionRoot() { NamespaceData data = namespaceCache.GetRootNamespace(); return new NamespaceDefinition(data); } public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle) { NamespaceData data = namespaceCache.GetNamespaceData(handle); return new NamespaceDefinition(data); } private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeDefTreatmentAndRowId(handle); } public TypeReference GetTypeReference(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle)); } private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateTypeRefTreatmentAndRowId(handle); } public ExportedType GetExportedType(ExportedTypeHandle handle) { return new ExportedType(this, handle.RowId); } public CustomAttributeHandleCollection GetCustomAttributes(EntityHandle handle) { Debug.Assert(!handle.IsNil); return new CustomAttributeHandleCollection(this, handle); } public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle)); } private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return TreatmentAndRowId((byte)CustomAttributeTreatment.WinMD, handle.RowId); } public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new DeclarativeSecurityAttribute(this, handle.RowId); } public Constant GetConstant(ConstantHandle handle) { return new Constant(this, handle.RowId); } public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle)); } private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMethodDefTreatmentAndRowId(handle); } public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle)); } private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateFieldDefTreatmentAndRowId(handle); } public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle) { return new PropertyDefinition(this, handle); } public EventDefinition GetEventDefinition(EventDefinitionHandle handle) { return new EventDefinition(this, handle); } public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle) { return new MethodImplementation(this, handle); } public MemberReference GetMemberReference(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle)); } private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle) { // PERF: This code pattern is JIT friendly and results in very efficient code. if (_metadataKind == MetadataKind.Ecma335) { return (uint)handle.RowId; } return CalculateMemberRefTreatmentAndRowId(handle); } public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle) { return new MethodSpecification(this, handle); } public Parameter GetParameter(ParameterHandle handle) { return new Parameter(this, handle); } public GenericParameter GetGenericParameter(GenericParameterHandle handle) { return new GenericParameter(this, handle); } public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle) { return new GenericParameterConstraint(this, handle); } public ManifestResource GetManifestResource(ManifestResourceHandle handle) { return new ManifestResource(this, handle); } public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle) { return new AssemblyFile(this, handle); } public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle) { return new StandaloneSignature(this, handle); } public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle) { return new TypeSpecification(this, handle); } public ModuleReference GetModuleReference(ModuleReferenceHandle handle) { return new ModuleReference(this, handle); } public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle) { return new InterfaceImplementation(this, handle); } internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef) { int methodRowId; if (UseMethodPtrTable) { methodRowId = MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId); } else { methodRowId = methodDef.RowId; } return TypeDefTable.FindTypeContainingMethod(methodRowId, MethodDefTable.NumberOfRows); } internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef) { int fieldRowId; if (UseFieldPtrTable) { fieldRowId = FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId); } else { fieldRowId = fieldDef.RowId; } return TypeDefTable.FindTypeContainingField(fieldRowId, FieldTable.NumberOfRows); } private static readonly ObjectPool<StringBuilder> s_stringBuilderPool = new ObjectPool<StringBuilder>(() => new StringBuilder()); public string GetString(DocumentNameBlobHandle handle) { return BlobStream.GetDocumentName(handle); } public Document GetDocument(DocumentHandle handle) { return new Document(this, handle); } public MethodDebugInformation GetMethodDebugInformation(MethodDebugInformationHandle handle) { return new MethodDebugInformation(this, handle); } public MethodDebugInformation GetMethodDebugInformation(MethodDefinitionHandle handle) { return new MethodDebugInformation(this, MethodDebugInformationHandle.FromRowId(handle.RowId)); } public LocalScope GetLocalScope(LocalScopeHandle handle) { return new LocalScope(this, handle); } public LocalVariable GetLocalVariable(LocalVariableHandle handle) { return new LocalVariable(this, handle); } public LocalConstant GetLocalConstant(LocalConstantHandle handle) { return new LocalConstant(this, handle); } public ImportScope GetImportScope(ImportScopeHandle handle) { return new ImportScope(this, handle); } public CustomDebugInformation GetCustomDebugInformation(CustomDebugInformationHandle handle) { return new CustomDebugInformation(this, handle); } public CustomDebugInformationHandleCollection GetCustomDebugInformation(EntityHandle handle) { Debug.Assert(!handle.IsNil); return new CustomDebugInformationHandleCollection(this, handle); } public LocalScopeHandleCollection GetLocalScopes(MethodDefinitionHandle handle) { return new LocalScopeHandleCollection(this, handle.RowId); } public LocalScopeHandleCollection GetLocalScopes(MethodDebugInformationHandle handle) { return new LocalScopeHandleCollection(this, handle.RowId); } #endregion #region Nested Types private void InitializeNestedTypesMap() { var groupedNestedTypes = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>.Builder>(); int numberOfNestedTypes = NestedClassTable.NumberOfRows; ImmutableArray<TypeDefinitionHandle>.Builder builder = null; TypeDefinitionHandle previousEnclosingClass = default(TypeDefinitionHandle); for (int i = 1; i <= numberOfNestedTypes; i++) { TypeDefinitionHandle enclosingClass = NestedClassTable.GetEnclosingClass(i); Debug.Assert(!enclosingClass.IsNil); if (enclosingClass != previousEnclosingClass) { if (!groupedNestedTypes.TryGetValue(enclosingClass, out builder)) { builder = ImmutableArray.CreateBuilder<TypeDefinitionHandle>(); groupedNestedTypes.Add(enclosingClass, builder); } previousEnclosingClass = enclosingClass; } else { Debug.Assert(builder == groupedNestedTypes[enclosingClass]); } builder.Add(NestedClassTable.GetNestedClass(i)); } var nestedTypesMap = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>>(); foreach (var group in groupedNestedTypes) { nestedTypesMap.Add(group.Key, group.Value.ToImmutable()); } _lazyNestedTypesMap = nestedTypesMap; } /// <summary> /// Returns an array of types nested in the specified type. /// </summary> internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef) { if (_lazyNestedTypesMap == null) { InitializeNestedTypesMap(); } ImmutableArray<TypeDefinitionHandle> nestedTypes; if (_lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes)) { return nestedTypes; } return ImmutableArray<TypeDefinitionHandle>.Empty; } #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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using Azure; using DataLake; using Management; using Azure; using Management; using DataLake; using Models; using Rest; using Rest.Azure; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for FirewallRulesOperations. /// </summary> public static partial class FirewallRulesOperationsExtensions { /// <summary> /// Creates or updates the specified firewall rule. During update, the firewall /// rule with the specified name will be replaced with this new firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to add or replace the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to create or update. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update the firewall rule. /// </param> public static FirewallRule CreateOrUpdate(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, FirewallRule parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, accountName, firewallRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified firewall rule. During update, the firewall /// rule with the specified name will be replaced with this new firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to add or replace the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to create or update. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update the firewall rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FirewallRule> CreateOrUpdateAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, FirewallRule parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the specified firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to update the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to update. /// </param> /// <param name='parameters'> /// Parameters supplied to update the firewall rule. /// </param> public static FirewallRule Update(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, UpdateFirewallRuleParameters parameters = default(UpdateFirewallRuleParameters)) { return operations.UpdateAsync(resourceGroupName, accountName, firewallRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates the specified firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to update the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to update. /// </param> /// <param name='parameters'> /// Parameters supplied to update the firewall rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FirewallRule> UpdateAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, UpdateFirewallRuleParameters parameters = default(UpdateFirewallRuleParameters), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified firewall rule from the specified Data Lake Store /// account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to delete. /// </param> public static void Delete(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { operations.DeleteAsync(resourceGroupName, accountName, firewallRuleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified firewall rule from the specified Data Lake Store /// account /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to delete. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Data Lake Store firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to retrieve. /// </param> public static FirewallRule Get(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName) { return operations.GetAsync(resourceGroupName, accountName, firewallRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified Data Lake Store firewall rule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rule. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to retrieve. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FirewallRule> GetAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, string firewallRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, firewallRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rules. /// </param> public static IPage<FirewallRule> ListByAccount(this IFirewallRulesOperations operations, string resourceGroupName, string accountName) { return operations.ListByAccountAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the firewall /// rules. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FirewallRule>> ListByAccountAsync(this IFirewallRulesOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<FirewallRule> ListByAccountNext(this IFirewallRulesOperations operations, string nextPageLink) { return operations.ListByAccountNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists the Data Lake Store firewall rules within the specified Data Lake /// Store account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FirewallRule>> ListByAccountNextAsync(this IFirewallRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByAccountNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
#if !NOT_UNITY3D using System; using System.Collections.Generic; using ModestTree; using UnityEngine; using System.Linq; using ModestTree.Util; namespace Zenject { public class InitialComponentsInjecter : IProvider { readonly DiContainer _container; readonly Dictionary<Component, ComponentInfo> _componentMap = new Dictionary<Component, ComponentInfo>(); readonly Dictionary<BindingId, List<ComponentInfo>> _bindings = new Dictionary<BindingId, List<ComponentInfo>>(); public InitialComponentsInjecter( DiContainer container, List<Component> injectableComponents) { _container = container; _componentMap = injectableComponents.ToDictionary(x => x, x => new ComponentInfo(x)); // Installers are always injected just before calling Install() Assert.That(injectableComponents.Where(x => x.GetType().DerivesFrom<MonoInstaller>()).IsEmpty()); } public IEnumerable<Component> Components { get { return _componentMap.Keys; } } public void InstallBinding(ZenjectBinding binding) { if (!binding.enabled) { return; } if (binding.Components == null || binding.Components.IsEmpty()) { Log.Warn("Found empty list of components on ZenjectBinding on object '{0}'", binding.name); return; } string identifier = null; if (binding.Identifier.Trim().Length > 0) { identifier = binding.Identifier; } foreach (var component in binding.Components) { var bindType = binding.BindType; if (component == null) { Log.Warn("Found null component in ZenjectBinding on object '{0}'", binding.name); continue; } var componentType = component.GetType(); ComponentInfo componentInfo; if (_componentMap.TryGetValue(component, out componentInfo)) { switch (bindType) { case ZenjectBinding.BindTypes.Self: { InstallSingleBinding(componentType, identifier, componentInfo); break; } case ZenjectBinding.BindTypes.AllInterfaces: { foreach (var baseType in componentType.Interfaces()) { InstallSingleBinding(baseType, identifier, componentInfo); } break; } case ZenjectBinding.BindTypes.AllInterfacesAndSelf: { foreach (var baseType in componentType.Interfaces()) { InstallSingleBinding(baseType, identifier, componentInfo); } InstallSingleBinding(componentType, identifier, componentInfo); break; } default: { throw Assert.CreateException(); } } } else { // In this case, we are adding a binding for a component that does not exist // in our 'context'. So we are not responsible for injecting it - there is // another InitialComponentsInjecter that does this. // Best we can do here is just add the instance to our container // This may result in the instance being injected somewhere without itself // being injected, but there's not much we can do about that InstallNonInjectedBinding(bindType, identifier, component); } } } void InstallNonInjectedBinding(ZenjectBinding.BindTypes bindType, string identifier, Component component) { switch (bindType) { case ZenjectBinding.BindTypes.Self: { _container.Bind(component.GetType()).WithId(identifier).FromInstance(component, true); break; } case ZenjectBinding.BindTypes.AllInterfaces: { _container.BindAllInterfaces(component.GetType()).WithId(identifier).FromInstance(component, true); break; } case ZenjectBinding.BindTypes.AllInterfacesAndSelf: { _container.BindAllInterfacesAndSelf(component.GetType()).WithId(identifier).FromInstance(component, true); break; } default: { throw Assert.CreateException(); } } } public void LazyInjectComponents() { foreach (var info in _componentMap.Values) { LazyInject(info); } } void InstallSingleBinding(Type type, string identifier, ComponentInfo componentInfo) { var bindingId = new BindingId(type, identifier); List<ComponentInfo> infoList; if (!_bindings.TryGetValue(bindingId, out infoList)) { infoList = new List<ComponentInfo>(); _bindings.Add(bindingId, infoList); // Note: We only want to register for each unique BindingId once // since we return multiple matches in GetAllInstancesWithInjectSplit _container.RegisterProvider(bindingId, null, this); } infoList.Add(componentInfo); } public Type GetInstanceType(InjectContext context) { return context.MemberType; } public IEnumerator<List<object>> GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args) { var infoList = GetBoundInfosWithId(context.GetBindingId()); yield return infoList.Select(x => (object)x.Component).ToList(); foreach (var info in infoList) { LazyInject(info); } } void LazyInject(ComponentInfo info) { if (!info.HasInjected) { info.HasInjected = true; _container.Inject(info.Component); } } List<ComponentInfo> GetBoundInfosWithId(BindingId bindingId) { List<ComponentInfo> result; if (!_bindings.TryGetValue(bindingId, out result)) { result = new List<ComponentInfo>(); } return result; } class ComponentInfo { public ComponentInfo(Component component) { Component = component; } public bool HasInjected { get; set; } public Component Component { get; private set; } } } } #endif
//! \file ImageTIFF.cs //! \date Mon Jul 07 06:39:45 2014 //! \brief TIFF image implementation. // // Copyright (C) 2014 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.ComponentModel.Composition; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes { [Export(typeof(ImageFormat))] public class TifFormat : ImageFormat { public override string Tag { get { return "TIFF"; } } public override string Description { get { return "Tagged Image File Format"; } } public override uint Signature { get { return 0; } } public TifFormat () { Extensions = new string[] { "tif", "tiff" }; Signatures = new uint[] { 0x002a4949, 0x2a004d4d }; } public override ImageData Read (Stream file, ImageMetaData info) { var decoder = new TiffBitmapDecoder (file, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); var frame = decoder.Frames[0]; frame.Freeze(); return new ImageData (frame, info); } public override void Write (Stream file, ImageData image) { var encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.Zip; encoder.Frames.Add (BitmapFrame.Create (image.Bitmap)); encoder.Save (file); } private delegate uint UInt32Reader(); private delegate ushort UInt16Reader(); enum TIFF { ImageWidth = 0x100, ImageHeight = 0x101, BitsPerSample = 0x102, Compression = 0x103, SamplesPerPixel = 0x115, XResolution = 0x11a, YResolution = 0x11b, XPosition = 0x11e, YPosition = 0x11f, } enum TagType { Byte = 1, Ascii = 2, Short = 3, Long = 4, Rational = 5, SByte = 6, Undefined = 7, SShort = 8, SLong = 9, SRational = 10, Float = 11, Double = 12, LastKnown = Double, } enum MetaParsed { None = 0, Width = 1, Height = 2, BPP = 4, PosX = 8, PosY = 16, Sufficient = Width|Height|BPP, Complete = Sufficient|PosX|PosY, } public override ImageMetaData ReadMetaData (Stream stream) { using (var file = new Parser (stream)) return file.ReadMetaData(); } public class Parser : IDisposable { private BinaryReader m_file; private readonly bool m_is_bigendian; private readonly uint m_first_ifd; private readonly uint[] m_type_size = { 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8 }; private delegate ushort UInt16Reader (); private delegate uint UInt32Reader (); private delegate ulong UInt64Reader (); UInt16Reader ReadUInt16; UInt32Reader ReadUInt32; UInt64Reader ReadUInt64; public Parser (Stream file) { m_file = new ArcView.Reader (file); uint signature = m_file.ReadUInt32(); m_is_bigendian = 0x2a004d4d == signature; if (m_is_bigendian) { ReadUInt16 = () => Binary.BigEndian (m_file.ReadUInt16()); ReadUInt32 = () => Binary.BigEndian (m_file.ReadUInt32()); ReadUInt64 = () => Binary.BigEndian (m_file.ReadUInt64()); } else { ReadUInt16 = () => m_file.ReadUInt16(); ReadUInt32 = () => m_file.ReadUInt32(); ReadUInt64 = () => m_file.ReadUInt64(); } m_first_ifd = ReadUInt32(); } public long FindLastIFD () { uint ifd = m_first_ifd; for (;;) { m_file.BaseStream.Position = ifd; uint tag_count = ReadUInt16(); ifd += 2 + tag_count*12; uint ifd_next = ReadUInt32(); if (0 == ifd_next) break; if (ifd_next == ifd || ifd_next >= m_file.BaseStream.Length) return -1; ifd = ifd_next; } return ifd; } public ImageMetaData ReadMetaData () { MetaParsed parsed = MetaParsed.None; int width = 0, height = 0, bpp = 0, pos_x = 0, pos_y = 0; uint ifd = m_first_ifd; while (ifd != 0 && parsed != MetaParsed.Complete) { m_file.BaseStream.Position = ifd; uint tag_count = ReadUInt16(); ifd += 2; for (uint i = 0; i < tag_count && parsed != MetaParsed.Complete; ++i) { ushort tag = ReadUInt16(); TagType type = (TagType)ReadUInt16(); uint count = ReadUInt32(); if (0 != count && 0 != type && type <= TagType.LastKnown) { switch ((TIFF)tag) { case TIFF.ImageWidth: if (1 == count) if (ReadOffsetValue (type, out width)) parsed |= MetaParsed.Width; break; case TIFF.ImageHeight: if (1 == count) if (ReadOffsetValue (type, out height)) parsed |= MetaParsed.Height; break; case TIFF.XPosition: if (1 == count) if (ReadOffsetValue (type, out pos_x)) parsed |= MetaParsed.PosX; break; case TIFF.YPosition: if (1 == count) if (ReadOffsetValue (type, out pos_y)) parsed |= MetaParsed.PosY; break; case TIFF.BitsPerSample: if (count * GetTypeSize (type) > 4) { var bpp_offset = ReadUInt32(); m_file.BaseStream.Position = bpp_offset; } bpp = 0; for (uint b = 0; b < count; ++b) { int plane = 0; ReadValue (type, out plane); bpp += plane; } parsed |= MetaParsed.BPP; break; default: break; } } ifd += 12; m_file.BaseStream.Position = ifd; } uint ifd_next = ReadUInt32(); if (ifd_next == ifd) break; ifd = ifd_next; } if (MetaParsed.Sufficient == (parsed & MetaParsed.Sufficient)) return new ImageMetaData() { Width = (uint)width, Height = (uint)height, OffsetX = pos_x, OffsetY = pos_y, BPP = bpp, }; else return null; } uint GetTypeSize (TagType type) { if ((int)type < m_type_size.Length) return m_type_size[(int)type]; else return 0; } bool ReadOffsetValue (TagType type, out int value) { if (GetTypeSize (type) > 4) m_file.BaseStream.Position = ReadUInt32(); return ReadValue (type, out value); } bool ReadValue (TagType type, out int value) { switch (type) { case TagType.Undefined: case TagType.SByte: case TagType.Byte: value = m_file.ReadByte(); break; default: case TagType.Ascii: value = 0; return false; case TagType.SShort: case TagType.Short: value = ReadUInt16(); break; case TagType.SLong: case TagType.Long: value = (int)ReadUInt32(); break; case TagType.Rational: return ReadRational (out value); case TagType.SRational: return ReadSRational (out value); case TagType.Float: return ReadFloat (out value); case TagType.Double: return ReadDouble (out value); } return true; } bool ReadRational (out int value) { uint numer = ReadUInt32(); uint denom = ReadUInt32(); if (1 == denom) value = (int)numer; else if (0 == denom) { value = 0; return false; } else value = (int)((double)numer / denom); return true; } bool ReadSRational (out int value) { int numer = (int)ReadUInt32(); int denom = (int)ReadUInt32(); if (1 == denom) value = numer; else if (0 == denom) { value = 0; return false; } else value = (int)((double)numer / denom); return true; } bool ReadFloat (out int value) { var convert_buffer = new byte[4]; if (4 != m_file.Read (convert_buffer, 0, 4)) { value = 0; return false; } if (m_is_bigendian) Array.Reverse (convert_buffer); value = (int)BitConverter.ToSingle (convert_buffer, 0); return true; } bool ReadDouble (out int value) { var convert_buffer = new byte[8]; if (8 != m_file.Read (convert_buffer, 0, 8)) { value = 0; return false; } if (m_is_bigendian) Array.Reverse (convert_buffer); long bits = BitConverter.ToInt64 (convert_buffer, 0); value = (int)BitConverter.Int64BitsToDouble (bits); return true; } #region IDisposable Members bool disposed = false; public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (!disposed) { if (disposing) { m_file.Dispose(); } m_file = null; disposed = true; } } #endregion } } }
//------------------------------------------------------------------------------ // <copyright file="ParameterCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Data; using System.Drawing.Design; using System.Globalization; using System.Reflection; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Util; /// <devdoc> /// A state managed collection of Parameter objects. /// These are used in many DataSourceControls to filter queries. /// </devdoc> [ Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), ] public class ParameterCollection : StateManagedCollection { private EventHandler _parametersChangedHandler; private static readonly Type[] knownTypes = new Type[] { typeof(ControlParameter), typeof(CookieParameter), typeof(FormParameter), typeof(Parameter), typeof(QueryStringParameter), typeof(SessionParameter), typeof(ProfileParameter), }; /// <devdoc> /// Returns the Parameter at a given index. /// </devdoc> public Parameter this[int index] { get { return (Parameter)((IList)this)[index]; } set { ((IList)this)[index] = value; } } /// <devdoc> /// Returns the Parameter with a given name. /// </devdoc> public Parameter this[string name] { get { int parameterIndex = GetParameterIndex(name); if (parameterIndex == -1) { return null; } return this[parameterIndex]; } set { int parameterIndex = GetParameterIndex(name); if (parameterIndex == -1) { Add(value); } else { this[parameterIndex] = value; } } } /// <devdoc> /// Occurs when any of the Parameter objects in the collection change or when the collection itself changes. /// </devdoc> public event EventHandler ParametersChanged { add { _parametersChangedHandler = (EventHandler)Delegate.Combine(_parametersChangedHandler, value); } remove { _parametersChangedHandler = (EventHandler)Delegate.Remove(_parametersChangedHandler, value); } } /// <devdoc> /// Adds a Parameter to the collection. /// </devdoc> public int Add(Parameter parameter) { return ((IList)this).Add(parameter); } /// <devdoc> /// Adds a Parameter to the collection with a specified name and value. /// </devdoc> public int Add(string name, string value) { return ((IList)this).Add(new Parameter(name, TypeCode.Empty, value)); } /// <devdoc> /// Adds a Parameter to the collection with a specified name, type, and value. /// </devdoc> public int Add(string name, TypeCode type, string value) { return ((IList)this).Add(new Parameter(name, type, value)); } /// <devdoc> /// Adds a Parameter to the collection with a specified name, database type, and value. /// </devdoc> public int Add(string name, DbType dbType, string value) { return ((IList)this).Add(new Parameter(name, dbType, value)); } /// <devdoc> /// Used by Parameters to raise the ParametersChanged event. /// </devdoc> internal void CallOnParametersChanged() { OnParametersChanged(EventArgs.Empty); } public bool Contains(Parameter parameter) { return ((IList)this).Contains(parameter); } public void CopyTo(Parameter[] parameterArray, int index) { base.CopyTo(parameterArray, index); } /// <devdoc> /// Creates a known type of Parameter. /// </devdoc> protected override object CreateKnownType(int index) { switch (index) { case 0: return new ControlParameter(); case 1: return new CookieParameter(); case 2: return new FormParameter(); case 3: return new Parameter(); case 4: return new QueryStringParameter(); case 5: return new SessionParameter(); case 6: return new ProfileParameter(); default: throw new ArgumentOutOfRangeException("index"); } } /// <devdoc> /// Returns an ArrayList of known Parameter types. /// </devdoc> protected override Type[] GetKnownTypes() { return knownTypes; } /// <devdoc> /// Returns the index of a parameter by name. /// </devdoc> private int GetParameterIndex(string name) { for (int i = 0; i < Count; i++) { if (String.Equals(this[i].Name, name, StringComparison.OrdinalIgnoreCase)) { return i; } } return -1; } /// <devdoc> /// Returns an IDictionary containing Name / Value pairs of all the parameters. /// </devdoc> public IOrderedDictionary GetValues(HttpContext context, Control control) { UpdateValues(context, control); // Create dictionary IOrderedDictionary valueDictionary = new OrderedDictionary(); // Add Parameters foreach (Parameter param in this) { // For the OrderedDictionary, every parameter must have a unique name, so in some cases we have to alter them. string uniqueName = param.Name; int count = 1; while (valueDictionary.Contains(uniqueName)) { uniqueName = param.Name + count.ToString(CultureInfo.InvariantCulture); count++; } valueDictionary.Add(uniqueName, param.ParameterValue); } return valueDictionary; } public int IndexOf(Parameter parameter) { return ((IList)this).IndexOf(parameter); } /// <devdoc> /// Inserts a Parameter into the collection. /// </devdoc> public void Insert(int index, Parameter parameter) { ((IList)this).Insert(index, parameter); } /// <devdoc> /// Called when the Clear() method is complete. /// </devdoc> protected override void OnClearComplete() { base.OnClearComplete(); OnParametersChanged(EventArgs.Empty); } /// <devdoc> /// Called when the Insert() method is starting. /// Adds an event handler to listen to the Parameter's ParameterChanged event. /// </devdoc> protected override void OnInsert(int index, object value) { base.OnInsert(index, value); // Set owner (we are guaranteed that it is a Parameter // in OnValidate). ((Parameter)value).SetOwner(this); } /// <devdoc> /// Called when the Insert() method is complete. /// </devdoc> protected override void OnInsertComplete(int index, object value) { base.OnInsertComplete(index, value); OnParametersChanged(EventArgs.Empty); } /// <devdoc> /// Raises the ParametersChanged event. /// </devdoc> protected virtual void OnParametersChanged(EventArgs e) { if (_parametersChangedHandler != null) { _parametersChangedHandler(this, e); } } /// <devdoc> /// Called when the Remove() method is complete. /// </devdoc> protected override void OnRemoveComplete(int index, object value) { base.OnRemoveComplete(index, value); // Clear owner ((Parameter)value).SetOwner(null); OnParametersChanged(EventArgs.Empty); } /// <devdoc> /// Validates that an object is a Parameter. /// </devdoc> protected override void OnValidate(object o) { base.OnValidate(o); if (!(o is Parameter)) throw new ArgumentException(SR.GetString(SR.ParameterCollection_NotParameter), "o"); } /// <devdoc> /// Removes a Parameter from the collection. /// </devdoc> public void Remove(Parameter parameter) { ((IList)this).Remove(parameter); } /// <devdoc> /// Removes a Parameter from the collection at a given index. /// </devdoc> public void RemoveAt(int index) { ((IList)this).RemoveAt(index); } /// <devdoc> /// Marks a Parameter as dirty so that it will record its entire state into view state. /// </devdoc> protected override void SetDirtyObject(object o) { ((Parameter)o).SetDirty(); } /// <devdoc> /// Updates all parameter values to possibly raise a ParametersChanged event. /// </devdoc> public void UpdateValues(HttpContext context, Control control) { foreach (Parameter param in this) { param.UpdateValue(context, control); } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.Cms { using System; using System.Diagnostics.Tracing; using System.Globalization; using System.Threading; using Adxstudio.Xrm.AspNet.Cms; using Adxstudio.Xrm.Core.Telemetry.EventSources; using Adxstudio.Xrm.Diagnostics.Metrics; using Adxstudio.Xrm.EventHubBasedInvalidation; using Microsoft.Xrm.Client; using Microsoft.Xrm.Sdk; [EventSource(Guid = "88E12386-900A-401D-92BA-CAFAF3FC6AEF", Name = InternalName)] internal sealed class CmsEventSource : EventSourceBase { /// <summary> /// The EventSource name. /// </summary> private const string InternalName = "PortalCms"; private static readonly Lazy<CmsEventSource> _instance = new Lazy<CmsEventSource>(); public static CmsEventSource Log { get { return _instance.Value; } } private enum EventName { /// <summary> /// A matching portal website binding has not been found. /// </summary> WebsiteBindingNotFound = 1, /// <summary> /// The required "Home" site marker for the current portal website has not been found. /// </summary> HomeSiteMarkerNotFound = 2, /// <summary> /// Content map read or write lock acquisition has failed. /// </summary> ContentMapLockTimeout = 3, /// <summary> /// Attempt to access attribute values from a content map reference node. /// </summary> /// <remarks> /// This is usually evidence of a content map corruption, which is usually evidence of /// a content map load/update issue. /// </remarks> ContentMapReferenceNodeAccess = 4, /// <summary> /// The status of the content map read or write lock. /// </summary> ContentMapLockStatus = 5, /// <summary> /// Event to log webhook notification received for scale out event. /// </summary> ScaleOutNotification = 6, /// <summary> /// Logs the latency information associated with the messages /// </summary> LatencyInfo = 7, } /// <summary> /// Log that content map read or write lock acquisition has failed. /// </summary> [NonEvent] public void ContentMapLockTimeout(ContentMapLockType lockType, ReaderWriterLockSlim contentMapLock) { ContentMapLockTimeout( lockType.ToString(), contentMapLock.IsReadLockHeld, contentMapLock.IsUpgradeableReadLockHeld, contentMapLock.IsWriteLockHeld, contentMapLock.CurrentReadCount, contentMapLock.RecursiveReadCount, contentMapLock.RecursiveUpgradeCount, contentMapLock.RecursiveWriteCount, contentMapLock.WaitingReadCount, contentMapLock.WaitingUpgradeCount, contentMapLock.WaitingWriteCount, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); } /// <summary> /// Log an attempt to access attribute values from a content map reference node. /// </summary> /// <remarks> /// This is usually evidence of a content map corruption, which is usually evidence of /// a content map load/update issue. /// </remarks> [Event((int)EventName.ContentMapLockTimeout, Message = "Lock Type : {0} Is Read Lock Held : {1} Is Upgradeble Lock Held : {2} Is Write Lock Held : {3} Current Read Count : {4} Recursive Read Count : {5} Recursive Upgrade Count : {6} Recursive Write Count : {7} Waiting Read Count : {8} Waiting Upgrade Count : {9} Waiting Write Count : {10} PortalUrl : {11} PortalVersion : {12} PortalProductionOrTrial : {13} SessionId : {14} ElapsedTime : {15}", Level = EventLevel.Error, Version = 3)] private void ContentMapLockTimeout(string lockType, bool isReadLockHeld, bool isUpgradeableReadLockHeld, bool isWriteLockHeld, int currentReadCount, int recursiveReadCount, int recursiveUpgradeCount, int recursiveWriteCount, int waitingReadCount, int waitingUpgradeCount, int waitingWriteCount, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { WriteEvent( EventName.ContentMapLockTimeout, lockType ?? string.Empty, isReadLockHeld, isUpgradeableReadLockHeld, isWriteLockHeld, currentReadCount, recursiveReadCount, recursiveUpgradeCount, recursiveWriteCount, waitingReadCount, waitingUpgradeCount, waitingWriteCount, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } /// <summary> /// Log the status of the content map read or write lock. /// </summary> [NonEvent] public void ContentMapLockStatus(ContentMapLockType lockType, string status, long duration) { ContentMapLockStatus( lockType.ToString(), status, duration, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); } /// <summary> /// Log the status of the content map read or write lock. /// </summary> [Event((int)EventName.ContentMapLockStatus, Message = "Lock Type : {0} Status : {1} Duration : {2} PortalUrl : {3} PortalVersion : {4} PortalProductionOrTrial : {5} SessionId : {6} ElapsedTime : {7}", Level = EventLevel.Informational, Version = 3)] private void ContentMapLockStatus(string lockType, string status, long duration, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { WriteEvent( EventName.ContentMapLockStatus, lockType ?? string.Empty, status ?? string.Empty, duration, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } [NonEvent] public void ContentMapReferenceNodeAccess(EntityReference reference, string attributeLogicalName) { if (reference == null) { return; } ContentMapReferenceNodeAccess( reference.LogicalName, reference.Id, attributeLogicalName, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); } [Event((int)EventName.ContentMapReferenceNodeAccess, Message = "Reference Entity Name : {0} Entity Id : {1} Attribute Name : {2} PortalUrl : {3} PortalVersion : {4} PortalProductionOrTrial : {5} SessionId : {6} ElapsedTime : {7}", Level = EventLevel.Error, Version = 3)] private void ContentMapReferenceNodeAccess(string logicalName, Guid id, string attributeLogicalName, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { WriteEvent(EventName.ContentMapReferenceNodeAccess, logicalName ?? string.Empty, id, attributeLogicalName ?? string.Empty, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } /// <summary> /// Log that the required "Home" site marker for the current portal website has not been found. /// </summary> [NonEvent] public void HomeSiteMarkerNotFound(WebsiteNode website) { if (website == null) { return; } HomeSiteMarkerNotFound( website.Name, website.Id, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); MdmMetrics.CmsHomeSiteMarkerNotFoundMetric.LogValue(1); } [Event((int)EventName.HomeSiteMarkerNotFound, Message = "Website Name : {0} Website Id : {1} PortalUrl : {2} PortalVersion : {3} PortalProductionOrTrial : {4} SessionId : {5} ElapsedTime : {6}", Level = EventLevel.Critical, Version = 3)] private void HomeSiteMarkerNotFound(string websiteName, Guid websiteId, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { WriteEvent(EventName.HomeSiteMarkerNotFound, websiteName ?? string.Empty, websiteId, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } /// <summary> /// Log that a matching portal website binding has not been found. /// </summary> [NonEvent] public void WebsiteBindingNotFoundByHostingEnvironment(PortalHostingEnvironment environment) { if (environment == null) { return; } WebsiteBindingNotFound( @"HostingEnvironment(SiteName=""{0}"" ApplicationVirtualPath=""{1}""). Current website binding is not present in database.".FormatWith(environment.SiteName, environment.ApplicationVirtualPath), this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); MdmMetrics.CmsWebsiteBindingNotFoundMetric.LogValue(1); } /// <summary> /// Log that a matching portal website binding has not been found. /// </summary> [NonEvent] public void WebsiteBindingNotFoundByWebsiteName(string websiteName) { WebsiteBindingNotFound( @"WebsiteName=""{0}""".FormatWith(websiteName), this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); MdmMetrics.CmsWebsiteBindingNotFoundMetric.LogValue(1); } [Event((int)EventName.WebsiteBindingNotFound, Message = "Website Name : {0} PortalUrl : {1} PortalVersion : {2} PortalProductionOrTrial : {3} SessionId : {4} ElapsedTime :5}", Level = EventLevel.Critical, Version = 3)] private void WebsiteBindingNotFound(string message, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { WriteEvent(EventName.WebsiteBindingNotFound, message ?? string.Empty, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } [NonEvent] public void ScaleOutNotification(string status, string operation, string notificationTimeStamp, string details, string oldCapacity, string newCapacity, string resourceId) { ScaleOutNotification( status ?? string.Empty, operation ?? string.Empty, notificationTimeStamp ?? string.Empty, details ?? string.Empty, oldCapacity ?? string.Empty, newCapacity ?? string.Empty, resourceId ?? string.Empty, this.PortalUrl, this.PortalVersion, this.ProductionOrTrial, this.SessionId, this.ElapsedTime()); } [Event((int)EventName.ScaleOutNotification, Message = "Status : {0} Operation : {1} NotificationTimeStamp : {2} Details : {3} OldCapacity : {4} NewCapacity : {5} ResourceId : {6} PortalUrl : {7} PortalVersion : {8} PortalProductionOrTrial : {9} SessionId : {10} ElapsedTime : {11}", Level = EventLevel.Critical, Version = 3)] private void ScaleOutNotification(string status, string operation, string notificationTimeStamp, string details, string oldCapacity, string newCapacity, string resourceId, string portalUrl, string portalVersion, string portalProductionOrTrialType, string sessionId, string elapsedTime) { WriteEvent( EventName.ScaleOutNotification, status ?? string.Empty, operation ?? string.Empty, notificationTimeStamp ?? string.Empty, details ?? string.Empty, oldCapacity ?? string.Empty, newCapacity ?? string.Empty, resourceId ?? string.Empty, portalUrl, portalVersion, portalProductionOrTrialType, sessionId, elapsedTime); } /// <summary> /// Logs Latency information given the subscriptionMessage /// </summary> /// <param name="subscriptionMessage">The <see cref="Exception"/> thrown.</param> /// <returns>Unique ID of event</returns> [NonEvent] public string LatencyInfo(ICrmSubscriptionMessage subscriptionMessage) { DateTime enqueueEventHubUtc = subscriptionMessage.EnqueuedEventhubTimeUtc; DateTime dequeueEventHubUtc = subscriptionMessage.DequeuedEventhubTimeUtc; TimeSpan eventHubLatency = dequeueEventHubUtc - enqueueEventHubUtc; DateTime enqueueTopicUtc = subscriptionMessage.EnqueuedTopicTimeUtc; DateTime dequeueTopicUtc = subscriptionMessage.DequeuedTopicTimeUtc; TimeSpan topicLatency = dequeueTopicUtc - enqueueTopicUtc; WriteEventLatencyInfo( subscriptionMessage.MessageId.ToString("D"), enqueueEventHubUtc.ToString(CultureInfo.InvariantCulture), dequeueEventHubUtc.ToString(CultureInfo.InvariantCulture), enqueueTopicUtc.ToString(CultureInfo.InvariantCulture), dequeueTopicUtc.ToString(CultureInfo.InvariantCulture), eventHubLatency.TotalSeconds.ToString(CultureInfo.InvariantCulture), topicLatency.TotalSeconds.ToString(CultureInfo.InvariantCulture), (topicLatency.TotalSeconds + eventHubLatency.TotalSeconds).ToString(CultureInfo.InvariantCulture), this.PortalUrl, this.PortalVersion, this.ProductionOrTrial); return GetActivityId(); } [Event((int)EventName.LatencyInfo, Message = "MessageId={0} enqueueEventHubUtc={1} dequeueEventHubUtc={2} enqueueTopicUtc={3} dequeueTopicUtc={4} eventhubLatency={5} topicLatency={6} totalLatency={7} portalUrl={8} portalVersion={9} portalProductionOrTrialType={10}", Level = EventLevel.Informational, Version = 1)] private void WriteEventLatencyInfo(string messageId, string enqueueEventHubUtc, string dequeueEventHubUtc, string enqueueTopicUtc, string dequeueTopicUtc, string eventhubLatency, string topicLatency, string totalLatency, string portalUrl, string portalVersion, string portalProductionOrTrialType) { WriteEvent(EventName.LatencyInfo, messageId, enqueueEventHubUtc, dequeueEventHubUtc, enqueueTopicUtc, dequeueTopicUtc, eventhubLatency, topicLatency, totalLatency, portalUrl, portalVersion, portalProductionOrTrialType); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Client { using System; using System.Diagnostics; using System.Threading; [DebuggerStepThrough] struct TimeoutHelper { DateTime deadline; bool deadlineSet; TimeSpan originalTimeout; public static readonly TimeSpan MaxWait = TimeSpan.FromMilliseconds(Int32.MaxValue); public TimeoutHelper(TimeSpan timeout) : this(timeout, false) { } public TimeoutHelper(TimeSpan timeout, bool startTimeout) { Fx.Assert(timeout >= TimeSpan.Zero, "timeout must be non-negative"); this.originalTimeout = timeout; this.deadline = DateTime.MaxValue; this.deadlineSet = (timeout == TimeSpan.MaxValue); if (startTimeout && !this.deadlineSet) { this.SetDeadline(); } } public TimeSpan OriginalTimeout { get { return this.originalTimeout; } } public static bool IsTooLarge(TimeSpan timeout) { return (timeout > TimeoutHelper.MaxWait) && (timeout != TimeSpan.MaxValue); } public static TimeSpan FromMilliseconds(int milliseconds) { if (milliseconds == Timeout.Infinite) { return TimeSpan.MaxValue; } else { return TimeSpan.FromMilliseconds(milliseconds); } } public static int ToMilliseconds(TimeSpan timeout) { if (timeout == TimeSpan.MaxValue) { return Timeout.Infinite; } else { long ticks = Ticks.FromTimeSpan(timeout); if (ticks / TimeSpan.TicksPerMillisecond > int.MaxValue) { return int.MaxValue; } return Ticks.ToMilliseconds(ticks); } } public static TimeSpan Min(TimeSpan val1, TimeSpan val2) { if (val1 > val2) { return val2; } else { return val1; } } public static DateTime Min(DateTime val1, DateTime val2) { if (val1 > val2) { return val2; } else { return val1; } } public static TimeSpan Add(TimeSpan timeout1, TimeSpan timeout2) { return Ticks.ToTimeSpan(Ticks.Add(Ticks.FromTimeSpan(timeout1), Ticks.FromTimeSpan(timeout2))); } public static DateTime Add(DateTime time, TimeSpan timeout) { if (timeout >= TimeSpan.Zero && DateTime.MaxValue - time <= timeout) { return DateTime.MaxValue; } if (timeout <= TimeSpan.Zero && DateTime.MinValue - time >= timeout) { return DateTime.MinValue; } return time + timeout; } public static DateTime Subtract(DateTime time, TimeSpan timeout) { return Add(time, TimeSpan.Zero - timeout); } public static TimeSpan Divide(TimeSpan timeout, int factor) { if (timeout == TimeSpan.MaxValue) { return TimeSpan.MaxValue; } return Ticks.ToTimeSpan((Ticks.FromTimeSpan(timeout) / factor) + 1); } public TimeSpan RemainingTime() { if (!this.deadlineSet) { this.SetDeadline(); return this.originalTimeout; } else if (this.deadline == DateTime.MaxValue) { return TimeSpan.MaxValue; } else { TimeSpan remaining = this.deadline - DateTime.UtcNow; if (remaining <= TimeSpan.Zero) { return TimeSpan.Zero; } else { return remaining; } } } public TimeSpan ElapsedTime() { return this.originalTimeout - this.RemainingTime(); } void SetDeadline() { Fx.Assert(!deadlineSet, "TimeoutHelper deadline set twice."); this.deadline = DateTime.UtcNow + this.originalTimeout; #if NOTIMEOUT this.deadline = DateTime.MaxValue; #endif this.deadlineSet = true; } public static void ThrowIfNegativeArgument(TimeSpan timeout) { ThrowIfNegativeArgument(timeout, "timeout"); } public static void ThrowIfNegativeArgument(TimeSpan timeout, string argumentName) { if (timeout < TimeSpan.Zero) { throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, CommonResources.GetString(CommonResources.TimeoutMustBeNonNegative, argumentName, timeout)); } } public static void ThrowIfNonPositiveArgument(TimeSpan timeout) { ThrowIfNonPositiveArgument(timeout, "timeout"); } public static void ThrowIfNonPositiveArgument(TimeSpan timeout, string argumentName) { if (timeout <= TimeSpan.Zero) { throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, CommonResources.GetString(CommonResources.TimeoutMustBePositive, argumentName, timeout)); } } #if !WINDOWS_UWP && !PCL [Fx.Tag.Blocking] #endif public static bool WaitOne(WaitHandle waitHandle, TimeSpan timeout) { ThrowIfNegativeArgument(timeout); if (timeout == TimeSpan.MaxValue) { waitHandle.WaitOne(); return true; } else { return waitHandle.WaitOne(timeout); } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using QuantConnect.Data.Market; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Orders.Fills; using QuantConnect.Orders.Slippage; using QuantConnect.Securities; using QuantConnect.Securities.Equity; using QuantConnect.Securities.Option; using QuantConnect.Util; package com.quantconnect.lean.Brokerages { /** * Provides a default implementation of <see cref="IBrokerageModel"/> that allows all orders and uses * the default transaction models */ public class DefaultBrokerageModel : IBrokerageModel { /** * The default markets for the backtesting brokerage */ public static final ImmutableMap<SecurityType,String> DefaultMarketMap = new Map<SecurityType,String> { {SecurityType.Base, Market.USA}, {SecurityType.Equity, Market.USA}, {SecurityType.Option, Market.USA}, {SecurityType.Forex, Market.FXCM}, {SecurityType.Cfd, Market.FXCM} }.ToReadOnlyDictionary(); /** * Gets or sets the account type used by this model */ public AccountType AccountType { get; private set; } /** * Gets a map of the default markets to be used for each security type */ public ImmutableMap<SecurityType,String> DefaultMarkets { get { return DefaultMarketMap; } } /** * Initializes a new instance of the <see cref="DefaultBrokerageModel"/> class */ * @param accountType The type of account to be modelled, defaults to * <see cref="QuantConnect.AccountType.Margin"/> public DefaultBrokerageModel(AccountType accountType = AccountType.Margin) { AccountType = accountType; } /** * Returns true if the brokerage could accept this order. This takes into account * order type, security type, and order size limits. */ * * For example, a brokerage may have no connectivity at certain times, or an order rate/size limit * * @param security The security being ordered * @param order The order to be processed * @param message If this function returns false, a brokerage message detailing why the order may not be submitted @returns True if the brokerage could process the order, false otherwise public boolean CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message) { message = null; return true; } /** * Returns true if the brokerage would allow updating the order as specified by the request */ * @param security The security of the order * @param order The order to be updated * @param request The requested update to be made to the order * @param message If this function returns false, a brokerage message detailing why the order may not be updated @returns True if the brokerage would allow updating the order, false otherwise public boolean CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message) { message = null; return true; } /** * Returns true if the brokerage would be able to execute this order at this time assuming * market prices are sufficient for the fill to take place. This is used to emulate the * brokerage fills in backtesting and paper trading. For example some brokerages may not perform * executions during extended market hours. This is not intended to be checking whether or not * the exchange is open, that is handled in the Security.Exchange property. */ * @param security The security being traded * @param order The order to test for execution @returns True if the brokerage would be able to perform the execution, false otherwise public boolean CanExecuteOrder(Security security, Order order) { return true; } /** * Applies the split to the specified order ticket */ * * This default implementation will update the orders to maintain a similar market value * * @param tickets The open tickets matching the split event * @param split The split event data public void ApplySplit(List<OrderTicket> tickets, Split split) { // by default we'll just update the orders to have the same notional value splitFactor = split.splitFactor; tickets.ForEach(ticket -> ticket.Update(new UpdateOrderFields { Quantity = (OptionalInt) (ticket.Quantity/splitFactor), LimitPrice = ticket.OrderType.IsLimitOrder() ? ticket.Get(OrderField.LimitPrice)*splitFactor : (Optional<BigDecimal>) null, StopPrice = ticket.OrderType.IsStopOrder() ? ticket.Get(OrderField.StopPrice)*splitFactor : (Optional<BigDecimal>) null })); } /** * Gets the brokerage's leverage for the specified security */ * @param security The security's whose leverage we seek @returns The leverage for the specified security public BigDecimal GetLeverage(Security security) { switch (security.Type) { case SecurityType.Equity: return 2m; case SecurityType.Forex: case SecurityType.Cfd: return 50m; case SecurityType.Base: case SecurityType.Commodity: case SecurityType.Option: case SecurityType.Future: default: return 1m; } } /** * Gets a new fill model that represents this brokerage's fill behavior */ * @param security The security to get fill model for @returns The new fill model for this brokerage public IFillModel GetFillModel(Security security) { return new ImmediateFillModel(); } /** * Gets a new fee model that represents this brokerage's fee structure */ * @param security The security to get a fee model for @returns The new fee model for this brokerage public IFeeModel GetFeeModel(Security security) { switch (security.Type) { case SecurityType.Base: return new ConstantFeeModel(0m); case SecurityType.Forex: case SecurityType.Equity: return new InteractiveBrokersFeeModel(); case SecurityType.Commodity: case SecurityType.Option: case SecurityType.Future: case SecurityType.Cfd: default: return new ConstantFeeModel(0m); } } /** * Gets a new slippage model that represents this brokerage's fill slippage behavior */ * @param security The security to get a slippage model for @returns The new slippage model for this brokerage public ISlippageModel GetSlippageModel(Security security) { switch (security.Type) { case SecurityType.Base: case SecurityType.Equity: return new ConstantSlippageModel(0); case SecurityType.Forex: case SecurityType.Cfd: return new SpreadSlippageModel(); case SecurityType.Commodity: case SecurityType.Option: case SecurityType.Future: default: return new ConstantSlippageModel(0); } } /** * Gets a new settlement model for the security */ * @param security The security to get a settlement model for * @param accountType The account type @returns The settlement model for this brokerage public ISettlementModel GetSettlementModel(Security security, AccountType accountType) { if( accountType == AccountType.Cash) { switch (security.Type) { case SecurityType.Equity: return new DelayedSettlementModel(Equity.DefaultSettlementDays, Equity.DefaultSettlementTime); case SecurityType.Option: return new DelayedSettlementModel(Option.DefaultSettlementDays, Option.DefaultSettlementTime); } } return new ImmediateSettlementModel(); } } }
// 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. ////////////////////////////////////////////////////////// // L-1-11-1.cs - Beta1 Layout Test - RDawson // // Tests layout of classes two unrelated classes in // the same assembly and module // // See ReadMe.txt in the same project as this source for // further details about these tests. // using System; class Test{ public static int Main(){ int mi_RetCode = 100; A a = new A(); B b = new B(); if(a.Test(b) != 100) mi_RetCode = 0; if(b.Test(a) != 100) mi_RetCode = 0; if(mi_RetCode == 100) Console.WriteLine("Pass"); else Console.WriteLine("FAIL"); return mi_RetCode; } } class A{ public int Test(B b){ int mi_RetCode = 100; ///////////////////////////////// // Test instance field access b.FldPubInst = 100; if(b.FldPubInst != 100) mi_RetCode = 0; //@csharp - Note that C# will not compile an illegal access of b.FldPrivInst //So there is no negative test here, it should be covered elsewhere and //should throw a FielAccessException within the runtime. (IL sources is //the most logical, only?, choice) //@csharp - C# Won't compile illegal family access from non-family members b.FldAsmInst = 100; if(b.FldAsmInst != 100) mi_RetCode = 0; b.FldFoaInst = 100; if(b.FldFoaInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access B.FldPubStat = 100; if(B.FldPubStat != 100) mi_RetCode = 0; //@csharp - Again, note C# won't do private field access //@csharp - C# Won't compile illegal family access from non-family members B.FldAsmStat = 100; if(B.FldAsmStat != 100) mi_RetCode = 0; B.FldFoaStat = 100; if(B.FldFoaStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance b.Method access if(b.MethPubInst() != 100) mi_RetCode = 0; //@csharp - C# won't do private b.Method access //@csharp - C# Won't compile illegal family access from non-family members if(b.MethAsmInst() != 100) mi_RetCode = 0; if(b.MethFoaInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static b.Method access if(B.MethPubStat() != 100) mi_RetCode = 0; //@csharp - C# won't do private b.Method access //@csharp - C# Won't compile illegal family access from non-family members if(B.MethAsmStat() != 100) mi_RetCode = 0; if(B.MethFoaStat() != 100) mi_RetCode = 0; ///////////////////////////////// // Test virtual b.Method access if(b.MethPubVirt() != 100) mi_RetCode = 0; //@csharp - C# won't do private b.Method access //@csharp - C# Won't compile illegal family access from non-family members if(b.MethAsmVirt() != 100) mi_RetCode = 0; if(b.MethFoaVirt() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int FldPubInst; private int FldPrivInst; protected int FldFamInst; //Translates to "family" internal int FldAsmInst; //Translates to "assembly" protected internal int FldFoaInst; //Translates to "famorassem" ////////////////////////////// // Static Fields public static int FldPubStat; private static int FldPrivStat; protected static int FldFamStat; //family internal static int FldAsmStat; //assembly protected internal static int FldFoaStat; //famorassem ////////////////////////////// // Instance Methods public int MethPubInst(){ Console.WriteLine("A::MethPubInst()"); return 100; } private int MethPrivInst(){ Console.WriteLine("A::MethPrivInst()"); return 100; } protected int MethFamInst(){ Console.WriteLine("A::MethFamInst()"); return 100; } internal int MethAsmInst(){ Console.WriteLine("A::MethAsmInst()"); return 100; } protected internal int MethFoaInst(){ Console.WriteLine("A::MethFoaInst()"); return 100; } ////////////////////////////// // Static Methods public static int MethPubStat(){ Console.WriteLine("A::MethPubStat()"); return 100; } private static int MethPrivStat(){ Console.WriteLine("A::MethPrivStat()"); return 100; } protected static int MethFamStat(){ Console.WriteLine("A::MethFamStat()"); return 100; } internal static int MethAsmStat(){ Console.WriteLine("A::MethAsmStat()"); return 100; } protected internal static int MethFoaStat(){ Console.WriteLine("A::MethFoaStat()"); return 100; } ////////////////////////////// // Virtual Instance Methods public virtual int MethPubVirt(){ Console.WriteLine("A::MethPubVirt()"); return 100; } //@csharp - Note that C# won't compile an illegal private virtual function //So there is no negative testing MethPrivVirt() here. protected virtual int MethFamVirt(){ Console.WriteLine("A::MethFamVirt()"); return 100; } internal virtual int MethAsmVirt(){ Console.WriteLine("A::MethAsmVirt()"); return 100; } protected internal virtual int MethFoaVirt(){ Console.WriteLine("A::MethFoaVirt()"); return 100; } } class B{ public int Test(A a){ int mi_RetCode = 100; ///////////////////////////////// // Test instance field access a.FldPubInst = 100; if(a.FldPubInst != 100) mi_RetCode = 0; //@csharp - Note that C# will not compile an illegal access of a.FldPrivInst //So there is no negative test here, it should be covered elsewhere and //should throw a FielAccessException within the runtime. (IL sources is //the most logical, only?, choice) //@csharp - C# Won't compile illegal family access from non-family members a.FldAsmInst = 100; if(a.FldAsmInst != 100) mi_RetCode = 0; a.FldFoaInst = 100; if(a.FldFoaInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access A.FldPubStat = 100; if(A.FldPubStat != 100) mi_RetCode = 0; //@csharp - Again, note C# won't do private field access //@csharp - C# Won't compile illegal family access from non-family members A.FldAsmStat = 100; if(A.FldAsmStat != 100) mi_RetCode = 0; A.FldFoaStat = 100; if(A.FldFoaStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance a.Method access if(a.MethPubInst() != 100) mi_RetCode = 0; //@csharp - C# won't do private a.Method access //@csharp - C# Won't compile illegal family access from non-family members if(a.MethAsmInst() != 100) mi_RetCode = 0; if(a.MethFoaInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static a.Method access if(A.MethPubStat() != 100) mi_RetCode = 0; //@csharp - C# won't do private a.Method access //@csharp - C# Won't compile illegal family access from non-family members if(A.MethAsmStat() != 100) mi_RetCode = 0; if(A.MethFoaStat() != 100) mi_RetCode = 0; ///////////////////////////////// // Test virtual a.Method access if(a.MethPubVirt() != 100) mi_RetCode = 0; //@csharp - C# won't do private a.Method access //@csharp - C# Won't compile illegal family access from non-family members if(a.MethAsmVirt() != 100) mi_RetCode = 0; if(a.MethFoaVirt() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int FldPubInst; private int FldPrivInst; protected int FldFamInst; //Translates to "family" internal int FldAsmInst; //Translates to "assembly" protected internal int FldFoaInst; //Translates to "famorassem" ////////////////////////////// // Static Fields public static int FldPubStat; private static int FldPrivStat; protected static int FldFamStat; //family internal static int FldAsmStat; //assembly protected internal static int FldFoaStat; //famorassem ////////////////////////////// // Instance Methods public int MethPubInst(){ Console.WriteLine("B::MethPubInst()"); return 100; } private int MethPrivInst(){ Console.WriteLine("B::MethPrivInst()"); return 100; } protected int MethFamInst(){ Console.WriteLine("B::MethFamInst()"); return 100; } internal int MethAsmInst(){ Console.WriteLine("B::MethAsmInst()"); return 100; } protected internal int MethFoaInst(){ Console.WriteLine("B::MethFoaInst()"); return 100; } ////////////////////////////// // Static Methods public static int MethPubStat(){ Console.WriteLine("B::MethPubStat()"); return 100; } private static int MethPrivStat(){ Console.WriteLine("B::MethPrivStat()"); return 100; } protected static int MethFamStat(){ Console.WriteLine("B::MethFamStat()"); return 100; } internal static int MethAsmStat(){ Console.WriteLine("B::MethAsmStat()"); return 100; } protected internal static int MethFoaStat(){ Console.WriteLine("B::MethFoaStat()"); return 100; } ////////////////////////////// // Virtual Instance Methods public virtual int MethPubVirt(){ Console.WriteLine("B::MethPubVirt()"); return 100; } //@csharp - Note that C# won't compile an illegal private virtual function //So there is no negative testing MethPrivVirt() here. protected virtual int MethFamVirt(){ Console.WriteLine("B::MethFamVirt()"); return 100; } internal virtual int MethAsmVirt(){ Console.WriteLine("B::MethAsmVirt()"); return 100; } protected internal virtual int MethFoaVirt(){ Console.WriteLine("B::MethFoaVirt()"); return 100; } }
// 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. /*============================================================ ** ** Classes: Security Descriptor family of classes ** ** ===========================================================*/ using Microsoft.Win32; using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Globalization; using System.Diagnostics.Contracts; namespace System.Security.AccessControl { [Flags] public enum ControlFlags { None = 0x0000, OwnerDefaulted = 0x0001, // set by RM only GroupDefaulted = 0x0002, // set by RM only DiscretionaryAclPresent = 0x0004, // set by RM or user, 'off' means DACL is null DiscretionaryAclDefaulted = 0x0008, // set by RM only SystemAclPresent = 0x0010, // same as DiscretionaryAclPresent SystemAclDefaulted = 0x0020, // sams as DiscretionaryAclDefaulted DiscretionaryAclUntrusted = 0x0040, // ignore this one ServerSecurity = 0x0080, // ignore this one DiscretionaryAclAutoInheritRequired = 0x0100, // ignore this one SystemAclAutoInheritRequired = 0x0200, // ignore this one DiscretionaryAclAutoInherited = 0x0400, // set by RM only SystemAclAutoInherited = 0x0800, // set by RM only DiscretionaryAclProtected = 0x1000, // when set, RM will stop inheriting SystemAclProtected = 0x2000, // when set, RM will stop inheriting RMControlValid = 0x4000, // the reserved 8 bits have some meaning SelfRelative = 0x8000, // must always be on } public abstract class GenericSecurityDescriptor { #region Protected Members // // Pictorially the structure of a security descriptor is as follows: // // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 // +---------------------------------------------------------------+ // | Control |Reserved1 (SBZ)| Revision | // +---------------------------------------------------------------+ // | Owner | // +---------------------------------------------------------------+ // | Group | // +---------------------------------------------------------------+ // | Sacl | // +---------------------------------------------------------------+ // | Dacl | // +---------------------------------------------------------------+ // internal const int HeaderLength = 20; internal const int OwnerFoundAt = 4; internal const int GroupFoundAt = 8; internal const int SaclFoundAt = 12; internal const int DaclFoundAt = 16; #endregion #region Private Methods // // Stores an integer in big-endian format into an array at a given offset // private static void MarshalInt(byte[] binaryForm, int offset, int number) { binaryForm[offset + 0] = (byte)(number >> 0); binaryForm[offset + 1] = (byte)(number >> 8); binaryForm[offset + 2] = (byte)(number >> 16); binaryForm[offset + 3] = (byte)(number >> 24); } // // Retrieves an integer stored in big-endian format at a given offset in an array // internal static int UnmarshalInt(byte[] binaryForm, int offset) { return (int)( (binaryForm[offset + 0] << 0) + (binaryForm[offset + 1] << 8) + (binaryForm[offset + 2] << 16) + (binaryForm[offset + 3] << 24)); } #endregion #region Constructors protected GenericSecurityDescriptor() { } #endregion #region Protected Properties // // Marshaling logic requires calling into the derived // class to obtain pointers to SACL and DACL // internal abstract GenericAcl GenericSacl { get; } internal abstract GenericAcl GenericDacl { get; } private bool IsCraftedAefaDacl { get { return (GenericDacl is DiscretionaryAcl) && (GenericDacl as DiscretionaryAcl).EveryOneFullAccessForNullDacl; } } #endregion #region Public Properties public static bool IsSddlConversionSupported() { return true; // SDDL to binary conversions are supported on Windows 2000 and higher } public static byte Revision { get { return 1; } } // // Allows retrieving and setting the control bits for this security descriptor // public abstract ControlFlags ControlFlags { get; } // // Allows retrieving and setting the owner SID for this security descriptor // public abstract SecurityIdentifier Owner { get; set; } // // Allows retrieving and setting the group SID for this security descriptor // public abstract SecurityIdentifier Group { get; set; } // // Retrieves the length of the binary representation // of the security descriptor // public int BinaryLength { get { int result = HeaderLength; if (Owner != null) { result += Owner.BinaryLength; } if (Group != null) { result += Group.BinaryLength; } if ((ControlFlags & ControlFlags.SystemAclPresent) != 0 && GenericSacl != null) { result += GenericSacl.BinaryLength; } if ((ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0 && GenericDacl != null && !IsCraftedAefaDacl) { result += GenericDacl.BinaryLength; } return result; } } #endregion #region Public Methods // // Converts the security descriptor to its SDDL form // public string GetSddlForm(AccessControlSections includeSections) { byte[] binaryForm = new byte[BinaryLength]; string resultSddl; int error; GetBinaryForm(binaryForm, 0); SecurityInfos flags = 0; if ((includeSections & AccessControlSections.Owner) != 0) { flags |= SecurityInfos.Owner; } if ((includeSections & AccessControlSections.Group) != 0) { flags |= SecurityInfos.Group; } if ((includeSections & AccessControlSections.Audit) != 0) { flags |= SecurityInfos.SystemAcl; } if ((includeSections & AccessControlSections.Access) != 0) { flags |= SecurityInfos.DiscretionaryAcl; } error = Win32.ConvertSdToSddl(binaryForm, 1, flags, out resultSddl); if (error == Interop.mincore.Errors.ERROR_INVALID_PARAMETER || error == Interop.mincore.Errors.ERROR_UNKNOWN_REVISION) { // // Indicates that the marshaling logic in GetBinaryForm is busted // Contract.Assert(false, "binaryForm produced invalid output"); throw new InvalidOperationException(); } else if (error != Interop.mincore.Errors.ERROR_SUCCESS) { Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.ConvertSdToSddl returned {0}", error)); throw new InvalidOperationException(); } return resultSddl; } // // Converts the security descriptor to its binary form // public void GetBinaryForm(byte[] binaryForm, int offset) { if (binaryForm == null) { throw new ArgumentNullException(nameof(binaryForm)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (binaryForm.Length - offset < BinaryLength) { throw new ArgumentOutOfRangeException( nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall); } Contract.EndContractBlock(); // // the offset will grow as we go for each additional field (owner, group, // acl, etc) being written. But for each of such fields, we must use the // original offset as passed in, not the growing offset // int originalOffset = offset; // // Populate the header // int length = BinaryLength; byte rmControl = ((this is RawSecurityDescriptor) && ((ControlFlags & ControlFlags.RMControlValid) != 0)) ? ((this as RawSecurityDescriptor).ResourceManagerControl) : (byte)0; // if the DACL is our internally crafted NULL replacement, then let us turn off this control int materializedControlFlags = (int)ControlFlags; if (IsCraftedAefaDacl) { unchecked { materializedControlFlags &= ~((int)ControlFlags.DiscretionaryAclPresent); } } binaryForm[offset + 0] = Revision; binaryForm[offset + 1] = rmControl; binaryForm[offset + 2] = (byte)((int)materializedControlFlags >> 0); binaryForm[offset + 3] = (byte)((int)materializedControlFlags >> 8); // // Compute offsets at which owner, group, SACL and DACL are stored // int ownerOffset, groupOffset, saclOffset, daclOffset; ownerOffset = offset + OwnerFoundAt; groupOffset = offset + GroupFoundAt; saclOffset = offset + SaclFoundAt; daclOffset = offset + DaclFoundAt; offset += HeaderLength; // // Marhsal the Owner SID into place // if (Owner != null) { MarshalInt(binaryForm, ownerOffset, offset - originalOffset); Owner.GetBinaryForm(binaryForm, offset); offset += Owner.BinaryLength; } else { // // If Owner SID is null, store 0 in the offset field // MarshalInt(binaryForm, ownerOffset, 0); } // // Marshal the Group SID into place // if (Group != null) { MarshalInt(binaryForm, groupOffset, offset - originalOffset); Group.GetBinaryForm(binaryForm, offset); offset += Group.BinaryLength; } else { // // If Group SID is null, store 0 in the offset field // MarshalInt(binaryForm, groupOffset, 0); } // // Marshal the SACL into place, if present // if ((ControlFlags & ControlFlags.SystemAclPresent) != 0 && GenericSacl != null) { MarshalInt(binaryForm, saclOffset, offset - originalOffset); GenericSacl.GetBinaryForm(binaryForm, offset); offset += GenericSacl.BinaryLength; } else { // // If SACL is null or not present, store 0 in the offset field // MarshalInt(binaryForm, saclOffset, 0); } // // Marshal the DACL into place, if present // if ((ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0 && GenericDacl != null && !IsCraftedAefaDacl) { MarshalInt(binaryForm, daclOffset, offset - originalOffset); GenericDacl.GetBinaryForm(binaryForm, offset); offset += GenericDacl.BinaryLength; } else { // // If DACL is null or not present, store 0 in the offset field // MarshalInt(binaryForm, daclOffset, 0); } } #endregion } public sealed class RawSecurityDescriptor : GenericSecurityDescriptor { #region Private Members private SecurityIdentifier _owner; private SecurityIdentifier _group; private ControlFlags _flags; private RawAcl _sacl; private RawAcl _dacl; private byte _rmControl; // the not-so-reserved SBZ1 field #endregion #region Protected Properties internal override GenericAcl GenericSacl { get { return _sacl; } } internal override GenericAcl GenericDacl { get { return _dacl; } } #endregion #region Private methods private void CreateFromParts(ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl) { SetFlags(flags); Owner = owner; Group = group; SystemAcl = systemAcl; DiscretionaryAcl = discretionaryAcl; ResourceManagerControl = 0; } #endregion #region Constructors // // Creates a security descriptor explicitly // public RawSecurityDescriptor(ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl) : base() { CreateFromParts(flags, owner, group, systemAcl, discretionaryAcl); } // // Creates a security descriptor from an SDDL string // public RawSecurityDescriptor(string sddlForm) : this(BinaryFormFromSddlForm(sddlForm), 0) { } // // Creates a security descriptor from its binary representation // Important: the representation must be in self-relative format // public RawSecurityDescriptor(byte[] binaryForm, int offset) : base() { // // The array passed in must be valid // if (binaryForm == null) { throw new ArgumentNullException(nameof(binaryForm)); } if (offset < 0) { // // Offset must not be negative // throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } // // At least make sure the header is in place // if (binaryForm.Length - offset < HeaderLength) { throw new ArgumentOutOfRangeException( nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall); } // // We only understand revision-1 security descriptors // if (binaryForm[offset + 0] != Revision) { throw new ArgumentOutOfRangeException(nameof(binaryForm), SR.AccessControl_InvalidSecurityDescriptorRevision); } Contract.EndContractBlock(); ControlFlags flags; SecurityIdentifier owner, group; RawAcl sacl, dacl; byte rmControl; // // Extract the ResourceManagerControl field // rmControl = binaryForm[offset + 1]; // // Extract the control flags // flags = (ControlFlags)((binaryForm[offset + 2] << 0) + (binaryForm[offset + 3] << 8)); // // Make sure that the input is in self-relative format // if ((flags & ControlFlags.SelfRelative) == 0) { throw new ArgumentException( SR.AccessControl_InvalidSecurityDescriptorSelfRelativeForm, nameof(binaryForm)); } // // Extract the owner SID // int ownerOffset = UnmarshalInt(binaryForm, offset + OwnerFoundAt); if (ownerOffset != 0) { owner = new SecurityIdentifier(binaryForm, offset + ownerOffset); } else { owner = null; } // // Extract the group SID // int groupOffset = UnmarshalInt(binaryForm, offset + GroupFoundAt); if (groupOffset != 0) { group = new SecurityIdentifier(binaryForm, offset + groupOffset); } else { group = null; } // // Extract the SACL // int saclOffset = UnmarshalInt(binaryForm, offset + SaclFoundAt); if (((flags & ControlFlags.SystemAclPresent) != 0) && saclOffset != 0) { sacl = new RawAcl(binaryForm, offset + saclOffset); } else { sacl = null; } // // Extract the DACL // int daclOffset = UnmarshalInt(binaryForm, offset + DaclFoundAt); if (((flags & ControlFlags.DiscretionaryAclPresent) != 0) && daclOffset != 0) { dacl = new RawAcl(binaryForm, offset + daclOffset); } else { dacl = null; } // // Create the resulting security descriptor // CreateFromParts(flags, owner, group, sacl, dacl); // // In the offchance that the flags indicate that the rmControl // field is meaningful, remember what was there. // if ((flags & ControlFlags.RMControlValid) != 0) { ResourceManagerControl = rmControl; } } #endregion #region Static Methods private static byte[] BinaryFormFromSddlForm(string sddlForm) { if (sddlForm == null) { throw new ArgumentNullException(nameof(sddlForm)); } Contract.EndContractBlock(); int error; IntPtr byteArray = IntPtr.Zero; uint byteArraySize = 0; byte[] binaryForm = null; try { if (!Interop.mincore.ConvertStringSdToSd( sddlForm, GenericSecurityDescriptor.Revision, out byteArray, ref byteArraySize)) { error = Marshal.GetLastWin32Error(); if (error == Interop.mincore.Errors.ERROR_INVALID_PARAMETER || error == Interop.mincore.Errors.ERROR_INVALID_ACL || error == Interop.mincore.Errors.ERROR_INVALID_SECURITY_DESCR || error == Interop.mincore.Errors.ERROR_UNKNOWN_REVISION) { throw new ArgumentException( SR.ArgumentException_InvalidSDSddlForm, nameof(sddlForm)); } else if (error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } else if (error == Interop.mincore.Errors.ERROR_INVALID_SID) { throw new ArgumentException( SR.AccessControl_InvalidSidInSDDLString, nameof(sddlForm)); } else if (error != Interop.mincore.Errors.ERROR_SUCCESS) { Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error out of Win32.ConvertStringSdToSd: {0}", error)); // TODO : This should be a Win32Exception once that type is available throw new Exception(); } } binaryForm = new byte[byteArraySize]; // // Extract the data from the returned pointer // Marshal.Copy(byteArray, binaryForm, 0, (int)byteArraySize); } finally { // // Now is a good time to get rid of the returned pointer // if (byteArray != IntPtr.Zero) { Interop.mincore_obsolete.LocalFree(byteArray); } } return binaryForm; } #endregion #region Public Properties // // Allows retrieving the control bits for this security descriptor // Important: Special checks must be applied when setting flags and not // all flags can be set (for instance, we only deal with self-relative // security descriptors), thus flags can be set through other methods. // public override ControlFlags ControlFlags { get { return _flags; } } // // Allows retrieving and setting the owner SID for this security descriptor // public override SecurityIdentifier Owner { get { return _owner; } set { _owner = value; } } // // Allows retrieving and setting the group SID for this security descriptor // public override SecurityIdentifier Group { get { return _group; } set { _group = value; } } // // Allows retrieving and setting the SACL for this security descriptor // public RawAcl SystemAcl { get { return _sacl; } set { _sacl = value; } } // // Allows retrieving and setting the DACL for this security descriptor // public RawAcl DiscretionaryAcl { get { return _dacl; } set { _dacl = value; } } // // CORNER CASE (LEGACY) // The ostensibly "reserved" field in the Security Descriptor header // can in fact be used by obscure resource managers which in this // case must set the RMControlValid flag. // public byte ResourceManagerControl { get { return _rmControl; } set { _rmControl = value; } } #endregion #region Public Methods public void SetFlags(ControlFlags flags) { // // We can not deal with non-self-relative descriptors // so just forget about it // _flags = (flags | ControlFlags.SelfRelative); } #endregion } public sealed class CommonSecurityDescriptor : GenericSecurityDescriptor { #region Private Members bool _isContainer; bool _isDS; private RawSecurityDescriptor _rawSd; private SystemAcl _sacl; private DiscretionaryAcl _dacl; #endregion #region Private Methods private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl) { if (systemAcl != null && systemAcl.IsContainer != isContainer) { throw new ArgumentException( isContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(systemAcl)); } if (discretionaryAcl != null && discretionaryAcl.IsContainer != isContainer) { throw new ArgumentException( isContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(discretionaryAcl)); } _isContainer = isContainer; if (systemAcl != null && systemAcl.IsDS != isDS) { throw new ArgumentException( isDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(systemAcl)); } if (discretionaryAcl != null && discretionaryAcl.IsDS != isDS) { throw new ArgumentException( isDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(discretionaryAcl)); } _isDS = isDS; _sacl = systemAcl; // // Replace null DACL with an allow-all for everyone DACL // if (discretionaryAcl == null) { // // to conform to native behavior, we will add allow everyone ace for DACL // discretionaryAcl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(_isDS, _isContainer); } _dacl = discretionaryAcl; // // DACL is never null. So always set the flag bit on // ControlFlags actualFlags = flags | ControlFlags.DiscretionaryAclPresent; // // Keep SACL and the flag bit in sync. // if (systemAcl == null) { unchecked { actualFlags &= ~(ControlFlags.SystemAclPresent); } } else { actualFlags |= (ControlFlags.SystemAclPresent); } _rawSd = new RawSecurityDescriptor(actualFlags, owner, group, systemAcl == null ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl); } #endregion #region Constructors // // Creates a security descriptor explicitly // public CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl) { CreateFromParts(isContainer, isDS, flags, owner, group, systemAcl, discretionaryAcl); } private CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl) : this(isContainer, isDS, flags, owner, group, systemAcl == null ? null : new SystemAcl(isContainer, isDS, systemAcl), discretionaryAcl == null ? null : new DiscretionaryAcl(isContainer, isDS, discretionaryAcl)) { } public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor) : this(isContainer, isDS, rawSecurityDescriptor, false) { } internal CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor, bool trusted) { if (rawSecurityDescriptor == null) { throw new ArgumentNullException(nameof(rawSecurityDescriptor)); } Contract.EndContractBlock(); CreateFromParts( isContainer, isDS, rawSecurityDescriptor.ControlFlags, rawSecurityDescriptor.Owner, rawSecurityDescriptor.Group, rawSecurityDescriptor.SystemAcl == null ? null : new SystemAcl(isContainer, isDS, rawSecurityDescriptor.SystemAcl, trusted), rawSecurityDescriptor.DiscretionaryAcl == null ? null : new DiscretionaryAcl(isContainer, isDS, rawSecurityDescriptor.DiscretionaryAcl, trusted)); } // // Create a security descriptor from an SDDL string // public CommonSecurityDescriptor(bool isContainer, bool isDS, string sddlForm) : this(isContainer, isDS, new RawSecurityDescriptor(sddlForm), true) { } // // Create a security descriptor from its binary representation // public CommonSecurityDescriptor(bool isContainer, bool isDS, byte[] binaryForm, int offset) : this(isContainer, isDS, new RawSecurityDescriptor(binaryForm, offset), true) { } #endregion #region Protected Properties internal sealed override GenericAcl GenericSacl { get { return _sacl; } } internal sealed override GenericAcl GenericDacl { get { return _dacl; } } #endregion #region Public Properties public bool IsContainer { get { return _isContainer; } } public bool IsDS { get { return _isDS; } } // // Allows retrieving the control bits for this security descriptor // public override ControlFlags ControlFlags { get { return _rawSd.ControlFlags; } } // // Allows retrieving and setting the owner SID for this security descriptor // public override SecurityIdentifier Owner { get { return _rawSd.Owner; } set { _rawSd.Owner = value; } } // // Allows retrieving and setting the group SID for this security descriptor // public override SecurityIdentifier Group { get { return _rawSd.Group; } set { _rawSd.Group = value; } } public SystemAcl SystemAcl { get { return _sacl; } set { if (value != null) { if (value.IsContainer != this.IsContainer) { throw new ArgumentException( this.IsContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(value)); } if (value.IsDS != this.IsDS) { throw new ArgumentException( this.IsDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(value)); } } _sacl = value; if (_sacl != null) { _rawSd.SystemAcl = _sacl.RawAcl; AddControlFlags(ControlFlags.SystemAclPresent); } else { _rawSd.SystemAcl = null; RemoveControlFlags(ControlFlags.SystemAclPresent); } } } // // Allows retrieving and setting the DACL for this security descriptor // public DiscretionaryAcl DiscretionaryAcl { get { return _dacl; } set { if (value != null) { if (value.IsContainer != this.IsContainer) { throw new ArgumentException( this.IsContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(value)); } if (value.IsDS != this.IsDS) { throw new ArgumentException( this.IsDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(value)); } } // // NULL DACLs are replaced with allow everyone full access DACLs. // if (value == null) { _dacl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(IsDS, IsContainer); } else { _dacl = value; } _rawSd.DiscretionaryAcl = _dacl.RawAcl; AddControlFlags(ControlFlags.DiscretionaryAclPresent); } } public bool IsSystemAclCanonical { get { return (SystemAcl == null || SystemAcl.IsCanonical); } } public bool IsDiscretionaryAclCanonical { get { return (DiscretionaryAcl == null || DiscretionaryAcl.IsCanonical); } } #endregion #region Public Methods public void SetSystemAclProtection(bool isProtected, bool preserveInheritance) { if (!isProtected) { RemoveControlFlags(ControlFlags.SystemAclProtected); } else { if (!preserveInheritance && SystemAcl != null) { SystemAcl.RemoveInheritedAces(); } AddControlFlags(ControlFlags.SystemAclProtected); } } public void SetDiscretionaryAclProtection(bool isProtected, bool preserveInheritance) { if (!isProtected) { RemoveControlFlags(ControlFlags.DiscretionaryAclProtected); } else { if (!preserveInheritance && DiscretionaryAcl != null) { DiscretionaryAcl.RemoveInheritedAces(); } AddControlFlags(ControlFlags.DiscretionaryAclProtected); } if (DiscretionaryAcl != null && DiscretionaryAcl.EveryOneFullAccessForNullDacl) { DiscretionaryAcl.EveryOneFullAccessForNullDacl = false; } } public void PurgeAccessControl(SecurityIdentifier sid) { if (sid == null) { throw new ArgumentNullException(nameof(sid)); } Contract.EndContractBlock(); if (DiscretionaryAcl != null) { DiscretionaryAcl.Purge(sid); } } public void PurgeAudit(SecurityIdentifier sid) { if (sid == null) { throw new ArgumentNullException(nameof(sid)); } Contract.EndContractBlock(); if (SystemAcl != null) { SystemAcl.Purge(sid); } } public void AddDiscretionaryAcl(byte revision, int trusted) { this.DiscretionaryAcl = new DiscretionaryAcl(this.IsContainer, this.IsDS, revision, trusted); this.AddControlFlags(ControlFlags.DiscretionaryAclPresent); } public void AddSystemAcl(byte revision, int trusted) { this.SystemAcl = new SystemAcl(this.IsContainer, this.IsDS, revision, trusted); this.AddControlFlags(ControlFlags.SystemAclPresent); } #endregion #region internal Methods internal void UpdateControlFlags(ControlFlags flagsToUpdate, ControlFlags newFlags) { ControlFlags finalFlags = newFlags | (_rawSd.ControlFlags & (~flagsToUpdate)); _rawSd.SetFlags(finalFlags); } // // These two add/remove method must be called with great care (and thus it is internal) // The caller is responsible for keeping the SaclPresent and DaclPresent bits in sync // with the actual SACL and DACL. // internal void AddControlFlags(ControlFlags flags) { _rawSd.SetFlags(_rawSd.ControlFlags | flags); } internal void RemoveControlFlags(ControlFlags flags) { unchecked { _rawSd.SetFlags(_rawSd.ControlFlags & ~flags); } } internal bool IsSystemAclPresent { get { return (_rawSd.ControlFlags & ControlFlags.SystemAclPresent) != 0; } } internal bool IsDiscretionaryAclPresent { get { return (_rawSd.ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0; } } #endregion } }
// Copyright (c) 2015 James Liu // // See the LISCENSE file for copying permission. using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using Vexe.Runtime.Types; using Vexe.Runtime.Extensions; using System.Linq; #if UNITY_EDITOR using UnityEditor; #endif namespace Hourai.DanmakU { /// <summary> /// /// </summary> [RequireComponent(typeof(ParticleSystem))] public abstract class DanmakuType : MonoBehaviour, IEnumerable<Danmaku> { internal static List<DanmakuType> activeTypes; internal DanmakuPrefab prefab; public DanmakuPrefab Prefab { get { return prefab; } } // Pool variables internal Danmaku[] all; internal int _totalCount; internal int _spawnCount; internal int _activeCount; internal int _releasedCount; // Particle System variables private ParticleSystem danmakuSystem; private ParticleSystemRenderer dRenderer; private ParticleSystem.Particle[] particles; // Rendedring variables internal Mesh mesh; internal Color color; internal float size; internal Material material; internal int sortingLayer; internal int sortingOrder; private int updateIndex; private ParticleSystem.Particle particle; Action PostUpdate; #region Public Properties public int IotalCount { get { return _totalCount; } } public int ActiveCount { get { return _activeCount; } } public int SpawnCount { get { return _spawnCount; } set { _spawnCount = value; } } public int SortingLayer { get { return sortingLayer; } set { sortingLayer = value; dRenderer.sortingLayerID = value; } } public int SortingOrder { get { return sortingOrder; } set { sortingOrder = value; dRenderer.sortingOrder = value; } } public Mesh Mesh { get { return mesh; } } public Color Color { get { return color; } set { color = value; if(danmakuSystem) danmakuSystem.startColor = value; } } public float Size { get { return size; } set { size = value; } } public Material Material { get { return material; } } #endregion #region Initialization void Awake() { if (activeTypes == null) activeTypes = new List<DanmakuType>(); activeTypes.Add(this); DontDestroyOnLoad(this); danmakuSystem = GetComponent<ParticleSystem>(); dRenderer = GetComponent<ParticleSystemRenderer>(); Transform root = transform.root; transform.parent = null; transform.localPosition = Vector3.zero; danmakuSystem.simulationSpace = ParticleSystemSimulationSpace.World; danmakuSystem.startSize = 1; danmakuSystem.startLifetime = Mathf.Infinity; danmakuSystem.maxParticles = int.MaxValue; danmakuSystem.gravityModifier = 0f; danmakuSystem.startSpeed = 0; danmakuSystem.enableEmission = false; particles = new ParticleSystem.Particle[danmakuSystem.particleCount]; dRenderer.renderMode = ParticleSystemRenderMode.Mesh; dRenderer.reflectionProbeUsage = ReflectionProbeUsage.Off; dRenderer.receiveShadows = false; dRenderer.shadowCastingMode = ShadowCastingMode.Off; dRenderer.useLightProbes = false; gameObject.hideFlags = HideFlags.HideInHierarchy; // Destroy rest of hiearchy if(root != transform) Destroy(root.gameObject); gameObject.Children().Destroy(); Component[] whitelist = new Component[] { this, danmakuSystem, dRenderer, transform }; foreach (Component comp in GetComponents<Component>()) if (!whitelist.Contains(comp)) Destroy(comp); } // MUST be called from a DanmakuPrefab internal void Init(Renderer renderer, DanmakuPrefab prefab) { if (!prefab) throw new ArgumentNullException("prefab"); this.prefab = prefab; size = prefab.cachedScale.Max(); _totalCount = 0; _activeCount = 0; _spawnCount = prefab.spawnCount; if (_spawnCount <= 0) _spawnCount = 1; all = new Danmaku[prefab.initialCount * 2]; Spawn(prefab.initialCount); material = renderer.sharedMaterial; sortingLayer = renderer.sortingLayerID; sortingOrder = renderer.sortingOrder; mesh = new Mesh(); OnInit(renderer); Matrix4x4 rot = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, prefab.rotationOffset), prefab.transform.localScale); Vector3[] verts = mesh.vertices; for (int i = 0; i < verts.Length; i++) verts[i] = rot * verts[i]; mesh.vertices = verts; dRenderer.mesh = mesh; danmakuSystem.startColor = color; dRenderer.sharedMaterial = material; dRenderer.sortingLayerID = sortingLayer; dRenderer.sortingOrder = sortingOrder; } internal abstract void OnInit(Renderer renderer); #endregion void Update() { if (_activeCount <= 0) return; int particleCount = danmakuSystem.particleCount; if (_activeCount > particleCount) danmakuSystem.Emit(_activeCount - particleCount); if (_activeCount > particles.Length) Array.Resize(ref particles, Mathf.NextPowerOfTwo(_activeCount + 1)); danmakuSystem.GetParticles(particles); // For some reason, new ParticleSystem.Particle breaks bullet systems // but accessing the first element like this and reusing it for each is OK. particle = particles[0]; particle.axisOfRotation = Vector3.forward; updateIndex = 0; if (prefab.fixedAngle) { while (updateIndex < _activeCount) { Danmaku danmaku = all[updateIndex]; danmaku.Update(); particle.position = danmaku.position; particle.size = danmaku.Size; particle.color = danmaku.Color; particles[updateIndex++] = particle; } } else { while (updateIndex < _activeCount) { Danmaku danmaku = all[updateIndex]; danmaku.Update(); particle.position = danmaku.position; particle.rotation = danmaku.rotation; particle.size = danmaku.Size; particle.color = danmaku.Color; particles[updateIndex++] = particle; } } updateIndex = -1; danmakuSystem.SetParticles(particles, _activeCount); if(PostUpdate != null) { PostUpdate(); PostUpdate = null; } } protected virtual void OnDestroy() { activeTypes.Remove(this); Destroy(mesh); } void OnLevelWasLoaded(int level) { _activeCount = 0; _releasedCount = 0; } public void DestroyAll() { PostUpdate += delegate() { for (int i = 0; i < _activeCount; i++) all[i].DestroyImpl(); _activeCount = 0; _releasedCount = 0; }; } void Spawn(int count) { int endCount = _totalCount + count; if (all.Length < endCount) Array.Resize(ref all, Mathf.NextPowerOfTwo(endCount + 1)); for (int i = _totalCount; i < all.Length; i++) all[i] = new Danmaku(i, this); _totalCount = endCount; } #region Pooling Functions /// <summary> /// Retrievese a inactive Danmaku from the pool. /// The Danmaku wil not be rendered or be updated until Activate is called on it. /// </summary> /// <returns></returns> public Danmaku Get() { if (_releasedCount >= _totalCount) Spawn(_spawnCount); Danmaku inactive = all[_releasedCount]; inactive.Color = color; inactive.prefab = prefab; inactive.Size = size; inactive.Layer = prefab.cachedLayer; inactive.ColliderSize = prefab.colliderSize; inactive.colliderOffset = prefab.colliderOffset; _releasedCount++; return inactive; } internal void Activate(Danmaku danmaku) { Danmaku active = all[_activeCount]; active.PoolIndex = danmaku.PoolIndex; danmaku.PoolIndex = _activeCount; all[_activeCount] = danmaku; all[active.PoolIndex] = active; _activeCount++; } internal void Return(Danmaku danmaku) { int index = danmaku.PoolIndex; _activeCount--; _releasedCount--; Danmaku active = all[_activeCount]; // Last active Danmaku if(_activeCount == _releasedCount) { all[danmaku.PoolIndex = _activeCount] = danmaku; all[active.PoolIndex = index] = active; } else { Danmaku released = all[_releasedCount]; // Last released Danmaku all[danmaku.PoolIndex = _releasedCount] = danmaku; all[released.PoolIndex = _activeCount] = released; all[active.PoolIndex = index] = active; } if (index <= updateIndex) { active.Update(); particle.position = active.position; particle.rotation = active.rotation; particle.size = active.Size; particle.color = active.Color; particles[index] = particle; } } #endregion #region IEnumerable Implementation public IEnumerator<Danmaku> GetEnumerator() { for (var i = 0; i < _activeCount; i++) yield return all[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } internal sealed class SpriteDanmaku : DanmakuType { internal override void OnInit(Renderer renderer) { SpriteRenderer sr = renderer as SpriteRenderer; if (sr == null) return; //cachedSprite = renderer.sprite; color = sr.color; Sprite sprite = sr.sprite; material = new Material(material); material.mainTexture = sprite.texture; if (sprite == null) Destroy(mesh); else { var verts = sprite.vertices; var tris = sprite.triangles; var vertexes = new Vector3[verts.Length]; int[] triangles = new int[tris.Length]; for (int i = 0; i < verts.Length; i++) vertexes[i] = verts[i]; for (int i = 0; i < tris.Length; i++) triangles[i] = tris[i]; mesh.vertices = vertexes; mesh.uv = sprite.uv; mesh.triangles = triangles; } } protected override void OnDestroy() { base.OnDestroy(); Destroy(material); } } internal sealed class MeshDanmaku : DanmakuType { internal override void OnInit(Renderer renderer) { var mr = renderer as MeshRenderer; if (mr == null) return; color = Color.white; MeshFilter filter = mr.GetComponent<MeshFilter>(); if (filter == null) { Debug.LogError("Danmaku Prefab (" + name + ") is trying to use a MeshRenderer as a base, but no MeshFilter is found. Please add one."); } else { Mesh fMesh = filter.sharedMesh; mesh.vertices = fMesh.vertices; mesh.uv = fMesh.uv; mesh.triangles = fMesh.triangles; mesh.colors = fMesh.colors; mesh.normals = fMesh.normals; mesh.tangents = fMesh.tangents; } } } /// <summary> /// A container behavior used on prefabs to define how a bullet looks or behaves /// </summary> [DisallowMultipleComponent] [AddComponentMenu("Hourai.DanmakU/Danmaku Prefab")] public sealed class DanmakuPrefab : BetterBehaviour, IEnumerable<FireData> { public enum RenderingType { Sprite, Mesh } void Awake() { Destroy(gameObject); } void Init() { cachedScale = transform.localScale; cachedLayer = gameObject.layer; var singleRenderer = GetComponent<Renderer>(); var spriteRenderer = singleRenderer as SpriteRenderer; var meshRenderer = singleRenderer as MeshRenderer; if (spriteRenderer == null && meshRenderer == null) { Debug.LogError("Danmaku Prefab (" + name + ") has neither SpriteRenderer or MeshRenderer. Attach one or the other to it."); Destroy(this); return; } ParticleSystem system = null; if (danmakuSystemPrefab != null) system = Instantiate(danmakuSystemPrefab); if (system == null) { GameObject runtimeObject = Instantiate(Resources.Load("Danmaku Particle System")) as GameObject ?? new GameObject(name); system = runtimeObject.GetOrAddComponent<ParticleSystem>(); } if(meshRenderer) type = system.gameObject.AddComponent<MeshDanmaku>(); else type = system.gameObject.AddComponent<SpriteDanmaku>(); type.Init(singleRenderer, this); type.gameObject.SetActive(true); } public Danmaku Get() { if (!type) Init(); return type.Get(); } public void Match(Danmaku danmaku) { throw new System.Exception(); if (danmaku.prefab != this) { danmaku.prefab = this; // TODO: Figure out how to transfer Danmaku from pool to pool here danmaku.colliderType = collisionType; switch (collisionType) { default: danmaku.colliderSize = Vector2.zero; break; case Danmaku.ColliderType.Circle: danmaku.colliderSize = colliderSize * Mathf.Max(cachedScale.x, cachedScale.y); break; case Danmaku.ColliderType.Line: danmaku.colliderSize = colliderSize; break; } danmaku.sizeSquared = colliderSize.y * colliderSize.y; danmaku.colliderOffset = Vector2.Scale(cachedScale, colliderOffset); } danmaku.Color = type.Color; danmaku.Size = 1f; danmaku.Layer = cachedLayer; } #if UNITY_EDITOR private void OnDrawGizmosSelected() { Matrix4x4 oldGizmoMatrix = Gizmos.matrix; Matrix4x4 oldHandlesMatrix = Handles.matrix; Color oldGizmosColor = Gizmos.color; Color oldHandlesColor = Handles.color; Matrix4x4 hitboxMatrix = Matrix4x4.TRS((Vector2) transform.position, Quaternion.Euler(0f, 0f, transform.eulerAngles.z), transform.lossyScale); Gizmos.matrix = hitboxMatrix; Handles.matrix = hitboxMatrix; Handles.color = Color.green; Gizmos.color = Color.green; switch (collisionType) { case Danmaku.ColliderType.Point: //Handles.PositionHandle(Vector3.zero, Quaternion.identity); break; case Danmaku.ColliderType.Circle: hitboxMatrix = Matrix4x4.TRS((Vector2) transform.position, Quaternion.Euler(0f, 0f, transform.Rotation2D()), transform.lossyScale.Max()*Vector3.one); Gizmos.matrix = hitboxMatrix; Handles.matrix = hitboxMatrix; Handles.DrawWireDisc(colliderOffset, Vector3.forward, colliderSize.Max()); break; case Danmaku.ColliderType.Box: Gizmos.DrawWireCube(colliderOffset, colliderSize); break; case Danmaku.ColliderType.Line: Handles.DrawLine(colliderOffset, colliderOffset + new Vector2(0f, colliderSize.x)); break; } Gizmos.matrix = oldGizmoMatrix; Handles.matrix = oldHandlesMatrix; Gizmos.color = oldGizmosColor; Handles.color = oldHandlesColor; } #endif private void OnDestroy() { if (type) Destroy(type.gameObject); } public static implicit operator FireData(DanmakuPrefab prefab) { return prefab ? new FireData() {Prefab = prefab} : null; } #region Prefab Fields [SerializeField] private ParticleSystem danmakuSystemPrefab; [Serialize, Default(Enum = 0)] internal Danmaku.ColliderType collisionType; [Serialize, Default(1f, 1f)] internal Vector2 colliderSize; [Serialize, Default(0f, 0f)] internal Vector2 colliderOffset; [Serialize, fSlider(-180f, 180f)] internal float rotationOffset; #if UNITY_EDITOR public override void Reset() { base.Reset(); danmakuSystemPrefab = (Resources.Load("Danmaku Particle System") as GameObject) .GetComponent<ParticleSystem>(); SpriteRenderer sprite = GetComponent<SpriteRenderer>(); MeshRenderer mesh = GetComponent<MeshRenderer>(); if (sprite == null && mesh == null) { if (EditorUtility.DisplayDialog("Choose a Renderer", "Danmaku Prefab requires one and only one renderer, please chose one", "Sprite Renderer", "Mesh Renderer")) gameObject.AddComponent<SpriteRenderer>(); else { gameObject.AddComponent<MeshFilter>(); gameObject.AddComponent<MeshRenderer>(); } } } #endif [Serialize] internal bool fixedAngle; [Serialize, Default(1000)] internal int initialCount; [Serialize, Default(100)] internal int spawnCount; internal Vector3 cachedScale; internal int cachedLayer; #endregion #region Runtime fields internal DanmakuType type; #endregion #region Accessor Properties public bool FixedAngle { get { return fixedAngle; } } /// <summary> /// Gets the radius of the instance's collider /// </summary> /// <value>the radius of the collider.</value> public Vector2 ColliderSize { get { return colliderSize; } } /// <summary> /// Gets the offset of the instance's collider /// </summary> /// <value>the offset of the collider.</value> public Vector2 ColliderOffset { get { return colliderOffset; } } public DanmakuType Renderer { get { return type; } } #endregion public IEnumerable Infinite() { return new FireData() { Prefab = this }.Infinite(); } public IEnumerator<FireData> GetEnumerator() { yield return new FireData() { Prefab = this }; } IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Batch; using Microsoft.Azure.Management.Batch.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Batch { public partial class BatchManagementClient : ServiceClient<BatchManagementClient>, IBatchManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IAccountOperations _accounts; /// <summary> /// Operations for managing batch accounts /// </summary> public virtual IAccountOperations Accounts { get { return this._accounts; } } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> private BatchManagementClient() : base() { this._accounts = new AccountOperations(this); this._apiVersion = "2014-05-01-privatepreview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public BatchManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public BatchManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> private BatchManagementClient(HttpClient httpClient) : base(httpClient) { this._accounts = new AccountOperations(this); this._apiVersion = "2014-05-01-privatepreview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public BatchManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public BatchManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// BatchManagementClient instance /// </summary> /// <param name='client'> /// Instance of BatchManagementClient to clone to /// </param> protected override void Clone(ServiceClient<BatchManagementClient> client) { base.Clone(client); if (client is BatchManagementClient) { BatchManagementClient clonedClient = ((BatchManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Account Create Operation Status operation returns the /// status of the account creation operation. After calling an /// asynchronous operation, you can call this method to determine /// whether the operation has succeeded, failed, or is still in /// progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the BeginCreating operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Values returned by the Create operation. /// </returns> public async Task<BatchAccountCreateResponse> GetAccountCreateOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); Tracing.Enter(invocationId, this, "GetAccountCreateOperationStatusAsync", tracingParameters); } // Construct URL string url = operationStatusLink.Trim(); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-05-01-privatepreview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result BatchAccountCreateResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new BatchAccountCreateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { AccountResource resourceInstance = new AccountResource(); result.Resource = resourceInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceInstance.Id = idInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); resourceInstance.Type = typeInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceInstance.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceInstance.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); resourceInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { AccountProperties propertiesInstance = new AccountProperties(); resourceInstance.Properties = propertiesInstance; JToken accountEndpointValue = propertiesValue["accountEndpoint"]; if (accountEndpointValue != null && accountEndpointValue.Type != JTokenType.Null) { string accountEndpointInstance = ((string)accountEndpointValue); propertiesInstance.AccountEndpoint = accountEndpointInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { AccountProvisioningState provisioningStateInstance = ((AccountProvisioningState)Enum.Parse(typeof(AccountProvisioningState), ((string)provisioningStateValue), true)); propertiesInstance.ProvisioningState = provisioningStateInstance; } } BatchManagementError errorInstance = new BatchManagementError(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (result.Resource != null && result.Resource.Properties != null && result.Resource.Properties.ProvisioningState == AccountProvisioningState.Succeeded) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Delete Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Delete Operation Status to determine whether the /// operation has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the BeginDeleting operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> GetAccountDeleteOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); Tracing.Enter(invocationId, this, "GetAccountDeleteOperationStatusAsync", tracingParameters); } // Construct URL string url = operationStatusLink.Trim(); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-05-01-privatepreview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NotFound) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.NotFound) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Concurrency; using Orleans.Runtime; using Orleans.Serialization; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates serializers. /// </summary> public static class SerializerGenerator { private static readonly TypeFormattingOptions GeneratedTypeNameOptions = new TypeFormattingOptions( ClassSuffix, includeGenericParameters: false, includeTypeParameters: false, nestedClassSeparator: '_', includeGlobal: false); /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "Serializer"; /// <summary> /// The suffix appended to the name of the generic serializer registration class. /// </summary> private const string RegistererClassSuffix = "Registerer"; /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="type">The grain interface type.</param> /// <param name="onEncounteredType"> /// The callback invoked when a type is encountered. /// </param> /// <returns> /// The generated class. /// </returns> internal static IEnumerable<TypeDeclarationSyntax> GenerateClass(Type type, Action<Type> onEncounteredType) { var typeInfo = type.GetTypeInfo(); var genericTypes = typeInfo.IsGenericTypeDefinition ? typeInfo.GetGenericArguments().Select(_ => SF.TypeParameter(_.ToString())).ToArray() : new TypeParameterSyntax[0]; var attributes = new List<AttributeSyntax> { CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), SF.Attribute(typeof(SerializerAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false)))) }; var className = CodeGeneratorCommon.ClassPrefix + type.GetParseableName(GeneratedTypeNameOptions); var fields = GetFields(type); // Mark each field type for generation foreach (var field in fields) { var fieldType = field.FieldInfo.FieldType; onEncounteredType(fieldType); } var members = new List<MemberDeclarationSyntax>(GenerateStaticFields(fields)) { GenerateDeepCopierMethod(type, fields), GenerateSerializerMethod(type, fields), GenerateDeserializerMethod(type, fields), }; if (typeInfo.IsConstructedGenericType || !typeInfo.IsGenericTypeDefinition) { members.Add(GenerateRegisterMethod(type)); members.Add(GenerateConstructor(className)); attributes.Add(SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax())); } var classDeclaration = SF.ClassDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray())) .AddMembers(members.ToArray()) .AddConstraintClauses(type.GetTypeConstraintSyntax()); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } var classes = new List<TypeDeclarationSyntax> { classDeclaration }; if (typeInfo.IsGenericTypeDefinition) { // Create a generic representation of the serializer type. var serializerType = SF.GenericName(classDeclaration.Identifier) .WithTypeArgumentList( SF.TypeArgumentList() .AddArguments( type.GetGenericArguments() .Select(_ => SF.OmittedTypeArgument()) .Cast<TypeSyntax>() .ToArray())); var registererClassName = className + "_" + string.Join("_", type.GetTypeInfo().GenericTypeParameters.Select(_ => _.Name)) + "_" + RegistererClassSuffix; classes.Add( SF.ClassDeclaration(registererClassName) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddAttributeLists( SF.AttributeList() .AddAttributes( CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), SF.Attribute(typeof(RegisterSerializerAttribute).GetNameSyntax()))) .AddMembers( GenerateMasterRegisterMethod(type, serializerType), GenerateConstructor(registererClassName))); } return classes; } /// <summary> /// Returns syntax for the deserializer method. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <returns>Syntax for the deserializer method.</returns> private static MemberDeclarationSyntax GenerateDeserializerMethod(Type type, List<FieldInfoMember> fields) { Expression<Action> deserializeInner = () => SerializationManager.DeserializeInner(default(Type), default(BinaryTokenStreamReader)); var streamParameter = SF.IdentifierName("stream"); var resultDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("result") .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type))))); var resultVariable = SF.IdentifierName("result"); var body = new List<StatementSyntax> { resultDeclaration }; // Value types cannot be referenced, only copied, so there is no need to box & record instances of value types. if (!type.IsValueType) { // Record the result for cyclic deserialization. Expression<Action> recordObject = () => DeserializationContext.Current.RecordObject(default(object)); var currentSerializationContext = SyntaxFactory.AliasQualifiedName( SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)), SF.IdentifierName("Orleans")) .Qualify("Serialization") .Qualify("DeserializationContext") .Qualify("Current"); body.Add( SF.ExpressionStatement( recordObject.Invoke(currentSerializationContext) .AddArgumentListArguments(SF.Argument(resultVariable)))); } // Deserialize all fields. foreach (var field in fields) { var deserialized = deserializeInner.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(field.Type)), SF.Argument(streamParameter)); body.Add( SF.ExpressionStatement( field.GetSetter( resultVariable, SF.CastExpression(field.Type, deserialized)))); } body.Add(SF.ReturnStatement(SF.CastExpression(type.GetTypeSyntax(), resultVariable))); return SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "Deserializer") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax()), SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamReader).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList() .AddAttributes(SF.Attribute(typeof(DeserializerMethodAttribute).GetNameSyntax()))); } private static MemberDeclarationSyntax GenerateSerializerMethod(Type type, List<FieldInfoMember> fields) { Expression<Action> serializeInner = () => SerializationManager.SerializeInner(default(object), default(BinaryTokenStreamWriter), default(Type)); var body = new List<StatementSyntax> { SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("input") .WithInitializer( SF.EqualsValueClause( SF.CastExpression(type.GetTypeSyntax(), SF.IdentifierName("untypedInput")))))) }; var inputExpression = SF.IdentifierName("input"); // Serialize all members. foreach (var field in fields) { body.Add( SF.ExpressionStatement( serializeInner.Invoke() .AddArgumentListArguments( SF.Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)), SF.Argument(SF.IdentifierName("stream")), SF.Argument(SF.TypeOfExpression(field.FieldInfo.FieldType.GetTypeSyntax()))))); } return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Serializer") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("untypedInput")).WithType(typeof(object).GetTypeSyntax()), SF.Parameter(SF.Identifier("stream")).WithType(typeof(BinaryTokenStreamWriter).GetTypeSyntax()), SF.Parameter(SF.Identifier("expected")).WithType(typeof(Type).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList() .AddAttributes(SF.Attribute(typeof(SerializerMethodAttribute).GetNameSyntax()))); } /// <summary> /// Returns syntax for the deep copier method. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <returns>Syntax for the deep copier method.</returns> private static MemberDeclarationSyntax GenerateDeepCopierMethod(Type type, List<FieldInfoMember> fields) { var originalVariable = SF.IdentifierName("original"); var inputVariable = SF.IdentifierName("input"); var resultVariable = SF.IdentifierName("result"); var body = new List<StatementSyntax>(); if (type.GetCustomAttribute<ImmutableAttribute>() != null) { // Immutable types do not require copying. body.Add(SF.ReturnStatement(originalVariable)); } else { body.Add( SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("input") .WithInitializer( SF.EqualsValueClause( SF.ParenthesizedExpression( SF.CastExpression(type.GetTypeSyntax(), originalVariable))))))); body.Add( SF.LocalDeclarationStatement( SF.VariableDeclaration(type.GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("result") .WithInitializer(SF.EqualsValueClause(GetObjectCreationExpressionSyntax(type)))))); // Copy all members from the input to the result. foreach (var field in fields) { body.Add(SF.ExpressionStatement(field.GetSetter(resultVariable, field.GetGetter(inputVariable)))); } // Record this serialization. Expression<Action> recordObject = () => SerializationContext.Current.RecordObject(default(object), default(object)); var currentSerializationContext = SyntaxFactory.AliasQualifiedName( SF.IdentifierName(SF.Token(SyntaxKind.GlobalKeyword)), SF.IdentifierName("Orleans")) .Qualify("Serialization") .Qualify("SerializationContext") .Qualify("Current"); body.Add( SF.ExpressionStatement( recordObject.Invoke(currentSerializationContext) .AddArgumentListArguments(SF.Argument(originalVariable), SF.Argument(resultVariable)))); body.Add(SF.ReturnStatement(resultVariable)); } return SF.MethodDeclaration(typeof(object).GetTypeSyntax(), "DeepCopier") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters( SF.Parameter(SF.Identifier("original")).WithType(typeof(object).GetTypeSyntax())) .AddBodyStatements(body.ToArray()) .AddAttributeLists( SF.AttributeList().AddAttributes(SF.Attribute(typeof(CopierMethodAttribute).GetNameSyntax()))); } /// <summary> /// Returns syntax for the static fields of the serializer class. /// </summary> /// <param name="fields">The fields.</param> /// <returns>Syntax for the static fields of the serializer class.</returns> private static MemberDeclarationSyntax[] GenerateStaticFields(List<FieldInfoMember> fields) { var result = new List<MemberDeclarationSyntax>(); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Expression<Action<Type>> getField = _ => _.GetField(string.Empty, BindingFlags.Default); Expression<Action> getGetter = () => SerializationManager.GetGetter(default(FieldInfo)); Expression<Action> getReferenceSetter = () => SerializationManager.GetReferenceSetter(default(FieldInfo)); Expression<Action> getValueSetter = () => SerializationManager.GetValueSetter(default(FieldInfo)); // Expressions for specifying binding flags. var bindingFlags = SyntaxFactoryExtensions.GetBindingFlagsParenthesizedExpressionSyntax( SyntaxKind.BitwiseOrExpression, BindingFlags.Instance, BindingFlags.NonPublic, BindingFlags.Public); // Add each field and initialize it. foreach (var field in fields) { var fieldInfo = getField.Invoke(SF.TypeOfExpression(field.FieldInfo.DeclaringType.GetTypeSyntax())) .AddArgumentListArguments( SF.Argument(field.FieldInfo.Name.GetLiteralExpression()), SF.Argument(bindingFlags)); var fieldInfoVariable = SF.VariableDeclarator(field.InfoFieldName).WithInitializer(SF.EqualsValueClause(fieldInfo)); var fieldInfoField = SF.IdentifierName(field.InfoFieldName); if (!field.IsGettableProperty || !field.IsSettableProperty) { result.Add( SF.FieldDeclaration( SF.VariableDeclaration(typeof(FieldInfo).GetTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } // Declare the getter for this field. if (!field.IsGettableProperty) { var getterType = typeof(Func<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType) .GetTypeSyntax(); var fieldGetterVariable = SF.VariableDeclarator(field.GetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( getterType, getGetter.Invoke().AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(getterType).AddVariables(fieldGetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } if (!field.IsSettableProperty) { if (field.FieldInfo.DeclaringType != null && field.FieldInfo.DeclaringType.IsValueType) { var setterType = typeof(SerializationManager.ValueTypeSetter<,>).MakeGenericType( field.FieldInfo.DeclaringType, field.FieldInfo.FieldType).GetTypeSyntax(); var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( setterType, getValueSetter.Invoke() .AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } else { var setterType = typeof(Action<,>).MakeGenericType(field.FieldInfo.DeclaringType, field.FieldInfo.FieldType) .GetTypeSyntax(); var fieldSetterVariable = SF.VariableDeclarator(field.SetterFieldName) .WithInitializer( SF.EqualsValueClause( SF.CastExpression( setterType, getReferenceSetter.Invoke() .AddArgumentListArguments(SF.Argument(fieldInfoField))))); result.Add( SF.FieldDeclaration(SF.VariableDeclaration(setterType).AddVariables(fieldSetterVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword))); } } } return result.ToArray(); } /// <summary> /// Returns syntax for initializing a new instance of the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>Syntax for initializing a new instance of the provided type.</returns> private static ExpressionSyntax GetObjectCreationExpressionSyntax(Type type) { ExpressionSyntax result; var typeInfo = type.GetTypeInfo(); if (typeInfo.IsValueType) { // Use the default value. result = SF.DefaultExpression(typeInfo.GetTypeSyntax()); } else if (type.GetConstructor(Type.EmptyTypes) != null) { // Use the default constructor. result = SF.ObjectCreationExpression(typeInfo.GetTypeSyntax()).AddArgumentListArguments(); } else { // Create an unformatted object. #if DNXCORE50 var bindingFlags = SyntaxFactoryExtensions.GetBindingFlagsParenthesizedExpressionSyntax( SyntaxKind.BitwiseOrExpression, BindingFlags.Instance, BindingFlags.NonPublic, BindingFlags.Public); var nullLiteralExpressionArgument = SF.Argument(SF.LiteralExpression(SyntaxKind.NullLiteralExpression)); var typeArg = SF.Argument(SF.TypeOfExpression(typeInfo.GetTypeSyntax())); var bindingFlagsArg = SF.Argument(bindingFlags); var binderArg = nullLiteralExpressionArgument; ArgumentSyntax ctorArgumentsArg; var cons = typeInfo.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .OrderBy(p => p.GetParameters().Count()).FirstOrDefault(); var consParameters = cons != null ? cons.GetParameters().Select(p => p.ParameterType).ToArray() : null; if (consParameters != null && consParameters.Length > 0) { var separatedSyntaxList = new SeparatedSyntaxList<ExpressionSyntax>(); separatedSyntaxList = consParameters .Aggregate(separatedSyntaxList, (current, t) => current.Add(SF.DefaultExpression(t.GetTypeInfo().GetTypeSyntax()))); ctorArgumentsArg = SF.Argument(separatedSyntaxList.GetArrayCreationWithInitializerSyntax( SF.PredefinedType(SF.Token(SyntaxKind.ObjectKeyword)))); } else { ctorArgumentsArg = nullLiteralExpressionArgument; } var cultureInfoArg = SF.Argument( SF.IdentifierName("System").Member("Globalization").Member("CultureInfo").Member("InvariantCulture")); var createInstanceArguments = new [] { typeArg, bindingFlagsArg, binderArg, ctorArgumentsArg, cultureInfoArg }; Expression<Func<object>> getUninitializedObject = () => Activator.CreateInstance( default(Type), BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, null, System.Globalization.CultureInfo.InvariantCulture); result = SF.CastExpression( type.GetTypeSyntax(), getUninitializedObject.Invoke() .AddArgumentListArguments(createInstanceArguments)); #else Expression<Func<object>> getUninitializedObject = () => FormatterServices.GetUninitializedObject(default(Type)); result = SF.CastExpression( type.GetTypeSyntax(), getUninitializedObject.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(typeInfo.GetTypeSyntax())))); #endif } return result; } /// <summary> /// Returns syntax for the serializer registration method. /// </summary> /// <param name="type">The type.</param> /// <returns>Syntax for the serializer registration method.</returns> private static MemberDeclarationSyntax GenerateRegisterMethod(Type type) { Expression<Action> register = () => SerializationManager.Register( default(Type), default(SerializationManager.DeepCopier), default(SerializationManager.Serializer), default(SerializationManager.Deserializer)); return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters() .AddBodyStatements( SF.ExpressionStatement( register.Invoke() .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(type.GetTypeSyntax())), SF.Argument(SF.IdentifierName("DeepCopier")), SF.Argument(SF.IdentifierName("Serializer")), SF.Argument(SF.IdentifierName("Deserializer"))))); } /// <summary> /// Returns syntax for the constructor. /// </summary> /// <param name="className">The name of the class.</param> /// <returns>Syntax for the constructor.</returns> private static ConstructorDeclarationSyntax GenerateConstructor(string className) { return SF.ConstructorDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters() .AddBodyStatements( SF.ExpressionStatement( SF.InvocationExpression(SF.IdentifierName("Register")).AddArgumentListArguments())); } /// <summary> /// Returns syntax for the generic serializer registration method for the provided type.. /// </summary> /// <param name="type">The type which is supported by this serializer.</param> /// <param name="serializerType">The type of the serializer.</param> /// <returns>Syntax for the generic serializer registration method for the provided type..</returns> private static MemberDeclarationSyntax GenerateMasterRegisterMethod(Type type, TypeSyntax serializerType) { Expression<Action> register = () => SerializationManager.Register(default(Type), default(Type)); return SF.MethodDeclaration(typeof(void).GetTypeSyntax(), "Register") .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.StaticKeyword)) .AddParameterListParameters() .AddBodyStatements( SF.ExpressionStatement( register.Invoke() .AddArgumentListArguments( SF.Argument( SF.TypeOfExpression(type.GetTypeSyntax(includeGenericParameters: false))), SF.Argument(SF.TypeOfExpression(serializerType))))); } /// <summary> /// Returns a sorted list of the fields of the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>A sorted list of the fields of the provided type.</returns> private static List<FieldInfoMember> GetFields(Type type) { var result = type.GetAllFields() .Where(field => !field.IsNotSerialized) .Select((info, i) => new FieldInfoMember { FieldInfo = info, FieldNumber = i }) .ToList(); result.Sort(FieldInfoMember.Comparer.Instance); return result; } /// <summary> /// Represents a field. /// </summary> private class FieldInfoMember { private PropertyInfo property; /// <summary> /// Gets or sets the underlying <see cref="FieldInfo"/> instance. /// </summary> public FieldInfo FieldInfo { get; set; } /// <summary> /// Sets the ordinal assigned to this field. /// </summary> public int FieldNumber { private get; set; } /// <summary> /// Gets the name of the field info field. /// </summary> public string InfoFieldName { get { return "field" + this.FieldNumber; } } /// <summary> /// Gets the name of the getter field. /// </summary> public string GetterFieldName { get { return "getField" + this.FieldNumber; } } /// <summary> /// Gets the name of the setter field. /// </summary> public string SetterFieldName { get { return "setField" + this.FieldNumber; } } /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter. /// </summary> public bool IsGettableProperty { get { return this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete; } } /// <summary> /// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter. /// </summary> public bool IsSettableProperty { get { return this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete; } } /// <summary> /// Gets syntax representing the type of this field. /// </summary> public TypeSyntax Type { get { return this.FieldInfo.FieldType.GetTypeSyntax(); } } /// <summary> /// Gets the <see cref="PropertyInfo"/> which this field is the backing property for, or /// <see langword="null" /> if this is not the backing field of an auto-property. /// </summary> private PropertyInfo PropertyInfo { get { if (this.property != null) { return this.property; } var propertyName = Regex.Match(this.FieldInfo.Name, "^<([^>]+)>.*$"); if (propertyName.Success && this.FieldInfo.DeclaringType != null) { var name = propertyName.Groups[1].Value; this.property = this.FieldInfo.DeclaringType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public); } return this.property; } } /// <summary> /// Gets a value indicating whether or not this field is obsolete. /// </summary> private bool IsObsolete { get { var obsoleteAttr = this.FieldInfo.GetCustomAttribute<ObsoleteAttribute>(); // Get the attribute from the property, if present. if (this.property != null && obsoleteAttr == null) { obsoleteAttr = this.property.GetCustomAttribute<ObsoleteAttribute>(); } return obsoleteAttr != null; } } /// <summary> /// Returns syntax for retrieving the value of this field, deep copying it if neccessary. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param> /// <returns>Syntax for retrieving the value of this field.</returns> public ExpressionSyntax GetGetter(ExpressionSyntax instance, bool forceAvoidCopy = false) { // Retrieve the value of the field. var getValueExpression = this.GetValueExpression(instance); // Avoid deep-copying the field if possible. if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable()) { // Return the value without deep-copying it. return getValueExpression; } // Deep-copy the value. Expression<Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object)); var typeSyntax = this.FieldInfo.FieldType.GetTypeSyntax(); return SF.CastExpression( typeSyntax, deepCopyInner.Invoke().AddArgumentListArguments(SF.Argument(getValueExpression))); } /// <summary> /// Returns syntax for setting the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <param name="value">Syntax for the new value.</param> /// <returns>Syntax for setting the value of this field.</returns> public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) { // If the field is the backing field for an accessible auto-property use the property directly. if (this.PropertyInfo != null && this.PropertyInfo.GetSetMethod() != null && !this.IsObsolete) { return SF.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, instance.Member(this.PropertyInfo.Name), value); } var instanceArg = SF.Argument(instance); if (this.FieldInfo.DeclaringType != null && this.FieldInfo.DeclaringType.IsValueType) { instanceArg = instanceArg.WithRefOrOutKeyword(SF.Token(SyntaxKind.RefKeyword)); } return SF.InvocationExpression(SF.IdentifierName(this.SetterFieldName)) .AddArgumentListArguments(instanceArg, SF.Argument(value)); } /// <summary> /// Returns syntax for retrieving the value of this field. /// </summary> /// <param name="instance">The instance of the containing type.</param> /// <returns>Syntax for retrieving the value of this field.</returns> private ExpressionSyntax GetValueExpression(ExpressionSyntax instance) { // If the field is the backing field for an accessible auto-property use the property directly. ExpressionSyntax result; if (this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null && !this.IsObsolete) { result = instance.Member(this.PropertyInfo.Name); } else { // Retrieve the field using the generated getter. result = SF.InvocationExpression(SF.IdentifierName(this.GetterFieldName)) .AddArgumentListArguments(SF.Argument(instance)); } return result; } /// <summary> /// A comparer for <see cref="FieldInfoMember"/> which compares by name. /// </summary> public class Comparer : IComparer<FieldInfoMember> { /// <summary> /// The singleton instance. /// </summary> private static readonly Comparer Singleton = new Comparer(); /// <summary> /// Gets the singleton instance of this class. /// </summary> public static Comparer Instance { get { return Singleton; } } public int Compare(FieldInfoMember x, FieldInfoMember y) { return string.Compare(x.FieldInfo.Name, y.FieldInfo.Name, StringComparison.Ordinal); } } } } }
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Security { using System.ServiceModel.Channels; using System.ServiceModel; using System.ServiceModel.Diagnostics; using System.IdentityModel.Selectors; using System.Runtime.Diagnostics; class WrapperSecurityCommunicationObject : CommunicationObject { ISecurityCommunicationObject innerCommunicationObject; public WrapperSecurityCommunicationObject(ISecurityCommunicationObject innerCommunicationObject) : base() { if (innerCommunicationObject == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerCommunicationObject"); } this.innerCommunicationObject = innerCommunicationObject; } protected override Type GetCommunicationObjectType() { return this.innerCommunicationObject.GetType(); } protected override TimeSpan DefaultCloseTimeout { get { return this.innerCommunicationObject.DefaultCloseTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return this.innerCommunicationObject.DefaultOpenTimeout; } } protected override void OnAbort() { this.innerCommunicationObject.OnAbort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return this.innerCommunicationObject.OnBeginClose(timeout, callback, state); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return this.innerCommunicationObject.OnBeginOpen(timeout, callback, state); } protected override void OnClose(TimeSpan timeout) { this.innerCommunicationObject.OnClose(timeout); } protected override void OnClosed() { this.innerCommunicationObject.OnClosed(); base.OnClosed(); } protected override void OnClosing() { this.innerCommunicationObject.OnClosing(); base.OnClosing(); } protected override void OnEndClose(IAsyncResult result) { this.innerCommunicationObject.OnEndClose(result); } protected override void OnEndOpen(IAsyncResult result) { this.innerCommunicationObject.OnEndOpen(result); } protected override void OnFaulted() { this.innerCommunicationObject.OnFaulted(); base.OnFaulted(); } protected override void OnOpen(TimeSpan timeout) { this.innerCommunicationObject.OnOpen(timeout); } protected override void OnOpened() { this.innerCommunicationObject.OnOpened(); base.OnOpened(); } protected override void OnOpening() { this.innerCommunicationObject.OnOpening(); base.OnOpening(); } new internal void ThrowIfDisposedOrImmutable() { base.ThrowIfDisposedOrImmutable(); } } abstract class CommunicationObjectSecurityTokenProvider : SecurityTokenProvider, ICommunicationObject, ISecurityCommunicationObject { EventTraceActivity eventTraceActivity; WrapperSecurityCommunicationObject communicationObject; protected CommunicationObjectSecurityTokenProvider() { communicationObject = new WrapperSecurityCommunicationObject(this); } internal EventTraceActivity EventTraceActivity { get { if (eventTraceActivity == null) { eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate(); } return this.eventTraceActivity; } } protected WrapperSecurityCommunicationObject CommunicationObject { get { return this.communicationObject; } } public event EventHandler Closed { add { this.communicationObject.Closed += value; } remove { this.communicationObject.Closed -= value; } } public event EventHandler Closing { add { this.communicationObject.Closing += value; } remove { this.communicationObject.Closing -= value; } } public event EventHandler Faulted { add { this.communicationObject.Faulted += value; } remove { this.communicationObject.Faulted -= value; } } public event EventHandler Opened { add { this.communicationObject.Opened += value; } remove { this.communicationObject.Opened -= value; } } public event EventHandler Opening { add { this.communicationObject.Opening += value; } remove { this.communicationObject.Opening -= value; } } public CommunicationState State { get { return this.communicationObject.State; } } public virtual TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public virtual TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } // communication object public void Abort() { this.communicationObject.Abort(); } public void Close() { this.communicationObject.Close(); } public void Close(TimeSpan timeout) { this.communicationObject.Close(timeout); } public IAsyncResult BeginClose(AsyncCallback callback, object state) { return this.communicationObject.BeginClose(callback, state); } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return this.communicationObject.BeginClose(timeout, callback, state); } public void EndClose(IAsyncResult result) { this.communicationObject.EndClose(result); } public void Open() { this.communicationObject.Open(); } public void Open(TimeSpan timeout) { this.communicationObject.Open(timeout); } public IAsyncResult BeginOpen(AsyncCallback callback, object state) { return this.communicationObject.BeginOpen(callback, state); } public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return this.communicationObject.BeginOpen(timeout, callback, state); } public void EndOpen(IAsyncResult result) { this.communicationObject.EndOpen(result); } public void Dispose() { this.Close(); } // ISecurityCommunicationObject methods public virtual void OnAbort() { } public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnClose), timeout, callback, state); } public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnOpen), timeout, callback, state); } public virtual void OnClose(TimeSpan timeout) { } public virtual void OnClosed() { SecurityTraceRecordHelper.TraceTokenProviderClosed(this); } public virtual void OnClosing() { } public void OnEndClose(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnEndOpen(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public virtual void OnFaulted() { this.OnAbort(); } public virtual void OnOpen(TimeSpan timeout) { } public virtual void OnOpened() { SecurityTraceRecordHelper.TraceTokenProviderOpened(this.EventTraceActivity, this); } public virtual void OnOpening() { } } abstract class CommunicationObjectSecurityTokenAuthenticator : SecurityTokenAuthenticator, ICommunicationObject, ISecurityCommunicationObject { WrapperSecurityCommunicationObject communicationObject; protected CommunicationObjectSecurityTokenAuthenticator() { communicationObject = new WrapperSecurityCommunicationObject(this); } protected WrapperSecurityCommunicationObject CommunicationObject { get { return this.communicationObject; } } public event EventHandler Closed { add { this.communicationObject.Closed += value; } remove { this.communicationObject.Closed -= value; } } public event EventHandler Closing { add { this.communicationObject.Closing += value; } remove { this.communicationObject.Closing -= value; } } public event EventHandler Faulted { add { this.communicationObject.Faulted += value; } remove { this.communicationObject.Faulted -= value; } } public event EventHandler Opened { add { this.communicationObject.Opened += value; } remove { this.communicationObject.Opened -= value; } } public event EventHandler Opening { add { this.communicationObject.Opening += value; } remove { this.communicationObject.Opening -= value; } } public CommunicationState State { get { return this.communicationObject.State; } } public virtual TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public virtual TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } // communication object public void Abort() { this.communicationObject.Abort(); } public void Close() { this.communicationObject.Close(); } public void Close(TimeSpan timeout) { this.communicationObject.Close(timeout); } public IAsyncResult BeginClose(AsyncCallback callback, object state) { return this.communicationObject.BeginClose(callback, state); } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return this.communicationObject.BeginClose(timeout, callback, state); } public void EndClose(IAsyncResult result) { this.communicationObject.EndClose(result); } public void Open() { this.communicationObject.Open(); } public void Open(TimeSpan timeout) { this.communicationObject.Open(timeout); } public IAsyncResult BeginOpen(AsyncCallback callback, object state) { return this.communicationObject.BeginOpen(callback, state); } public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return this.communicationObject.BeginOpen(timeout, callback, state); } public void EndOpen(IAsyncResult result) { this.communicationObject.EndOpen(result); } public void Dispose() { this.Close(); } // ISecurityCommunicationObject methods public virtual void OnAbort() { } public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnClose), timeout, callback, state); } public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnOpen), timeout, callback, state); } public virtual void OnClose(TimeSpan timeout) { } public virtual void OnClosed() { SecurityTraceRecordHelper.TraceTokenAuthenticatorClosed(this); } public virtual void OnClosing() { } public void OnEndClose(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnEndOpen(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public virtual void OnFaulted() { this.OnAbort(); } public virtual void OnOpen(TimeSpan timeout) { } public virtual void OnOpened() { SecurityTraceRecordHelper.TraceTokenAuthenticatorOpened(this); } public virtual void OnOpening() { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using Microsoft.Practices.ServiceLocation; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Prism.Events; using Prism.Logging; using Prism.Mef.Modularity; using Prism.Modularity; using Prism.Regions; using Prism.Regions.Behaviors; namespace Prism.Mef.Wpf.Tests { [TestClass] public class DefaultPrismServiceRegistrarFixture { [TestMethod] public void NullAggregateCatalogThrows() { try { DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(null); Assert.Fail("Expected exception not thrown"); } catch (Exception) { // no op } } [TestMethod] public void SingleSelectorItemsSourceSyncBehaviorIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); foreach (var part in container.Catalog.Parts) { foreach (var export in part.ExportDefinitions) { System.Diagnostics.Debug.WriteLine(string.Format("Part contract name => '{0}'", export.ContractName)); } } var exportedValue = container.GetExportedValue<SelectorItemsSourceSyncBehavior>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleRegionLifetimeBehaviorIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); foreach (var part in container.Catalog.Parts) { foreach (var export in part.ExportDefinitions) { System.Diagnostics.Debug.WriteLine(string.Format("Part contract name => '{0}'", export.ContractName)); } } var exportedValue = container.GetExportedValue<RegionMemberLifetimeBehavior>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleIRegionViewRegistryIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<IRegionViewRegistry>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleContentControlRegionAdapterIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<ContentControlRegionAdapter>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleIModuleInitializerIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); container.ComposeExportedValue<AggregateCatalog>(catalog); SetupLoggerForTest(container); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<IModuleInitializer>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleIEventAggregatorIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<IEventAggregator>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleSelectorRegionAdapterIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<SelectorRegionAdapter>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleBindRegionContextToDependencyObjectBehaviorIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<BindRegionContextToDependencyObjectBehavior>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleIRegionManagerIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<IRegionManager>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleRegionAdapterMappingsIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<RegionAdapterMappings>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleItemsControlRegionAdapterIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<ItemsControlRegionAdapter>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleSyncRegionContextWithHostBehaviorIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<SyncRegionContextWithHostBehavior>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleIRegionNavigationServiceIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<IRegionNavigationService>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleIRegionNavigationContentLoaderIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<IRegionNavigationContentLoader>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleRegionManagerRegistrationBehaviorIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<RegionManagerRegistrationBehavior>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleIModuleManagerIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); container.ComposeExportedValue<IModuleCatalog>(new ModuleCatalog()); container.ComposeExportedValue<AggregateCatalog>(catalog); SetupLoggerForTest(container); SetupServiceLocator(container); DumpExportsFromCompositionContainer(container); var exportedValue = container.GetExportedValue<IModuleManager>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleDelayedRegionCreationBehaviorIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<DelayedRegionCreationBehavior>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleAutoPopulateRegionBehaviorIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<AutoPopulateRegionBehavior>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleRegionActiveAwareBehaviorIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<RegionActiveAwareBehavior>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleMefFileModuleTypeLoaderIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); container.ComposeExportedValue<AggregateCatalog>(catalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<MefFileModuleTypeLoader>(); Assert.IsNotNull(exportedValue); } [TestMethod] public void SingleIRegionBehaviorFactoryIsRegisteredWithContainer() { AggregateCatalog catalog = new AggregateCatalog(); var newCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(catalog); CompositionContainer container = new CompositionContainer(newCatalog); SetupServiceLocator(container); var exportedValue = container.GetExportedValue<IRegionBehaviorFactory>(); Assert.IsNotNull(exportedValue); } private void DumpExportsFromCompositionContainer(CompositionContainer container) { foreach (var part in container.Catalog.Parts) { foreach (var export in part.ExportDefinitions) { System.Diagnostics.Debug.WriteLine(string.Format("Part contract name => '{0}'", export.ContractName)); } } } private void SetupServiceLocator(CompositionContainer container) { container.ComposeExportedValue<IServiceLocator>(new MefServiceLocatorAdapter(container)); IServiceLocator serviceLocator = container.GetExportedValue<IServiceLocator>(); ServiceLocator.SetLocatorProvider(() => serviceLocator); } private static void SetupLoggerForTest(CompositionContainer container) { ILoggerFacade logger = new Mock<ILoggerFacade>().Object; container.ComposeExportedValue<ILoggerFacade>(logger); } } }
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System.Threading { internal sealed class ThreadHelper { private Delegate _start; internal CultureInfo? _startCulture; internal CultureInfo? _startUICulture; private object? _startArg = null; private ExecutionContext? _executionContext = null; internal ThreadHelper(Delegate start) { _start = start; } internal void SetExecutionContextHelper(ExecutionContext? ec) { _executionContext = ec; } internal static readonly ContextCallback s_threadStartContextCallback = new ContextCallback(ThreadStart_Context); private static void ThreadStart_Context(object? state) { Debug.Assert(state is ThreadHelper); ThreadHelper t = (ThreadHelper)state; t.InitializeCulture(); Debug.Assert(t._start is ThreadStart || t._start is ParameterizedThreadStart); if (t._start is ThreadStart threadStart) { threadStart(); } else { ((ParameterizedThreadStart)t._start)(t._startArg); } } private void InitializeCulture() { if (_startCulture != null) { CultureInfo.CurrentCulture = _startCulture; _startCulture = null; } if (_startUICulture != null) { CultureInfo.CurrentUICulture = _startUICulture; _startUICulture = null; } } // call back helper internal void ThreadStart(object? obj) { Debug.Assert(_start is ParameterizedThreadStart); _startArg = obj; ExecutionContext? context = _executionContext; if (context != null) { ExecutionContext.RunInternal(context, s_threadStartContextCallback, this); } else { InitializeCulture(); ((ParameterizedThreadStart)_start)(obj); } } // call back helper internal void ThreadStart() { Debug.Assert(_start is ThreadStart); ExecutionContext? context = _executionContext; if (context != null) { ExecutionContext.RunInternal(context, s_threadStartContextCallback, this); } else { InitializeCulture(); ((ThreadStart)_start)(); } } } internal readonly struct ThreadHandle { private readonly IntPtr _ptr; internal ThreadHandle(IntPtr pThread) { _ptr = pThread; } } public sealed partial class Thread { /*========================================================================= ** Data accessed from managed code that needs to be defined in ** ThreadBaseObject to maintain alignment between the two classes. ** DON'T CHANGE THESE UNLESS YOU MODIFY ThreadBaseObject in vm\object.h =========================================================================*/ internal ExecutionContext? _executionContext; // this call context follows the logical thread internal SynchronizationContext? _synchronizationContext; // maintained separately from ExecutionContext private string? _name; private Delegate? _delegate; // Delegate private object? _threadStartArg; /*========================================================================= ** The base implementation of Thread is all native. The following fields ** should never be used in the C# code. They are here to define the proper ** space so the thread object may be allocated. DON'T CHANGE THESE UNLESS ** YOU MODIFY ThreadBaseObject in vm\object.h =========================================================================*/ #pragma warning disable CA1823, 169 // These fields are not used from managed. // IntPtrs need to be together, and before ints, because IntPtrs are 64-bit // fields on 64-bit platforms, where they will be sorted together. private IntPtr _DONT_USE_InternalThread; // Pointer private int _priority; // INT32 // The following field is required for interop with the VS Debugger // Prior to making any changes to this field, please reach out to the VS Debugger // team to make sure that your changes are not going to prevent the debugger // from working. private int _managedThreadId; // INT32 #pragma warning restore CA1823, 169 private Thread() { } private void Create(ThreadStart start) => SetStartHelper((Delegate)start, 0); // 0 will setup Thread with default stackSize private void Create(ThreadStart start, int maxStackSize) => SetStartHelper((Delegate)start, maxStackSize); private void Create(ParameterizedThreadStart start) => SetStartHelper((Delegate)start, 0); private void Create(ParameterizedThreadStart start, int maxStackSize) => SetStartHelper((Delegate)start, maxStackSize); public extern int ManagedThreadId { [MethodImpl(MethodImplOptions.InternalCall)] get; } /// <summary>Returns handle for interop with EE. The handle is guaranteed to be non-null.</summary> internal ThreadHandle GetNativeHandle() { IntPtr thread = _DONT_USE_InternalThread; // This should never happen under normal circumstances. if (thread == IntPtr.Zero) { throw new ArgumentException(null, SR.Argument_InvalidHandle); } return new ThreadHandle(thread); } /// <summary> /// Spawns off a new thread which will begin executing at the ThreadStart /// method on the IThreadable interface passed in the constructor. Once the /// thread is dead, it cannot be restarted with another call to Start. /// </summary> public void Start(object? parameter) { // In the case of a null delegate (second call to start on same thread) // StartInternal method will take care of the error reporting. if (_delegate is ThreadStart) { // We expect the thread to be setup with a ParameterizedThreadStart if this Start is called. throw new InvalidOperationException(SR.InvalidOperation_ThreadWrongThreadStart); } _threadStartArg = parameter; Start(); } public void Start() { #if FEATURE_COMINTEROP_APARTMENT_SUPPORT // Eagerly initialize the COM Apartment state of the thread if we're allowed to. StartupSetApartmentStateInternal(); #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT // Attach current thread's security principal object to the new // thread. Be careful not to bind the current thread to a principal // if it's not already bound. if (_delegate != null) { // If we reach here with a null delegate, something is broken. But we'll let the StartInternal method take care of // reporting an error. Just make sure we don't try to dereference a null delegate. Debug.Assert(_delegate.Target is ThreadHelper); var t = (ThreadHelper)_delegate.Target; ExecutionContext? ec = ExecutionContext.Capture(); t.SetExecutionContextHelper(ec); } StartInternal(); } private void SetCultureOnUnstartedThreadNoCheck(CultureInfo value, bool uiCulture) { Debug.Assert(_delegate != null); Debug.Assert(_delegate.Target is ThreadHelper); var t = (ThreadHelper)(_delegate.Target); if (uiCulture) { t._startUICulture = value; } else { t._startCulture = value; } } [MethodImpl(MethodImplOptions.InternalCall)] private extern void StartInternal(); // Invoked by VM. Helper method to get a logical thread ID for StringBuilder (for // correctness) and for FileStream's async code path (for perf, to avoid creating // a Thread instance). [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr InternalGetCurrentThread(); /// <summary> /// Suspends the current thread for timeout milliseconds. If timeout == 0, /// forces the thread to give up the remainder of its timeslice. If timeout /// == Timeout.Infinite, no timeout will occur. /// </summary> [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SleepInternal(int millisecondsTimeout); public static void Sleep(int millisecondsTimeout) => SleepInternal(millisecondsTimeout); /// <summary> /// Wait for a length of time proportional to 'iterations'. Each iteration is should /// only take a few machine instructions. Calling this API is preferable to coding /// a explicit busy loop because the hardware can be informed that it is busy waiting. /// </summary> [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SpinWaitInternal(int iterations); public static void SpinWait(int iterations) => SpinWaitInternal(iterations); [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)] private static extern Interop.BOOL YieldInternal(); public static bool Yield() => YieldInternal() != Interop.BOOL.FALSE; [MethodImpl(MethodImplOptions.NoInlining)] private static Thread InitializeCurrentThread() => t_currentThread = GetCurrentThreadNative(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Thread GetCurrentThreadNative(); private void SetStartHelper(Delegate start, int maxStackSize) { Debug.Assert(maxStackSize >= 0); var helper = new ThreadHelper(start); if (start is ThreadStart) { SetStart(new ThreadStart(helper.ThreadStart), maxStackSize); } else { SetStart(new ParameterizedThreadStart(helper.ThreadStart), maxStackSize); } } /// <summary>Sets the IThreadable interface for the thread. Assumes that start != null.</summary> [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetStart(Delegate start, int maxStackSize); /// <summary>Clean up the thread when it goes away.</summary> ~Thread() => InternalFinalize(); // Delegate to the unmanaged portion. [MethodImpl(MethodImplOptions.InternalCall)] private extern void InternalFinalize(); #if FEATURE_COMINTEROP_APARTMENT_SUPPORT [MethodImpl(MethodImplOptions.InternalCall)] private extern void StartupSetApartmentStateInternal(); #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT partial void ThreadNameChanged(string? value) { InformThreadNameChange(GetNativeHandle(), value, value?.Length ?? 0); } [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void InformThreadNameChange(ThreadHandle t, string? name, int len); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern DeserializationTracker GetThreadDeserializationTracker(ref StackCrawlMark stackMark); /// <summary>Returns true if the thread has been started and is not dead.</summary> public extern bool IsAlive { [MethodImpl(MethodImplOptions.InternalCall)] get; } /// <summary> /// Return whether or not this thread is a background thread. Background /// threads do not affect when the Execution Engine shuts down. /// </summary> public bool IsBackground { get => IsBackgroundNative(); set => SetBackgroundNative(value); } [MethodImpl(MethodImplOptions.InternalCall)] private extern bool IsBackgroundNative(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetBackgroundNative(bool isBackground); /// <summary>Returns true if the thread is a threadpool thread.</summary> public extern bool IsThreadPoolThread { [MethodImpl(MethodImplOptions.InternalCall)] get; } /// <summary>Returns the priority of the thread.</summary> public ThreadPriority Priority { get => (ThreadPriority)GetPriorityNative(); set => SetPriorityNative((int)value); } [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetPriorityNative(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetPriorityNative(int priority); /// <summary>Returns the operating system identifier for the current thread.</summary> internal static ulong CurrentOSThreadId => GetCurrentOSThreadId(); [DllImport(RuntimeHelpers.QCall)] private static extern ulong GetCurrentOSThreadId(); /// <summary> /// Return the thread state as a consistent set of bits. This is more /// general then IsAlive or IsBackground. /// </summary> public ThreadState ThreadState => (ThreadState)GetThreadStateNative(); [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetThreadStateNative(); public ApartmentState GetApartmentState() => #if FEATURE_COMINTEROP_APARTMENT_SUPPORT (ApartmentState)GetApartmentStateNative(); #else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT ApartmentState.Unknown; #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT /// <summary> /// An unstarted thread can be marked to indicate that it will host a /// single-threaded or multi-threaded apartment. /// </summary> private bool TrySetApartmentStateUnchecked(ApartmentState state) => #if FEATURE_COMINTEROP_APARTMENT_SUPPORT SetApartmentStateHelper(state, false); #else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT state == ApartmentState.Unknown; #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT #if FEATURE_COMINTEROP_APARTMENT_SUPPORT internal bool SetApartmentStateHelper(ApartmentState state, bool fireMDAOnMismatch) { ApartmentState retState = (ApartmentState)SetApartmentStateNative((int)state, fireMDAOnMismatch); // Special case where we pass in Unknown and get back MTA. // Once we CoUninitialize the thread, the OS will still // report the thread as implicitly in the MTA if any // other thread in the process is CoInitialized. if ((state == System.Threading.ApartmentState.Unknown) && (retState == System.Threading.ApartmentState.MTA)) { return true; } if (retState != state) { return false; } return true; } [MethodImpl(MethodImplOptions.InternalCall)] internal extern int GetApartmentStateNative(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern int SetApartmentStateNative(int state, bool fireMDAOnMismatch); #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT #if FEATURE_COMINTEROP [MethodImpl(MethodImplOptions.InternalCall)] public extern void DisableComObjectEagerCleanup(); #else // !FEATURE_COMINTEROP public void DisableComObjectEagerCleanup() { } #endif // FEATURE_COMINTEROP /// <summary> /// Interrupts a thread that is inside a Wait(), Sleep() or Join(). If that /// thread is not currently blocked in that manner, it will be interrupted /// when it next begins to block. /// </summary> [MethodImpl(MethodImplOptions.InternalCall)] public extern void Interrupt(); /// <summary> /// Waits for the thread to die or for timeout milliseconds to elapse. /// </summary> /// <returns> /// Returns true if the thread died, or false if the wait timed out. If /// -1 is given as the parameter, no timeout will occur. /// </returns> /// <exception cref="ArgumentException">if timeout &lt; -1 (Timeout.Infinite)</exception> /// <exception cref="ThreadInterruptedException">if the thread is interrupted while waiting</exception> /// <exception cref="ThreadStateException">if the thread has not been started yet</exception> [MethodImpl(MethodImplOptions.InternalCall)] public extern bool Join(int millisecondsTimeout); private static int s_optimalMaxSpinWaitsPerSpinIteration; [DllImport(RuntimeHelpers.QCall)] private static extern int GetOptimalMaxSpinWaitsPerSpinIterationInternal(); /// <summary> /// Max value to be passed into <see cref="SpinWait(int)"/> for optimal delaying. This value is normalized to be /// appropriate for the processor. /// </summary> internal static int OptimalMaxSpinWaitsPerSpinIteration { get { int optimalMaxSpinWaitsPerSpinIteration = s_optimalMaxSpinWaitsPerSpinIteration; return optimalMaxSpinWaitsPerSpinIteration != 0 ? optimalMaxSpinWaitsPerSpinIteration : CalculateOptimalMaxSpinWaitsPerSpinIteration(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static int CalculateOptimalMaxSpinWaitsPerSpinIteration() { // This is done lazily because the first call to the function below in the process triggers a measurement that // takes a nontrivial amount of time if the measurement has not already been done in the backgorund. // See Thread::InitializeYieldProcessorNormalized(), which describes and calculates this value. s_optimalMaxSpinWaitsPerSpinIteration = GetOptimalMaxSpinWaitsPerSpinIterationInternal(); Debug.Assert(s_optimalMaxSpinWaitsPerSpinIteration > 0); return s_optimalMaxSpinWaitsPerSpinIteration; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetCurrentProcessorNumber(); // The upper bits of t_currentProcessorIdCache are the currentProcessorId. The lower bits of // the t_currentProcessorIdCache are counting down to get it periodically refreshed. // TODO: Consider flushing the currentProcessorIdCache on Wait operations or similar // actions that are likely to result in changing the executing core [ThreadStatic] private static int t_currentProcessorIdCache; private const int ProcessorIdCacheShift = 16; private const int ProcessorIdCacheCountDownMask = (1 << ProcessorIdCacheShift) - 1; private const int ProcessorIdRefreshRate = 5000; private static int RefreshCurrentProcessorId() { int currentProcessorId = GetCurrentProcessorNumber(); // On Unix, GetCurrentProcessorNumber() is implemented in terms of sched_getcpu, which // doesn't exist on all platforms. On those it doesn't exist on, GetCurrentProcessorNumber() // returns -1. As a fallback in that case and to spread the threads across the buckets // by default, we use the current managed thread ID as a proxy. if (currentProcessorId < 0) currentProcessorId = Environment.CurrentManagedThreadId; // Add offset to make it clear that it is not guaranteed to be 0-based processor number currentProcessorId += 100; Debug.Assert(ProcessorIdRefreshRate <= ProcessorIdCacheCountDownMask); // Mask with int.MaxValue to ensure the execution Id is not negative t_currentProcessorIdCache = ((currentProcessorId << ProcessorIdCacheShift) & int.MaxValue) | ProcessorIdRefreshRate; return currentProcessorId; } // Cached processor id used as a hint for which per-core stack to access. It is periodically // refreshed to trail the actual thread core affinity. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetCurrentProcessorId() { int currentProcessorIdCache = t_currentProcessorIdCache--; if ((currentProcessorIdCache & ProcessorIdCacheCountDownMask) == 0) { return RefreshCurrentProcessorId(); } return currentProcessorIdCache >> ProcessorIdCacheShift; } internal void ResetThreadPoolThread() { // Currently implemented in unmanaged method Thread::InternalReset and // called internally from the ThreadPool in NotifyWorkItemComplete. } } // End of class Thread }
// 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.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Diagnostics.Contracts; namespace Microsoft.Win32.SafeHandles { /// <summary> /// Base class for NCrypt handles which need to support being pseudo-duplicated. This class is not for /// external use (instead applications should consume the concrete subclasses of this class). /// </summary> /// <remarks> /// Since NCrypt handles do not have a native DuplicateHandle type call, we need to do manual /// reference counting in managed code whenever we hand out an extra reference to one of these handles. /// This class wraps up the logic to correctly duplicate and free these handles to simluate a native /// duplication. /// /// Each open handle object can be thought of as being in one of three states: /// 1. Owner - created via the marshaler, traditional style safe handle. Notably, only one owner /// handle exists for a given native handle. /// 2. Duplicate - points at a handle in the Holder state. Releasing a handle in the duplicate state /// results only in decrementing the reference count of the holder, not in a release /// of the native handle. /// 3. Holder - holds onto a native handle and is referenced by handles in the duplicate state. /// When all duplicate handles are closed, the holder handle releases the native /// handle. A holder handle will never be finalized, since this results in a race /// between the finalizers of the duplicate handles and the holder handle. Instead, /// it relies upon all of the duplicate handles to be finalized and decriment the /// ref count to zero. Instances of a holder handle should never be referenced by /// anything but a duplicate handle. /// </remarks> public abstract class SafeNCryptHandle : SafeHandle { private enum OwnershipState { /// <summary> /// The safe handle owns the native handle outright. This must be value 0, as this is the /// state the marshaler will place the handle in when marshaling back a SafeHandle /// </summary> Owner = 0, /// <summary> /// The safe handle does not own the native handle, but points to a Holder which does /// </summary> Duplicate, /// <summary> /// The safe handle owns the native handle, but shares it with other Duplicate handles /// </summary> Holder } private OwnershipState m_ownershipState; /// <summary> /// If the handle is a Duplicate, this points at the safe handle which actually owns the native handle. /// </summary> private SafeNCryptHandle m_holder; protected SafeNCryptHandle() : base(IntPtr.Zero, true) { return; } /// <summary> /// Wrapper for the m_holder field which ensures that we're in a consistent state /// </summary> private SafeNCryptHandle Holder { get { Contract.Requires((m_ownershipState == OwnershipState.Duplicate && m_holder != null) || (m_ownershipState != OwnershipState.Duplicate && m_holder == null)); Contract.Requires(m_holder == null || m_holder.m_ownershipState == OwnershipState.Holder); return m_holder; } set { Contract.Ensures(m_holder.m_ownershipState == OwnershipState.Holder); Contract.Ensures(m_ownershipState == OwnershipState.Duplicate); #if DEBUG Contract.Ensures(IsValidOpenState); Contract.Assert(value.IsValidOpenState); #endif Contract.Assert(m_ownershipState != OwnershipState.Duplicate); Contract.Assert(value.m_ownershipState == OwnershipState.Holder); m_holder = value; m_ownershipState = OwnershipState.Duplicate; } } #if DEBUG /// <summary> /// Ensure the state of the handle is consistent for an open handle /// </summary> private bool IsValidOpenState { [Pure] get { switch (m_ownershipState) { // Owner handles do not have a holder case OwnershipState.Owner: return Holder == null && !IsInvalid && !IsClosed; // Duplicate handles have valid open holders with the same raw handle value case OwnershipState.Duplicate: bool acquiredHolder = false; try { IntPtr holderRawHandle = IntPtr.Zero; if (Holder != null) { Holder.DangerousAddRef(ref acquiredHolder); holderRawHandle = Holder.DangerousGetHandle(); } bool holderValid = Holder != null && !Holder.IsInvalid && !Holder.IsClosed && holderRawHandle != IntPtr.Zero && holderRawHandle == handle; return holderValid && !IsInvalid && !IsClosed; } finally { if (acquiredHolder) { Holder.DangerousRelease(); } } // Holder handles do not have a holder case OwnershipState.Holder: return Holder == null && !IsInvalid && !IsClosed; // Unknown ownership state default: return false; } } } #endif /// <summary> /// Duplicate a handle /// </summary> /// <remarks> /// #NCryptHandleDuplicationAlgorithm /// /// Duplicating a handle performs different operations depending upon the state of the handle: /// /// * Owner - Allocate two new handles, a holder and a duplicate. /// - Suppress finalization on the holder /// - Transition into the duplicate state /// - Use the new holder as the holder for both this handle and the duplicate /// - Increment the reference count on the holder /// /// * Duplicate - Allocate a duplicate handle /// - Increment the reference count of our holder /// - Assign the duplicate's holder to be our holder /// /// * Holder - Specifically disallowed. Holders should only ever be referenced by duplicates, /// so duplication will occur on the duplicate rather than the holder handle. /// </remarks> internal T Duplicate<T>() where T : SafeNCryptHandle, new() { // Spec#: Consider adding a model variable for ownership state? Contract.Ensures(Contract.Result<T>() != null); Contract.Ensures(m_ownershipState == OwnershipState.Duplicate); Contract.Ensures(Contract.Result<T>().m_ownershipState == OwnershipState.Duplicate); #if DEBUG // Spec#: Consider a debug-only? model variable for IsValidOpenState? Contract.Ensures(Contract.Result<T>().IsValidOpenState); Contract.Ensures(IsValidOpenState); Contract.Assert(IsValidOpenState); #endif Contract.Assert(m_ownershipState != OwnershipState.Holder); Contract.Assert(typeof(T) == this.GetType()); if (m_ownershipState == OwnershipState.Owner) { return DuplicateOwnerHandle<T>(); } else { // If we're not an owner handle, and we're being duplicated then we must be a duplicate handle. return DuplicateDuplicatedHandle<T>(); } } /// <summary> /// Duplicate a safe handle which is already duplicated. /// /// See code:Microsoft.Win32.SafeHandles.SafeNCryptHandle#NCryptHandleDuplicationAlgorithm for /// details about the algorithm. /// </summary> private T DuplicateDuplicatedHandle<T>() where T : SafeNCryptHandle, new() { Contract.Ensures(m_ownershipState == OwnershipState.Duplicate); Contract.Ensures(Contract.Result<T>() != null && Contract.Result<T>().m_ownershipState == OwnershipState.Duplicate); #if DEBUG Contract.Ensures(IsValidOpenState); Contract.Ensures(Contract.Result<T>().IsValidOpenState); Contract.Assert(IsValidOpenState); #endif Contract.Assert(m_ownershipState == OwnershipState.Duplicate); Contract.Assert(typeof(T) == this.GetType()); bool addedRef = false; T duplicate = new T(); // We need to do this operation in a CER, since we need to make sure that if the AddRef occurs // that the duplicated handle will always point back to the Holder, otherwise the Holder will leak // since it will never have its ref count reduced to zero. try { } finally { Holder.DangerousAddRef(ref addedRef); duplicate.SetHandle(Holder.DangerousGetHandle()); duplicate.Holder = Holder; // Transitions to OwnershipState.Duplicate } return duplicate; } /// <summary> /// Duplicate a safe handle which is currently the exclusive owner of a native handle /// /// See code:Microsoft.Win32.SafeHandles.SafeNCryptHandle#NCryptHandleDuplicationAlgorithm for /// details about the algorithm. /// </summary> private T DuplicateOwnerHandle<T>() where T : SafeNCryptHandle, new() { Contract.Ensures(m_ownershipState == OwnershipState.Duplicate); Contract.Ensures(Contract.Result<T>() != null && Contract.Result<T>().m_ownershipState == OwnershipState.Duplicate); #if DEBUG Contract.Ensures(IsValidOpenState); Contract.Ensures(Contract.Result<T>().IsValidOpenState); Contract.Assert(IsValidOpenState); #endif Contract.Assert(m_ownershipState == OwnershipState.Owner); Contract.Assert(typeof(T) == this.GetType()); bool addRef = false; T holder = new T(); T duplicate = new T(); // We need to do this operation in a CER in order to ensure that everybody's state stays consistent // with the current view of the world. If the state of the various handles gets out of sync, then // we'll end up leaking since reference counts will not be set up properly. try { } finally { // Setup a holder safe handle to ref count the native handle holder.m_ownershipState = OwnershipState.Holder; holder.SetHandle(DangerousGetHandle()); GC.SuppressFinalize(holder); // Transition into the duplicate state, referencing the holder. The initial reference count // on the holder will refer to the original handle so there is no need to AddRef here. Holder = holder; // Transitions to OwnershipState.Duplicate // The duplicate handle will also reference the holder holder.DangerousAddRef(ref addRef); duplicate.SetHandle(holder.DangerousGetHandle()); duplicate.Holder = holder; // Transitions to OwnershipState.Duplicate } return duplicate; } public override bool IsInvalid { get { return handle == IntPtr.Zero || handle == new IntPtr(-1); } } /// <summary> /// Release the handle /// </summary> /// <remarks> /// Similar to duplication, releasing a handle performs different operations based upon the state /// of the handle. /// /// * Owner - Simply call the release P/Invoke method /// * Duplicate - Decrement the reference count of the current holder /// * Holder - Call the release P/Invoke. Note that ReleaseHandle on a holder implies a reference /// count of zero. /// </remarks> protected override bool ReleaseHandle() { if (m_ownershipState == OwnershipState.Duplicate) { Holder.DangerousRelease(); return true; } else { return ReleaseNativeHandle(); } } /// <summary> /// Perform the actual release P/Invoke /// </summary> protected abstract bool ReleaseNativeHandle(); } /// <summary> /// Safe handle representing an NCRYPT_KEY_HANDLE /// </summary> public sealed class SafeNCryptKeyHandle : SafeNCryptHandle { [DllImport("ncrypt.dll")] private static extern int NCryptFreeObject(IntPtr hObject); internal SafeNCryptKeyHandle Duplicate() { return Duplicate<SafeNCryptKeyHandle>(); } protected override bool ReleaseNativeHandle() { return NCryptFreeObject(handle) == 0; } } /// <summary> /// Safe handle representing an NCRYPT_PROV_HANDLE /// </summary> public sealed class SafeNCryptProviderHandle : SafeNCryptHandle { [DllImport("ncrypt.dll")] private static extern int NCryptFreeObject(IntPtr hObject); internal SafeNCryptProviderHandle Duplicate() { return Duplicate<SafeNCryptProviderHandle>(); } internal void SetHandleValue(IntPtr newHandleValue) { Contract.Requires(newHandleValue != IntPtr.Zero); Contract.Requires(!IsClosed); Contract.Ensures(!IsInvalid); Contract.Assert(handle == IntPtr.Zero); SetHandle(newHandleValue); } protected override bool ReleaseNativeHandle() { return NCryptFreeObject(handle) == 0; } } /// <summary> /// Safe handle representing an NCRYPT_SECRET_HANDLE /// </summary> public sealed class SafeNCryptSecretHandle : SafeNCryptHandle { [DllImport("ncrypt.dll")] private static extern int NCryptFreeObject(IntPtr hObject); protected override bool ReleaseNativeHandle() { return NCryptFreeObject(handle) == 0; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Linq; using Gallio.Framework; using Gallio.Model.Commands; using Gallio.Common.Reflection; using Gallio.Runner.Reports.Schema; using Gallio.Tests; using MbUnit.Framework; namespace MbUnit.Tests.Framework { [TestFixture] [TestsOn(typeof(RowAttribute))] [TestsOn(typeof(ColumnAttribute))] [TestsOn(typeof(BindAttribute))] [TestsOn(typeof(CombinatorialJoinAttribute))] [TestsOn(typeof(SequentialJoinAttribute))] [TestsOn(typeof(PairwiseJoinAttribute))] [RunSample(typeof(TypeParameterBindingInsideSample<>))] [RunSample(typeof(TypeParameterBindingOutsideSample<>))] [RunSample(typeof(ConstructorParameterBindingInsideSample))] [RunSample(typeof(ConstructorParameterBindingOutsideSample))] [RunSample(typeof(TypeParameterAndConstructorParameterBindingOutsideSample<>))] [RunSample(typeof(FieldBindingSample))] [RunSample(typeof(PropertyBindingSample))] [RunSample(typeof(MethodParameterBindingInsideSample))] [RunSample(typeof(MethodParameterBindingOutsideSample))] [RunSample(typeof(MethodParameterBindingOutsideSampleInherited))] [RunSample(typeof(ExplicitBindingByNameSample<>))] [RunSample(typeof(ExplicitBindingByIndexSample<>))] [RunSample(typeof(ImplicitBindingByNameSample<>))] [RunSample(typeof(ImplicitBindingByIndexOnClassSample<,>))] [RunSample(typeof(ImplicitBindingByIndexOnMethodSample))] [RunSample(typeof(CombinatorialBindingOfClassAndMethodWithOrderingSample<>))] [RunSample(typeof(CombinatorialBindingOfMethodWithMultipleDataSourcesAndOrderingSample))] [RunSample(typeof(CombinatorialJoinStrategySample))] [RunSample(typeof(SequentialJoinStrategySample))] [RunSample(typeof(PairwiseJoinStrategySample))] [RunSample(typeof(ConcreteFixtureSample))] public class DataBindingTest : BaseTestWithSampleRunner { [Test] [Row(typeof(TypeParameterBindingInsideSample<>), "Test", new[] { "System.Int32" })] [Row(typeof(TypeParameterBindingOutsideSample<>), "Test", new[] { "System.String" })] [Row(typeof(ConstructorParameterBindingInsideSample), "Test", new[] { "(Apples, 1)" })] [Row(typeof(ConstructorParameterBindingOutsideSample), "Test", new[] { "(Apples, 1)" })] [Row(typeof(TypeParameterAndConstructorParameterBindingOutsideSample<>), "Test", new[] { "System.String -> (Apples, 1)" })] [Row(typeof(FieldBindingSample), "Test", new[] { "(Apples, 1)" })] [Row(typeof(PropertyBindingSample), "Test", new[] { "(Apples, 1)" })] [Row(typeof(MethodParameterBindingInsideSample), "Test", new[] { "(Apples, 1)" })] [Row(typeof(MethodParameterBindingOutsideSample), "Test", new[] { "(Apples, 1)" })] [Row(typeof(MethodParameterBindingOutsideSampleInherited), "Test", new[] { "(Apples, 1)", "(Oranges, 2)" }, Description = "Should inherit rows.")] [Row(typeof(ExplicitBindingByNameSample<>), "Test", new[] { "System.String -> (Apples, 1) x 10, Empire" })] [Row(typeof(ExplicitBindingByIndexSample<>), "Test", new[] { "System.String -> (Apples, 1) x 10, Empire" })] [Row(typeof(ImplicitBindingByNameSample<>), "Test", new[] { "System.String -> (Apples, 1) x 10, Empire" })] [Row(typeof(ImplicitBindingByIndexOnClassSample<,>), "Test", new[] { "System.String, System.Decimal -> (Apples, 1)" })] [Row(typeof(ImplicitBindingByIndexOnMethodSample), "Test", new[] { "System.String, System.Decimal -> (Apples, 1)" })] [Row(typeof(CombinatorialBindingOfClassAndMethodWithOrderingSample<>), "Test", new[] { "System.String, System.Int32 -> (abc, 456)", "System.String, System.String -> (abc, def)", "System.Int32, System.Int32 -> (123, 456)", "System.Int32, System.String -> (123, def)" })] [Row(typeof(CombinatorialBindingOfMethodWithMultipleDataSourcesAndOrderingSample), "Test", new[] { "System.String, System.Int32 -> (abc, 456)", "System.String, System.String -> (abc, def)", "System.Int32, System.Int32 -> (123, 456)", "System.Int32, System.String -> (123, def)" })] [Row(typeof(CombinatorialJoinStrategySample), "Test", new[] { "000", "001", "010", "011", "100", "101", "110", "111" })] [Row(typeof(SequentialJoinStrategySample), "Test", new[] { "000", "111" })] [Row(typeof(PairwiseJoinStrategySample), "Test", new[] { "111", "100", "010", "001" })] [Row(typeof(ConcreteFixtureSample), "BaseTest", new[] { "i = 123, s = ABC" })] [Row(typeof(ConcreteFixtureSample), "ConcreteTest", new[] { "i = 123, s = ABC" })] public void VerifySampleOutput(Type fixtureType, string sampleName, string[] output) { IList<TestStepRun> runs = Runner .GetTestCaseRunsWithin(CodeReference.CreateFromType(fixtureType)) .Where(run => run.Step.Name.StartsWith(sampleName)) .ToList(); Assert.Count(output.Length, runs, "Different number of runs than expected."); for (int i = 0; i < output.Length; i++) AssertLogContains(runs[i], output[i]); } [TestFixture, Explicit("Sample")] internal class TypeParameterBindingInsideSample<[Column(typeof(int))] T> { [Test] public void Test() { TestLog.WriteLine(typeof(T)); } } [TestFixture, Explicit("Sample")] [Row(typeof(string))] internal class TypeParameterBindingOutsideSample<T> { [Test] public void Test() { TestLog.WriteLine(typeof(T)); } } [TestFixture, Explicit("Sample")] internal class ConstructorParameterBindingInsideSample { private readonly string item; private readonly decimal price; public ConstructorParameterBindingInsideSample([Column("Apples")] string item, [Column(1)] decimal price) { this.item = item; this.price = price; } [Test] public void Test() { TestLog.WriteLine("({0}, {1})", item, price); } } [TestFixture, Explicit("Sample")] [Row("Apples", 1)] internal class ConstructorParameterBindingOutsideSample { private readonly string item; private readonly decimal price; public ConstructorParameterBindingOutsideSample(string item, decimal price) { this.item = item; this.price = price; } [Test] public void Test() { TestLog.WriteLine("({0}, {1})", item, price); } } [TestFixture, Explicit("Sample")] [Row(typeof(string), "Apples", 1)] internal class TypeParameterAndConstructorParameterBindingOutsideSample<T> { private readonly T item; private readonly decimal price; public TypeParameterAndConstructorParameterBindingOutsideSample(T item, decimal price) { this.item = item; this.price = price; } [Test] public void Test() { TestLog.WriteLine("{0} -> ({1}, {2})", typeof(T), item, price); } } [TestFixture, Explicit("Sample")] internal class FieldBindingSample { [Column("Apples")] public string Item = null; [Column(1)] public decimal Price = 0.0m; [Test] public void Test() { TestLog.WriteLine("({0}, {1})", Item, Price); } } [TestFixture, Explicit("Sample")] internal class PropertyBindingSample { private string item; private decimal price; [Column("Apples")] public string Item { set { item = value; } } [Column(1)] public decimal Price { get { return price; } set { price = value; } } [Test] public void Test() { TestLog.WriteLine("({0}, {1})", item, price); } } [TestFixture, Explicit("Sample")] internal class MethodParameterBindingInsideSample { [Test] public void Test([Column("Apples")] string item, [Column(1)] decimal price) { TestLog.WriteLine("({0}, {1})", item, price); } } [TestFixture, Explicit("Sample")] internal class MethodParameterBindingOutsideSample { [Test] [Row("Apples", 1)] public virtual void Test(string item, decimal price) { TestLog.WriteLine("({0}, {1})", item, price); } } [TestFixture, Explicit("Sample")] internal class MethodParameterBindingOutsideSampleInherited : MethodParameterBindingOutsideSample { [Row("Oranges", 2)] public override void Test(string item, decimal price) { base.Test(item, price); } } [TestFixture, Explicit("Sample")] [Header("Type", "Item", "Price", "Quantity", "Variety", SourceName = "Data")] [Row(typeof(string), "Apples", 1, 10, "Empire", SourceName = "Data")] internal class ExplicitBindingByNameSample<[Bind("Type", Source = "Data")] T> { private readonly T item; private decimal price; public ExplicitBindingByNameSample([Bind("Item", Source = "Data")] T item) { this.item = item; } [Bind("Price", Source = "Data")] public decimal Price { set { price = value; } } [Bind("Quantity", Source = "Data")] public int Quantity = 0; [Test] public void Test([Bind("Variety", Source = "Data")] string variety) { TestLog.WriteLine("{0} -> ({1}, {2}) x {3}, {4}", typeof(T), item, price, Quantity, variety); } } [TestFixture, Explicit("Sample")] [Row(typeof(string), "Apples", 1, 10, "Empire")] internal class ExplicitBindingByIndexSample<[Bind(0)] T> { private readonly T item; private decimal price; public ExplicitBindingByIndexSample([Bind(1)] T item) { this.item = item; } [Bind(2)] public decimal Price { set { price = value; } } [Bind(3)] public int Quantity = 0; [Test] public void Test([Bind(4)] string variety) { TestLog.WriteLine("{0} -> ({1}, {2}) x {3}, {4}", typeof(T), item, price, Quantity, variety); } } [TestFixture, Explicit("Sample")] [Header("Type", "Item", "Price", "Quantity", "Variety")] [Row(typeof(string), "Apples", 1, 10, "Empire")] internal class ImplicitBindingByNameSample<[Name("Type")] T> { private readonly T item; private decimal price; public ImplicitBindingByNameSample(T item) { this.item = item; } [Bind("Price")] public decimal Price { set { price = value; } } [Bind("Quantity")] public int Quantity = 0; [Test] public void Test(string variety) { TestLog.WriteLine("{0} -> ({1}, {2}) x {3}, {4}", typeof(T), item, price, Quantity, variety); } } [TestFixture, Explicit("Sample")] [Row(typeof(string), typeof(decimal), "Apples", 1)] internal class ImplicitBindingByIndexOnClassSample<T, P> { private readonly T item; private readonly P price; public ImplicitBindingByIndexOnClassSample(T item, P price) { this.item = item; this.price = price; } [Test] public void Test() { TestLog.WriteLine("{0}, {1} -> ({2}, {3})", typeof(T), typeof(P), item, price); } } [TestFixture, Explicit("Sample")] internal class ImplicitBindingByIndexOnMethodSample { [Test] [Row(typeof(string), typeof(decimal), "Apples", 1)] public void Test<T, P>(T item, P price) { TestLog.WriteLine("{0}, {1} -> ({2}, {3})", typeof(T), typeof(P), item, price); } } [TestFixture, Explicit("Sample")] [Row(typeof(string), "abc", Order = 1)] [Row(typeof(int), 123, Order = 2)] internal class CombinatorialBindingOfClassAndMethodWithOrderingSample<TOuter> { private readonly TOuter outerValue; public CombinatorialBindingOfClassAndMethodWithOrderingSample(TOuter outerValue) { this.outerValue = outerValue; } [Test] [Row(typeof(string), "def", Order = 2)] [Row(typeof(int), 456, Order = 1)] public void Test<TInner>(TInner innerValue) { TestLog.WriteLine("{0}, {1} -> ({2}, {3})", typeof(TOuter), typeof(TInner), outerValue, innerValue); } } [TestFixture, Explicit("Sample")] internal class CombinatorialBindingOfMethodWithMultipleDataSourcesAndOrderingSample { [Test] [Row(typeof(string), "abc", SourceName = "A", Order = 1)] [Row(typeof(int), 123, SourceName = "A", Order = 2)] [Row(typeof(string), "def", SourceName = "B", Order = 2)] [Row(typeof(int), 456, SourceName = "B", Order = 1)] public void Test<[Bind(0, Source = "A")] TA, [Bind(0, Source = "B")] TB>( [Bind(1, Source = "A")] TA outerValue, [Bind(1, Source = "B")] TB innerValue) { TestLog.WriteLine("{0}, {1} -> ({2}, {3})", typeof(TA), typeof(TB), outerValue, innerValue); } } [TestFixture, Explicit("Sample")] internal class CombinatorialJoinStrategySample { [Test, CombinatorialJoin] public void Test([Column(0, 1)] int a, [Column(0, 1)] int b, [Column(0, 1)] int c) { TestLog.WriteLine("{0}{1}{2}", a, b, c); } } [TestFixture, Explicit("Sample")] internal class SequentialJoinStrategySample { [Test, SequentialJoin] public void Test([Column(0, 1)] int a, [Column(0, 1)] int b, [Column(0, 1)] int c) { TestLog.WriteLine("{0}{1}{2}", a, b, c); } } [TestFixture, Explicit("Sample")] internal class PairwiseJoinStrategySample { [Test, PairwiseJoin] public void Test([Column(0, 1)] int a, [Column(0, 1)] int b, [Column(0, 1)] int c) { TestLog.WriteLine("{0}{1}{2}", a, b, c); } } [TestFixture, Disable] internal abstract class AbstractFixtureSample { [Bind(0, Source = "DataSource1")] public int i = 0; [Test] public void BaseTest([Bind(0, Source = "DataSource2")] string s) { TestLog.WriteLine("i = {0}, s = {1}", i, s); } } [TestFixture, Explicit("Sample")] [Column(123, SourceName = "DataSource1")] [Column("ABC", SourceName = "DataSource2")] internal class ConcreteFixtureSample : AbstractFixtureSample { [Test] public void ConcreteTest([Bind(0, Source = "DataSource2")] string s) { TestLog.WriteLine("i = {0}, s = {1}", i, s); } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Globalization; using System.Management.Automation; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.Common.Models; using Microsoft.WindowsAzure.Commands.SqlDatabase.Properties; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Common; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server; using Microsoft.WindowsAzure.Commands.Utilities.Common; namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet { /// <summary> /// Update settings for an existing Microsoft Azure SQL Database in the given server context. /// </summary> [Cmdlet(VerbsCommon.Set, "AzureSqlDatabase", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] public class SetAzureSqlDatabase : AzurePSCmdlet { #region Parameter sets /// <summary> /// Parameter set name for updating by name with a connection context /// </summary> internal const string ByNameWithConnectionContext = "ByNameWithConnectionContext"; /// <summary> /// Parameter set name for updating by name using azure subscription /// </summary> internal const string ByNameWithServerName = "ByNameWithServerName"; /// <summary> /// Parameter set name for updating by input object with a connection context /// </summary> internal const string ByObjectWithConnectionContext = "ByObjectWithConnectionContext"; /// <summary> /// Parameter set name for updating by input object with a azure subscription /// </summary> internal const string ByObjectWithServerName = "ByObjectWithServerName"; #endregion #region Parameters /// <summary> /// Gets or sets the server connection context. /// </summary> [Alias("Context")] [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByNameWithConnectionContext, HelpMessage = "The connection context to the specified server.")] [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByObjectWithConnectionContext, HelpMessage = "The connection context to the specified server.")] [ValidateNotNull] public IServerDataServiceContext ConnectionContext { get; set; } /// <summary> /// Gets or sets the name of the server to connect to /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByNameWithServerName, HelpMessage = "The name of the server to connect to")] [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByObjectWithServerName, HelpMessage = "The name of the server to connect to")] [ValidateNotNullOrEmpty] public string ServerName { get; set; } /// <summary> /// Gets or sets the database. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByObjectWithConnectionContext, ValueFromPipeline = true)] [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByObjectWithServerName, ValueFromPipeline = true)] [ValidateNotNull] public Services.Server.Database Database { get; set; } /// <summary> /// Gets or sets the database name. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByNameWithConnectionContext)] [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByNameWithServerName)] [ValidateNotNullOrEmpty] public string DatabaseName { get; set; } /// <summary> /// Gets or sets the new name for the database. /// </summary> [Alias("NewName")] [Parameter(Mandatory = false, HelpMessage = "The new name for the database.")] [ValidateNotNullOrEmpty] public string NewDatabaseName { get; set; } /// <summary> /// Gets or sets the new Edition value for the database. /// </summary> [Parameter(Mandatory = false, HelpMessage = "The new edition for the database.")] public DatabaseEdition Edition { get; set; } /// <summary> /// Gets or sets the new maximum size for the database in GB. /// </summary> [Parameter(Mandatory = false, HelpMessage = "The new maximum size for the database in GB." + "This is not to be used in conjunction with MaxSizeBytes.")] public int MaxSizeGB { get; set; } /// <summary> /// Gets or sets the new maximum size for the database in bytes. /// </summary> [Parameter(Mandatory = false, HelpMessage = "The new maximum size for the database in Bytes." + "This is not to be used in conjunction with MaxSizeGB.")] public long MaxSizeBytes { get; set; } /// <summary> /// Gets or sets the new ServiceObjective for this database. /// </summary> [Parameter(Mandatory = false, HelpMessage = "The new ServiceObjective for the database.")] [ValidateNotNull] public ServiceObjective ServiceObjective { get; set; } /// <summary> /// Gets or sets the switch to output the target object to the pipeline. /// </summary> [Parameter(HelpMessage = "Pass through the input object to the output pipeline")] public SwitchParameter PassThru { get; set; } /// <summary> /// Gets or sets the switch to not confirm on the altering of the database. /// </summary> [Parameter(HelpMessage = "Do not confirm on the altering of the database")] public SwitchParameter Force { get; set; } /// <summary> /// Gets or sets the switch to wait for the operation to complete on the server before returning /// </summary> [Parameter(HelpMessage = "Wait for the update operation to complete (synchronously)")] public SwitchParameter Sync { get; set; } #endregion /// <summary> /// Process the command. /// </summary> public override void ExecuteCmdlet() { // Obtain the database name from the given parameters. string databaseName = null; if (this.MyInvocation.BoundParameters.ContainsKey("Database")) { databaseName = this.Database.Name; } else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName")) { databaseName = this.DatabaseName; } // Obtain the name of the server string serverName = null; if (this.MyInvocation.BoundParameters.ContainsKey("ServerName")) { serverName = this.ServerName; } else { serverName = this.ConnectionContext.ServerName; } // Determine the max size of the db int? maxSizeGb = null; if (this.MyInvocation.BoundParameters.ContainsKey("MaxSizeGB")) { maxSizeGb = this.MaxSizeGB; } long? maxSizeBytes = null; if (this.MyInvocation.BoundParameters.ContainsKey("MaxSizeBytes")) { maxSizeBytes = this.MaxSizeBytes; } // Determine the edition for the db DatabaseEdition? edition = null; if (this.MyInvocation.BoundParameters.ContainsKey("Edition")) { edition = this.Edition; } string actionDescription = string.Format( CultureInfo.InvariantCulture, Resources.SetAzureSqlDatabaseDescription, serverName, databaseName); string actionWarning = string.Format( CultureInfo.InvariantCulture, Resources.SetAzureSqlDatabaseWarning, serverName, databaseName); this.WriteVerbose(actionDescription); // Do nothing if force is not specified and user cancelled the operation if (!this.Force.IsPresent && !this.ShouldProcess(actionDescription, actionWarning, Resources.ShouldProcessCaption)) { return; } // If service objective is specified, ask the user to confirm the change if (!this.Force.IsPresent && this.ServiceObjective != null) { string serviceObjectiveWarning = string.Format( CultureInfo.InvariantCulture, Resources.SetAzureSqlDatabaseServiceObjectiveWarning, serverName, databaseName); if (!this.ShouldContinue( serviceObjectiveWarning, Resources.ShouldProcessCaption)) { return; } } switch (this.ParameterSetName) { case ByNameWithConnectionContext: case ByObjectWithConnectionContext: this.ProcessWithConnectionContext(databaseName, maxSizeGb, maxSizeBytes, edition); break; case ByNameWithServerName: case ByObjectWithServerName: this.ProcessWithServerName(databaseName, maxSizeGb, maxSizeBytes, edition); break; } } /// <summary> /// Process the request using a temporary connection context using certificate authentication /// </summary> /// <param name="databaseName">The name of the database to update</param> /// <param name="maxSizeGb">the new size for the database or null</param> /// <param name="maxSizeBytes"></param> /// <param name="edition">the new edition for the database or null</param> private void ProcessWithServerName(string databaseName, int? maxSizeGb, long? maxSizeBytes, DatabaseEdition? edition) { Func<string> GetClientRequestId = () => string.Empty; try { // Get the current subscription data. AzureSubscription subscription = AzureSession.CurrentContext.Subscription; // Create a temporary context ServerDataServiceCertAuth context = ServerDataServiceCertAuth.Create(this.ServerName, subscription); GetClientRequestId = () => context.ClientRequestId; // Remove the database with the specified name Services.Server.Database database = context.UpdateDatabase( databaseName, this.NewDatabaseName, maxSizeGb, maxSizeBytes, edition, this.ServiceObjective); if (this.Sync.IsPresent) { // Wait for the operation to complete on the server. database = CmdletCommon.WaitForDatabaseOperation(this, context, database, this.DatabaseName, false); } // Update the passed in database object if (this.MyInvocation.BoundParameters.ContainsKey("Database")) { this.Database.CopyFields(database); database = this.Database; } // If PassThru was specified, write back the updated object to the pipeline if (this.PassThru.IsPresent) { this.WriteObject(database); } } catch (Exception ex) { SqlDatabaseExceptionHandler.WriteErrorDetails( this, GetClientRequestId(), ex); } } /// <summary> /// process the request using the connection context. /// </summary> /// <param name="databaseName">the name of the database to alter</param> /// <param name="maxSizeGb">the new maximum size for the database</param> /// <param name="maxSizeBytes"></param> /// <param name="edition">the new edition for the database</param> private void ProcessWithConnectionContext(string databaseName, int? maxSizeGb, long? maxSizeBytes, DatabaseEdition? edition) { try { // Update the database with the specified name Services.Server.Database database = this.ConnectionContext.UpdateDatabase( databaseName, this.NewDatabaseName, maxSizeGb, maxSizeBytes, edition, this.ServiceObjective); if (this.Sync.IsPresent) { // Wait for the operation to complete on the server. database = CmdletCommon.WaitForDatabaseOperation(this, this.ConnectionContext, database, this.DatabaseName, false); } // If PassThru was specified, write back the updated object to the pipeline if (this.PassThru.IsPresent) { this.WriteObject(database); } if (this.ConnectionContext.GetType() == typeof(ServerDataServiceCertAuth)) { if (this.MyInvocation.BoundParameters.ContainsKey("Database")) { this.Database.CopyFields(database); } } } catch (Exception ex) { SqlDatabaseExceptionHandler.WriteErrorDetails( this, this.ConnectionContext.ClientRequestId, ex); } } } }
// // PhotoVersionCommands.cs // // Author: // Anton Keks <[email protected]> // Ettore Perazzoli <[email protected]> // Ruben Vermeersch <[email protected]> // // Copyright (C) 2003-2010 Novell, Inc. // Copyright (C) 2009-2010 Anton Keks // Copyright (C) 2003 Ettore Perazzoli // Copyright (C) 2010 Ruben Vermeersch // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Gtk; using System; using Mono.Unix; using FSpot; using Hyena; using Hyena.Widgets; using FSpot.UI.Dialog; public class PhotoVersionCommands { private class VersionNameRequest : BuilderDialog { private Photo photo; [GtkBeans.Builder.Object] private Button ok_button; [GtkBeans.Builder.Object] private Entry version_name_entry; [GtkBeans.Builder.Object] private Label prompt_label; [GtkBeans.Builder.Object] private Label already_in_use_label; public enum RequestType { Create, Rename } private RequestType request_type; private void Update () { string new_name = version_name_entry.Text; if (photo.VersionNameExists (new_name) && ! (request_type == RequestType.Rename && new_name == photo.GetVersion (photo.DefaultVersionId).Name)) { already_in_use_label.Markup = "<small>This name is already in use</small>"; ok_button.Sensitive = false; return; } already_in_use_label.Text = String.Empty; if (new_name.Length == 0) ok_button.Sensitive = false; else ok_button.Sensitive = true; } private void HandleVersionNameEntryChanged (object obj, EventArgs args) { Update (); } public VersionNameRequest (RequestType request_type, Photo photo, Gtk.Window parent_window) : base ("version_name_dialog.ui", "version_name_dialog") { this.request_type = request_type; this.photo = photo; switch (request_type) { case RequestType.Create: this.Title = Catalog.GetString ("Create New Version"); prompt_label.Text = Catalog.GetString ("Name:"); break; case RequestType.Rename: this.Title = Catalog.GetString ("Rename Version"); prompt_label.Text = Catalog.GetString ("New name:"); version_name_entry.Text = photo.GetVersion (photo.DefaultVersionId).Name; version_name_entry.SelectRegion (0, -1); break; } version_name_entry.Changed += HandleVersionNameEntryChanged; version_name_entry.ActivatesDefault = true; this.TransientFor = parent_window; this.DefaultResponse = ResponseType.Ok; Update (); } public ResponseType Run (out string name) { ResponseType response = (ResponseType) this.Run (); name = version_name_entry.Text; if (request_type == RequestType.Rename && name == photo.GetVersion (photo.DefaultVersionId).Name) response = ResponseType.Cancel; this.Destroy (); return response; } } // Creating a new version. public class Create { public bool Execute (PhotoStore store, Photo photo, Gtk.Window parent_window) { VersionNameRequest request = new VersionNameRequest (VersionNameRequest.RequestType.Create, photo, parent_window); string name; ResponseType response = request.Run (out name); if (response != ResponseType.Ok) return false; try { photo.DefaultVersionId = photo.CreateVersion (name, photo.DefaultVersionId, true); store.Commit (photo); return true; } catch (Exception e) { HandleException ("Could not create a new version", e, parent_window); return false; } } } // Deleting a version. public class Delete { public bool Execute (PhotoStore store, Photo photo, Gtk.Window parent_window) { string ok_caption = Catalog.GetString ("Delete"); string msg = String.Format (Catalog.GetString ("Really delete version \"{0}\"?"), photo.DefaultVersion.Name); string desc = Catalog.GetString ("This removes the version and deletes the corresponding file from disk."); try { if (ResponseType.Ok == HigMessageDialog.RunHigConfirmation(parent_window, DialogFlags.DestroyWithParent, MessageType.Warning, msg, desc, ok_caption)) { photo.DeleteVersion (photo.DefaultVersionId); store.Commit (photo); return true; } } catch (Exception e) { HandleException ("Could not delete a version", e, parent_window); } return false; } } // Renaming a version. public class Rename { public bool Execute (PhotoStore store, Photo photo, Gtk.Window parent_window) { VersionNameRequest request = new VersionNameRequest (VersionNameRequest.RequestType.Rename, photo, parent_window); string new_name; ResponseType response = request.Run (out new_name); if (response != ResponseType.Ok) return false; try { photo.RenameVersion (photo.DefaultVersionId, new_name); store.Commit (photo); return true; } catch (Exception e) { HandleException ("Could not rename a version", e, parent_window); return false; } } } // Detaching a version (making it a separate photo). public class Detach { public bool Execute (PhotoStore store, Photo photo, Gtk.Window parent_window) { string ok_caption = Catalog.GetString ("De_tach"); string msg = String.Format (Catalog.GetString ("Really detach version \"{0}\" from \"{1}\"?"), photo.DefaultVersion.Name, photo.Name.Replace("_", "__")); string desc = Catalog.GetString ("This makes the version appear as a separate photo in the library. To undo, drag the new photo back to its parent."); try { if (ResponseType.Ok == HigMessageDialog.RunHigConfirmation(parent_window, DialogFlags.DestroyWithParent, MessageType.Warning, msg, desc, ok_caption)) { Photo new_photo = store.CreateFrom (photo, photo.RollId); new_photo.CopyAttributesFrom (photo); photo.DeleteVersion (photo.DefaultVersionId, false, true); store.Commit (new Photo[] {new_photo, photo}); return true; } } catch (Exception e) { HandleException ("Could not detach a version", e, parent_window); } return false; } } // Reparenting a photo as version of another one public class Reparent { public bool Execute (PhotoStore store, Photo [] photos, Photo new_parent, Gtk.Window parent_window) { string ok_caption = Catalog.GetString ("Re_parent"); string msg = String.Format (Catalog.GetPluralString ("Really reparent \"{0}\" as version of \"{1}\"?", "Really reparent {2} photos as versions of \"{1}\"?", photos.Length), new_parent.Name.Replace ("_", "__"), photos[0].Name.Replace ("_", "__"), photos.Length); string desc = Catalog.GetString ("This makes the photos appear as a single one in the library. The versions can be detached using the Photo menu."); try { if (ResponseType.Ok == HigMessageDialog.RunHigConfirmation(parent_window, DialogFlags.DestroyWithParent, MessageType.Warning, msg, desc, ok_caption)) { uint highest_rating = new_parent.Rating; string new_description = new_parent.Description; foreach (Photo photo in photos) { highest_rating = Math.Max(photo.Rating, highest_rating); if (string.IsNullOrEmpty(new_description)) new_description = photo.Description; new_parent.AddTag (photo.Tags); foreach (uint version_id in photo.VersionIds) { new_parent.DefaultVersionId = new_parent.CreateReparentedVersion (photo.GetVersion (version_id) as PhotoVersion); store.Commit (new_parent); } uint [] version_ids = photo.VersionIds; Array.Reverse (version_ids); foreach (uint version_id in version_ids) { photo.DeleteVersion (version_id, true, true); } store.Remove (photo); } new_parent.Rating = highest_rating; new_parent.Description = new_description; store.Commit (new_parent); return true; } } catch (Exception e) { HandleException ("Could not reparent photos", e, parent_window); } return false; } } private static void HandleException (string msg, Exception e, Gtk.Window parent_window) { Log.DebugException (e); msg = Catalog.GetString (msg); string desc = String.Format (Catalog.GetString ("Received exception \"{0}\"."), e.Message); HigMessageDialog md = new HigMessageDialog (parent_window, DialogFlags.DestroyWithParent, Gtk.MessageType.Error, ButtonsType.Ok, msg, desc); md.Run (); md.Destroy (); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.DataContracts.ManagedReference; public class ResolveReference : IResolverPipeline { public void Run(MetadataModel yaml, ResolverContext context) { TreeIterator.Preorder(yaml.TocYamlViewModel, null, s => s.IsInvalid ? null : s.Items, (current, parent) => { MetadataItem page; var addingReferences = new List<ReferenceItem>(); var documentReferences = current.References; if (current.Type.IsPageLevel()) { page = current; current.References = new Dictionary<string, ReferenceItem>(); } else { page = parent; current.References = null; } if (documentReferences != null && documentReferences.Count > 0) { foreach (var key in documentReferences.Keys) { TryAddReference(context, page, addingReferences, key); } } foreach (var key in GetReferenceKeys(current)) { TryAddReference(context, page, addingReferences, key); } if (current.Type == MemberType.Namespace) { foreach (var item in current.Items) { TryAddReference(context, page, addingReferences, item.Name); } } AddIndirectReference(context, page, addingReferences); return true; }); } private static void TryAddReference(ResolverContext context, MetadataItem page, List<ReferenceItem> addingReferences, string key) { if (!page.References.ContainsKey(key)) { if (context.References.TryGetValue(key, out ReferenceItem item)) { var reference = context.References[key].Clone(); page.References.Add(key, reference); addingReferences.Add(reference); } else { Debug.Fail(string.Format("Reference not found: {0}", key)); } } } private void AddIndirectReference(ResolverContext context, MetadataItem page, List<ReferenceItem> addedReferences) { while (addedReferences.Count > 0) { var addingReferences = new List<ReferenceItem>(); foreach (var r in addedReferences) { foreach (var key in GetReferenceKeys(r)) { TryAddReference(context, page, addingReferences, key); } } addedReferences = addingReferences; } } private IEnumerable<string> GetReferenceKeys(MetadataItem current) { if (current.NamespaceName != null) { yield return current.NamespaceName; } if (current.Overridden != null) { yield return current.Overridden; } if (current.Overload != null) { yield return current.Overload; } if (current.Inheritance?.Count > 0) { foreach (var item in current.Inheritance) { yield return item; } } if (current.Implements?.Count > 0) { foreach (var item in current.Implements) { yield return item; } } if (current.DerivedClasses?.Count > 0) { foreach (var item in current.DerivedClasses) { yield return item; } } if (current.InheritedMembers?.Count > 0) { foreach (var item in current.InheritedMembers) { yield return item; } } if (current.ExtensionMethods?.Count > 0) { foreach (var item in current.ExtensionMethods) { yield return item; } } if (current.Exceptions?.Count > 0) { foreach (var item in current.Exceptions) { yield return item.Type; } } if (current.Sees?.Count > 0) { foreach (var item in current.Sees.Where(l => l.LinkType == LinkType.CRef)) { yield return item.LinkId; } } if (current.SeeAlsos?.Count > 0) { foreach (var item in current.SeeAlsos.Where(l => l.LinkType == LinkType.CRef)) { yield return item.LinkId; } } if (current.Syntax != null) { if (current.Syntax.Parameters?.Count > 0) { foreach (var item in current.Syntax.Parameters) { yield return item.Type; } } if (current.Syntax.Return != null) { yield return current.Syntax.Return.Type; } } } private IEnumerable<string> GetReferenceKeys(ReferenceItem reference) { if (reference.Definition != null) { yield return reference.Definition; } if (reference.Parent != null) { yield return reference.Parent; } } } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.ComponentModel; using OpenSource.UPnP; namespace UPnPAuthor { /// <summary> /// Summary description for FieldForm. /// </summary> public class FieldForm : System.Windows.Forms.Form { public UPnPComplexType.ContentData NewContentItem; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox NameTextBox; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.ComboBox TypeComboBox; private System.Windows.Forms.Button OKButton; private UPnPComplexType[] ComplexTypeList; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox MinOccursTextBox; private System.Windows.Forms.TextBox MaxOccursTextBox; private System.Windows.Forms.RadioButton MaxOccursRadio1; private System.Windows.Forms.RadioButton MaxOccursRadio2; private System.Windows.Forms.Button CancelButton; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.RadioButton ElementRadioButton; private System.Windows.Forms.RadioButton AttributeRadioButton; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public FieldForm(UPnPComplexType[] ComplexTypes, UPnPComplexType.ContentData cd) { // // Required for Windows Form Designer support // InitializeComponent(); ComplexTypeList = ComplexTypes; foreach(UPnPComplexType ct in ComplexTypes) { TypeComboBox.Items.Add(ct); } if(cd==null) { TypeComboBox.SelectedIndex=11; } else { if(cd.GetType() == typeof(UPnPComplexType.Element)) { ElementRadioButton.Checked = true; } else { AttributeRadioButton.Checked = true; } this.NameTextBox.Text = cd.Name; this.MinOccursTextBox.Text = cd.MinOccurs; if(cd.MaxOccurs == "UNBOUNDED") { this.MaxOccursRadio2.Checked = true; } else { this.MaxOccursRadio2.Checked = false; this.MaxOccursTextBox.Text = cd.MaxOccurs; } bool ok=false; foreach(UPnPComplexType ct in ComplexTypes) { if(ct.Name_LOCAL == cd.Type && ct.Name_NAMESPACE==cd.TypeNS) { ok=true; TypeComboBox.SelectedItem = ct; break; } } if(!ok) { TypeComboBox.SelectedItem = cd.Type; } } // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.NameTextBox = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.TypeComboBox = new System.Windows.Forms.ComboBox(); this.OKButton = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.MinOccursTextBox = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.MaxOccursRadio2 = new System.Windows.Forms.RadioButton(); this.MaxOccursRadio1 = new System.Windows.Forms.RadioButton(); this.MaxOccursTextBox = new System.Windows.Forms.TextBox(); this.CancelButton = new System.Windows.Forms.Button(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.AttributeRadioButton = new System.Windows.Forms.RadioButton(); this.ElementRadioButton = new System.Windows.Forms.RadioButton(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(16, 16); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(72, 20); this.textBox1.TabIndex = 0; this.textBox1.TabStop = false; this.textBox1.Text = "Name"; // // NameTextBox // this.NameTextBox.Location = new System.Drawing.Point(88, 16); this.NameTextBox.Name = "NameTextBox"; this.NameTextBox.Size = new System.Drawing.Size(312, 20); this.NameTextBox.TabIndex = 1; this.NameTextBox.Text = ""; this.NameTextBox.TextChanged += new System.EventHandler(this.OnTextChanged); // // textBox3 // this.textBox3.Location = new System.Drawing.Point(16, 40); this.textBox3.Name = "textBox3"; this.textBox3.ReadOnly = true; this.textBox3.Size = new System.Drawing.Size(72, 20); this.textBox3.TabIndex = 2; this.textBox3.TabStop = false; this.textBox3.Text = "Type"; // // TypeComboBox // this.TypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.TypeComboBox.Items.AddRange(new object[] { "UI1", "UI2", "UI4", "I1", "I2", "I4", "int", "R4", "R8", "float", "char", "string", "date", "dateTime", "dateTime.tz", "time", "time.tz", "boolean", "bin.base64", "bin.hex", "uri", "uuid"}); this.TypeComboBox.Location = new System.Drawing.Point(88, 40); this.TypeComboBox.Name = "TypeComboBox"; this.TypeComboBox.Size = new System.Drawing.Size(312, 21); this.TypeComboBox.TabIndex = 3; // // OKButton // this.OKButton.Enabled = false; this.OKButton.Location = new System.Drawing.Point(328, 152); this.OKButton.Name = "OKButton"; this.OKButton.TabIndex = 4; this.OKButton.Text = "OK"; this.OKButton.Click += new System.EventHandler(this.OKButton_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.MinOccursTextBox); this.groupBox1.Location = new System.Drawing.Point(8, 80); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(88, 64); this.groupBox1.TabIndex = 5; this.groupBox1.TabStop = false; this.groupBox1.Text = "MinOccurs"; // // MinOccursTextBox // this.MinOccursTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.MinOccursTextBox.Location = new System.Drawing.Point(16, 24); this.MinOccursTextBox.MaxLength = 5; this.MinOccursTextBox.Name = "MinOccursTextBox"; this.MinOccursTextBox.Size = new System.Drawing.Size(48, 22); this.MinOccursTextBox.TabIndex = 0; this.MinOccursTextBox.Text = "1"; this.MinOccursTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // groupBox2 // this.groupBox2.Controls.Add(this.MaxOccursRadio2); this.groupBox2.Controls.Add(this.MaxOccursRadio1); this.groupBox2.Controls.Add(this.MaxOccursTextBox); this.groupBox2.Location = new System.Drawing.Point(104, 80); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(208, 64); this.groupBox2.TabIndex = 6; this.groupBox2.TabStop = false; this.groupBox2.Text = "MaxOccurs"; // // MaxOccursRadio2 // this.MaxOccursRadio2.Location = new System.Drawing.Point(80, 24); this.MaxOccursRadio2.Name = "MaxOccursRadio2"; this.MaxOccursRadio2.Size = new System.Drawing.Size(96, 24); this.MaxOccursRadio2.TabIndex = 3; this.MaxOccursRadio2.Text = "UNBOUNDED"; // // MaxOccursRadio1 // this.MaxOccursRadio1.Checked = true; this.MaxOccursRadio1.Location = new System.Drawing.Point(8, 24); this.MaxOccursRadio1.Name = "MaxOccursRadio1"; this.MaxOccursRadio1.Size = new System.Drawing.Size(16, 24); this.MaxOccursRadio1.TabIndex = 2; this.MaxOccursRadio1.TabStop = true; // // MaxOccursTextBox // this.MaxOccursTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.MaxOccursTextBox.Location = new System.Drawing.Point(24, 24); this.MaxOccursTextBox.Name = "MaxOccursTextBox"; this.MaxOccursTextBox.Size = new System.Drawing.Size(48, 22); this.MaxOccursTextBox.TabIndex = 1; this.MaxOccursTextBox.Text = "1"; this.MaxOccursTextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // CancelButton // this.CancelButton.Enabled = false; this.CancelButton.Location = new System.Drawing.Point(240, 152); this.CancelButton.Name = "CancelButton"; this.CancelButton.TabIndex = 7; this.CancelButton.Text = "Cancel"; this.CancelButton.Click += new System.EventHandler(this.CancelButton_Click); // // groupBox3 // this.groupBox3.Controls.Add(this.AttributeRadioButton); this.groupBox3.Controls.Add(this.ElementRadioButton); this.groupBox3.Location = new System.Drawing.Point(320, 80); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(80, 64); this.groupBox3.TabIndex = 8; this.groupBox3.TabStop = false; this.groupBox3.Text = "Property"; // // AttributeRadioButton // this.AttributeRadioButton.Location = new System.Drawing.Point(8, 40); this.AttributeRadioButton.Name = "AttributeRadioButton"; this.AttributeRadioButton.Size = new System.Drawing.Size(64, 16); this.AttributeRadioButton.TabIndex = 1; this.AttributeRadioButton.Text = "Attribute"; // // ElementRadioButton // this.ElementRadioButton.Checked = true; this.ElementRadioButton.Location = new System.Drawing.Point(8, 16); this.ElementRadioButton.Name = "ElementRadioButton"; this.ElementRadioButton.Size = new System.Drawing.Size(64, 16); this.ElementRadioButton.TabIndex = 0; this.ElementRadioButton.TabStop = true; this.ElementRadioButton.Text = "Element"; // // FieldForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(416, 190); this.Controls.Add(this.groupBox3); this.Controls.Add(this.CancelButton); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.OKButton); this.Controls.Add(this.TypeComboBox); this.Controls.Add(this.textBox3); this.Controls.Add(this.NameTextBox); this.Controls.Add(this.textBox1); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FieldForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Field"; this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void OnTextChanged(object sender, System.EventArgs e) { if(this.NameTextBox.Text=="") { OKButton.Enabled=false; } else { OKButton.Enabled = true; } } private void OKButton_Click(object sender, System.EventArgs e) { if(ElementRadioButton.Checked) { NewContentItem = new UPnPComplexType.Element(); } else { NewContentItem = new UPnPComplexType.Attribute(); } NewContentItem.Name = this.NameTextBox.Text; if(TypeComboBox.SelectedItem.GetType()==typeof(UPnPComplexType)) { // Complex Type NewContentItem.Type = ((UPnPComplexType)TypeComboBox.SelectedItem).Name_LOCAL; NewContentItem.TypeNS = ((UPnPComplexType)TypeComboBox.SelectedItem).Name_NAMESPACE; NewContentItem.MinOccurs = MinOccursTextBox.Text; NewContentItem.MaxOccurs = MaxOccursRadio1.Checked?MaxOccursTextBox.Text:"UNBOUNDED"; } else { // Simple Type NewContentItem.Type = TypeComboBox.SelectedItem.ToString(); NewContentItem.TypeNS = ""; NewContentItem.MinOccurs = MinOccursTextBox.Text; NewContentItem.MaxOccurs = MaxOccursRadio1.Checked?MaxOccursTextBox.Text:"UNBOUNDED"; } this.DialogResult = DialogResult.OK; } private void CancelButton_Click(object sender, System.EventArgs e) { this.DialogResult = DialogResult.Cancel; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Xml.Serialization; using THNETII.Common; namespace THNETII.TypeConverter.Xml { /// <summary> /// Helper class that provides Enum-String Conversions that honour the /// <see cref="XmlEnumAttribute"/> applied to values of an enumeration type. /// </summary> public static class XmlEnumStringConverter { private class EnumValues<T> where T : struct, Enum { public static readonly Type TypeRef = typeof(T); public static readonly IDictionary<string, T> StringToValue = InitializeStringToValueDictionary(); public static readonly IDictionary<T, string> ValueToString = InitializeValueToStringDictionary(); [SuppressMessage("Microsoft.Usage", "CA2208", Target = "System.ArgumentException")] static void InitializeConversionDictionary(Action<string, T> dictionaryAddValueAction) { var ti = TypeRef.GetTypeInfo(); if (!ti.IsEnum) throw new ArgumentException($"Type Argument must represent an Enum type", nameof(T)); foreach (var fi in ti.DeclaredFields.Where(i => i.IsStatic)) { var enumMemberAttr = fi.GetCustomAttribute<XmlEnumAttribute>(); if (enumMemberAttr is null) continue; T v = (T)fi.GetValue(null); string s = enumMemberAttr.Name.NotNull(fi.Name); dictionaryAddValueAction(s, v); } } static IDictionary<string, T> InitializeStringToValueDictionary() { var stringToValue = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase); InitializeConversionDictionary((s, v) => { if (s is null) return; if (!stringToValue.ContainsKey(s)) stringToValue[s] = v; }); return stringToValue; } static IDictionary<T, string> InitializeValueToStringDictionary() { var valueToString = new Dictionary<T, string>(); InitializeConversionDictionary((s, v) => { if (!valueToString.ContainsKey(v)) valueToString[v] = s; }); return valueToString; } } /// <summary> /// Converts the string representation of the constant name, serialization name or the numeric value of one /// or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <returns>The converted value as an instance of <typeparamref name="T"/>.</returns> /// <remarks> /// The serialization name refers to the value specified in for the <see cref="XmlEnumAttribute.Name"/> member of an /// <see cref="XmlEnumAttribute"/> applied to one of the enumerated constants of the <typeparamref name="T"/> enumeration type. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1000")] public static T Parse<T>(string s) where T : struct, Enum { if (!(s is null) && EnumValues<T>.StringToValue.TryGetValue(s, out T value)) return value; return EnumStringConverter.Parse<T>(s!); } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns the default value for <typeparamref name="T"/> in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or the default value of <typeparamref name="T"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static T ParseOrDefault<T>(string? s) where T : struct, Enum => ParseOrDefault<T>(s, @default: default); /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns the specified alternate value in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <param name="default">The default value to return if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or <paramref name="default"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static T ParseOrDefault<T>(string? s, T @default) where T : struct, Enum { if (TryParse(s, out T value)) return value; return @default; } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns the specified alternate value in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <param name="defaultFactory">The factory that produces the value to return if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. Must not be <see langword="null"/>.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or the return value from <paramref name="defaultFactory"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="defaultFactory"/> is <see langword="null"/>.</exception> [SuppressMessage("Microsoft.Design", "CA1000")] public static T ParseOrDefault<T>(string? s, Func<T> defaultFactory) where T : struct, Enum { if (TryParse(s, out T value)) return value; else if (defaultFactory is null) throw new ArgumentNullException(nameof(defaultFactory)); return defaultFactory(); } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns the specified alternate value in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <param name="defaultFactory">The factory that produces the value to return if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. Must not be <see langword="null"/>.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or the return value from <paramref name="defaultFactory"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="defaultFactory"/> is <see langword="null"/>.</exception> [SuppressMessage("Microsoft.Design", "CA1000")] public static T ParseOrDefault<T>(string? s, Func<string?, T> defaultFactory) where T : struct, Enum { if (TryParse(s, out T value)) return value; else if (defaultFactory is null) throw new ArgumentNullException(nameof(defaultFactory)); return defaultFactory(s); } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns <see langword="null"/> in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <returns> /// The converted value as an instance of <typeparamref name="T"/>, or <see langword="null"/> /// if <paramref name="s"/> cannot be converted to <typeparamref name="T"/>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static T? ParseOrNull<T>(string? s) where T : struct, Enum { if (TryParse(s, out T value)) return value; return null; } /// <summary> /// Attempts to convert the string representation of the constant name, serialization name or numeric value of /// one or more enumerated constants to an equivalent enumerated value of <typeparamref name="T"/>. /// <para>This operation is always case-insensitive using ordinal string comparison.</para> /// <para>Returns <see langword="null"/> in case the string cannot be converted.</para> /// </summary> /// <typeparam name="T">The enumeration type to convert to.</typeparam> /// <param name="s">A string containing the name, serialization name or value to convert.</param> /// <param name="value">The converted value of <paramref name="s"/> if the method returns <see langword="true"/>.</param> /// <returns> /// <see langword="true"/> if <paramref name="s"/> was successfully converted to a value of <typeparamref name="T"/>; otherwise, <see langword="false"/>. /// </returns> /// <remarks>If this method returns <see langword="false"/>, the out-value of the <paramref name="value"/> parameter is not defined.</remarks> [SuppressMessage("Microsoft.Design", "CA1000")] public static bool TryParse<T>(string? s, out T value) where T : struct, Enum { if (!(s is null) && EnumValues<T>.StringToValue.TryGetValue(s, out value)) return true; return EnumStringConverter.TryParse(s!, out value); } /// <summary> /// Returns the serialized name or the default string representation of the specified value. /// </summary> /// <typeparam name="T">The enumeration type to convert from.</typeparam> /// <param name="value">The value of <typeparamref name="T"/> to serialize.</param> /// <returns> /// A string containing either the serialization name if the constant equal to <paramref name="value"/> /// has an <see cref="XmlEnumAttribute"/> applied to it; otherwise, the return value of <see cref="Enum.ToString()"/> for /// the specified value. /// </returns> [SuppressMessage("Microsoft.Design", "CA1000")] public static string ToString<T>(T value) where T : struct, Enum { if (EnumValues<T>.ValueToString.TryGetValue(value, out string s)) return s; return EnumStringConverter.ToString(value); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 10/6/2009 8:53:01 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// TabColorControl /// </summary> [DefaultEvent("ColorChanged"), ToolboxItem(false)] public class TabColorControl : UserControl { #region Events /// <summary> /// Occurs when the color is changed. /// </summary> public event EventHandler<ColorRangeEventArgs> ColorChanged; #endregion #region Private Variables private Color _endColor; private int _endHue; private float _endLight; private float _endSat; private bool _hsl; private int _hueShift; private bool _ignoreUpdates; private Color _startColor; private int _startHue; private float _startLight; private float _startSat; private Button btnHueShift; private Button btnReverseHue; private Button btnReverseLight; private Button btnReverseSat; private ColorButton cbEndColor; private ColorButton cbStartColor; private CheckBox chkUseColorRange; private GroupBox groupBox1; private Label lblEndColor; private Label lblHueRange; private Label lblLightnessRange; private Label lblSaturationRange; private Label lblStartColor; private RampSlider rampSlider1; private RampSlider rampSlider2; private HueSlider sldHue; private TwoColorSlider sldLightness; private TwoColorSlider sldSaturation; private TabControl tabColorRange; private TabPage tabHSL; private TabPage tabRGB; private Timer tmrHueShift; #endregion #region Constructors /// <summary> /// Creates a new instance of TabColorControl /// </summary> public TabColorControl() { InitializeComponent(); Configure(); } private void Configure() { tmrHueShift = new Timer { Interval = 100 }; tmrHueShift.Tick += tmrHueShift_Tick; btnHueShift.MouseDown += btnHueShift_MouseDown; btnHueShift.MouseUp += btnHueShift_MouseUp; } #endregion #region Methods /// <summary> /// Initializes a new instance of this control using the specified values. /// </summary> /// <param name="args">The ColorRangeEventArgs that stores the initial values.</param> public void Initialize(ColorRangeEventArgs args) { _endColor = args.EndColor; _hsl = args.HSL; _hueShift = args.HueShift; _startColor = args.StartColor; chkUseColorRange.Checked = args.UseColorRange; SetStartHsl(); SetEndHsl(); UpdateControls(); } private void SetStartHsl() { _startHue = (int)_startColor.GetHue(); _startSat = _startColor.GetSaturation(); _startLight = _startColor.GetBrightness(); } private void SetEndHsl() { _endHue = (int)_endColor.GetHue(); _endSat = _endColor.GetSaturation(); _endLight = _endColor.GetBrightness(); } #endregion #region Properties /// <summary> /// Gets or sets the start color, which controls the RGB start colors and the HSL left ranges /// </summary> [Category("Colors"), Description("Gets or sets the start color, which controls the RGB colors and the HSL range")] public Color StartColor { get { return _startColor; } set { _startColor = value; SetStartHsl(); cbStartColor.Color = value; } } /// <summary> /// Gets or sets the end color, which controls the RGB end color and the right HSL ranges /// </summary> [Category("Colors"), Description("Gets or sets the end color, which controls the RGB end color and the right HSL ranges")] public Color EndColor { get { return _endColor; } set { _endColor = value; SetEndHsl(); cbEndColor.Color = value; } } /// <summary> /// Gets or sets the integer hue shift marking how much the hue slider should be shifted /// </summary> [Category("Behavior"), Description("Gets or sets the integer hue shift marking how much the hue slider should be shifted")] public int HueShift { get { return _hueShift; } set { _hueShift = value; } } /// <summary> /// Gets or sets a boolean indicating whether or not the hue range is to be used. /// </summary> [Category("Behavior"), Description("Gets or sets a boolean indicating whether or not the hue range is to be used.")] public bool UseRangeChecked { get { return chkUseColorRange.Checked; } set { chkUseColorRange.Checked = value; } } #endregion #region Windows Form Designer generated code /// <summary> /// Disposes the unmanaged memory or controls /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { base.Dispose(disposing); } private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tabColorRange = new System.Windows.Forms.TabControl(); this.tabHSL = new System.Windows.Forms.TabPage(); this.btnReverseLight = new System.Windows.Forms.Button(); this.btnReverseSat = new System.Windows.Forms.Button(); this.btnReverseHue = new System.Windows.Forms.Button(); this.sldLightness = new DotSpatial.Symbology.Forms.TwoColorSlider(); this.sldSaturation = new DotSpatial.Symbology.Forms.TwoColorSlider(); this.btnHueShift = new System.Windows.Forms.Button(); this.sldHue = new DotSpatial.Symbology.Forms.HueSlider(); this.lblHueRange = new System.Windows.Forms.Label(); this.lblSaturationRange = new System.Windows.Forms.Label(); this.lblLightnessRange = new System.Windows.Forms.Label(); this.tabRGB = new System.Windows.Forms.TabPage(); this.rampSlider2 = new DotSpatial.Symbology.Forms.RampSlider(); this.cbEndColor = new DotSpatial.Symbology.Forms.ColorButton(); this.rampSlider1 = new DotSpatial.Symbology.Forms.RampSlider(); this.cbStartColor = new DotSpatial.Symbology.Forms.ColorButton(); this.lblEndColor = new System.Windows.Forms.Label(); this.lblStartColor = new System.Windows.Forms.Label(); this.chkUseColorRange = new System.Windows.Forms.CheckBox(); this.groupBox1.SuspendLayout(); this.tabColorRange.SuspendLayout(); this.tabHSL.SuspendLayout(); this.tabRGB.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.tabColorRange); this.groupBox1.Controls.Add(this.chkUseColorRange); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(227, 219); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; // // tabColorRange // this.tabColorRange.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabColorRange.Controls.Add(this.tabHSL); this.tabColorRange.Controls.Add(this.tabRGB); this.tabColorRange.Location = new System.Drawing.Point(6, 23); this.tabColorRange.Name = "tabColorRange"; this.tabColorRange.SelectedIndex = 0; this.tabColorRange.Size = new System.Drawing.Size(217, 189); this.tabColorRange.TabIndex = 12; // // tabHSL // this.tabHSL.Controls.Add(this.btnReverseLight); this.tabHSL.Controls.Add(this.btnReverseSat); this.tabHSL.Controls.Add(this.btnReverseHue); this.tabHSL.Controls.Add(this.sldLightness); this.tabHSL.Controls.Add(this.sldSaturation); this.tabHSL.Controls.Add(this.btnHueShift); this.tabHSL.Controls.Add(this.sldHue); this.tabHSL.Controls.Add(this.lblHueRange); this.tabHSL.Controls.Add(this.lblSaturationRange); this.tabHSL.Controls.Add(this.lblLightnessRange); this.tabHSL.Location = new System.Drawing.Point(4, 25); this.tabHSL.Name = "tabHSL"; this.tabHSL.Padding = new System.Windows.Forms.Padding(3); this.tabHSL.Size = new System.Drawing.Size(209, 160); this.tabHSL.TabIndex = 0; this.tabHSL.Text = "HSL"; this.tabHSL.UseVisualStyleBackColor = true; // // btnReverseLight // this.btnReverseLight.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.redbluearrows; this.btnReverseLight.Location = new System.Drawing.Point(144, 127); this.btnReverseLight.Name = "btnReverseLight"; this.btnReverseLight.Size = new System.Drawing.Size(28, 23); this.btnReverseLight.TabIndex = 9; this.btnReverseLight.UseVisualStyleBackColor = true; this.btnReverseLight.Click += new System.EventHandler(this.btnReverseLight_Click); // // btnReverseSat // this.btnReverseSat.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.redbluearrows; this.btnReverseSat.Location = new System.Drawing.Point(144, 78); this.btnReverseSat.Name = "btnReverseSat"; this.btnReverseSat.Size = new System.Drawing.Size(28, 23); this.btnReverseSat.TabIndex = 6; this.btnReverseSat.UseVisualStyleBackColor = true; this.btnReverseSat.Click += new System.EventHandler(this.btnReverseSat_Click); // // btnReverseHue // this.btnReverseHue.BackColor = System.Drawing.Color.Transparent; this.btnReverseHue.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.redbluearrows; this.btnReverseHue.Location = new System.Drawing.Point(144, 29); this.btnReverseHue.Name = "btnReverseHue"; this.btnReverseHue.Size = new System.Drawing.Size(28, 23); this.btnReverseHue.TabIndex = 2; this.btnReverseHue.UseVisualStyleBackColor = false; this.btnReverseHue.Click += new System.EventHandler(this.btnReverseHue_Click); // // sldLightness // this.sldLightness.Inverted = false; this.sldLightness.LeftHandle.Color = System.Drawing.Color.SteelBlue; this.sldLightness.LeftHandle.IsLeft = true; this.sldLightness.LeftHandle.Position = 0.0406504F; this.sldLightness.LeftHandle.RoundingRadius = 2; this.sldLightness.LeftHandle.Visible = true; this.sldLightness.LeftHandle.Width = 5; this.sldLightness.LeftValue = 0.0406504F; this.sldLightness.Location = new System.Drawing.Point(15, 127); this.sldLightness.Maximum = 1F; this.sldLightness.MaximumColor = System.Drawing.Color.White; this.sldLightness.Minimum = 0F; this.sldLightness.MinimumColor = System.Drawing.Color.Black; this.sldLightness.Name = "sldLightness"; this.sldLightness.RightHandle.Color = System.Drawing.Color.SteelBlue; this.sldLightness.RightHandle.IsLeft = false; this.sldLightness.RightHandle.Position = 0.8F; this.sldLightness.RightHandle.RoundingRadius = 2; this.sldLightness.RightHandle.Visible = true; this.sldLightness.RightHandle.Width = 5; this.sldLightness.RightValue = 0.8F; this.sldLightness.Size = new System.Drawing.Size(123, 23); this.sldLightness.TabIndex = 8; this.sldLightness.Text = "twoColorSlider2"; this.sldLightness.PositionChanging += new System.EventHandler(this.sldLightness_PositionChanging); // // sldSaturation // this.sldSaturation.Inverted = false; this.sldSaturation.LeftHandle.Color = System.Drawing.Color.SteelBlue; this.sldSaturation.LeftHandle.IsLeft = true; this.sldSaturation.LeftHandle.Position = 0.04098361F; this.sldSaturation.LeftHandle.RoundingRadius = 2; this.sldSaturation.LeftHandle.Visible = true; this.sldSaturation.LeftHandle.Width = 5; this.sldSaturation.LeftValue = 0.04098361F; this.sldSaturation.Location = new System.Drawing.Point(15, 78); this.sldSaturation.Maximum = 1F; this.sldSaturation.MaximumColor = System.Drawing.Color.Blue; this.sldSaturation.Minimum = 0F; this.sldSaturation.MinimumColor = System.Drawing.Color.White; this.sldSaturation.Name = "sldSaturation"; this.sldSaturation.RightHandle.Color = System.Drawing.Color.SteelBlue; this.sldSaturation.RightHandle.IsLeft = false; this.sldSaturation.RightHandle.Position = 0.8F; this.sldSaturation.RightHandle.RoundingRadius = 2; this.sldSaturation.RightHandle.Visible = true; this.sldSaturation.RightHandle.Width = 5; this.sldSaturation.RightValue = 0.8F; this.sldSaturation.Size = new System.Drawing.Size(122, 23); this.sldSaturation.TabIndex = 5; this.sldSaturation.Text = "twoColorSlider1"; this.sldSaturation.PositionChanging += new System.EventHandler(this.sldSaturation_PositionChanging); // // btnHueShift // this.btnHueShift.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.RunModel; this.btnHueShift.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.btnHueShift.Location = new System.Drawing.Point(178, 29); this.btnHueShift.Name = "btnHueShift"; this.btnHueShift.Size = new System.Drawing.Size(21, 23); this.btnHueShift.TabIndex = 3; this.btnHueShift.UseVisualStyleBackColor = true; // // sldHue // this.sldHue.HueShift = 0; this.sldHue.Inverted = false; this.sldHue.LeftHandle.Color = System.Drawing.Color.SteelBlue; this.sldHue.LeftHandle.Left = true; this.sldHue.LeftHandle.Position = 14.7541F; this.sldHue.LeftHandle.RoundingRadius = 2; this.sldHue.LeftHandle.Visible = true; this.sldHue.LeftHandle.Width = 5; this.sldHue.LeftValue = 14.7541F; this.sldHue.Location = new System.Drawing.Point(16, 29); this.sldHue.Maximum = 360; this.sldHue.Minimum = 0; this.sldHue.Name = "sldHue"; this.sldHue.RightHandle.Color = System.Drawing.Color.SteelBlue; this.sldHue.RightHandle.Left = false; this.sldHue.RightHandle.Position = 288F; this.sldHue.RightHandle.RoundingRadius = 2; this.sldHue.RightHandle.Visible = true; this.sldHue.RightHandle.Width = 5; this.sldHue.RightValue = 288F; this.sldHue.Size = new System.Drawing.Size(122, 23); this.sldHue.TabIndex = 1; this.sldHue.Text = "hueSlider1"; this.sldHue.PositionChanging += new System.EventHandler(this.sldHue_PositionChanging); // // lblHueRange // this.lblHueRange.AutoSize = true; this.lblHueRange.Location = new System.Drawing.Point(9, 13); this.lblHueRange.Name = "lblHueRange"; this.lblHueRange.Size = new System.Drawing.Size(84, 17); this.lblHueRange.TabIndex = 0; this.lblHueRange.Text = "Hue Range:"; // // lblSaturationRange // this.lblSaturationRange.AutoSize = true; this.lblSaturationRange.Location = new System.Drawing.Point(9, 62); this.lblSaturationRange.Name = "lblSaturationRange"; this.lblSaturationRange.Size = new System.Drawing.Size(123, 17); this.lblSaturationRange.TabIndex = 4; this.lblSaturationRange.Text = "Saturation Range:"; // // lblLightnessRange // this.lblLightnessRange.AutoSize = true; this.lblLightnessRange.Location = new System.Drawing.Point(9, 111); this.lblLightnessRange.Name = "lblLightnessRange"; this.lblLightnessRange.Size = new System.Drawing.Size(119, 17); this.lblLightnessRange.TabIndex = 7; this.lblLightnessRange.Text = "Lightness Range:"; // // tabRGB // this.tabRGB.Controls.Add(this.rampSlider2); this.tabRGB.Controls.Add(this.rampSlider1); this.tabRGB.Controls.Add(this.lblEndColor); this.tabRGB.Controls.Add(this.lblStartColor); this.tabRGB.Controls.Add(this.cbEndColor); this.tabRGB.Controls.Add(this.cbStartColor); this.tabRGB.Location = new System.Drawing.Point(4, 25); this.tabRGB.Name = "tabRGB"; this.tabRGB.Padding = new System.Windows.Forms.Padding(3); this.tabRGB.Size = new System.Drawing.Size(209, 160); this.tabRGB.TabIndex = 1; this.tabRGB.Text = "RGB"; this.tabRGB.UseVisualStyleBackColor = true; // // rampSlider2 // this.rampSlider2.ColorButton = this.cbEndColor; this.rampSlider2.FlipRamp = false; this.rampSlider2.FlipText = false; this.rampSlider2.InvertRamp = false; this.rampSlider2.Location = new System.Drawing.Point(93, 106); this.rampSlider2.Maximum = 1D; this.rampSlider2.MaximumColor = System.Drawing.Color.Blue; this.rampSlider2.Minimum = 0D; this.rampSlider2.MinimumColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); this.rampSlider2.Name = "rampSlider2"; this.rampSlider2.NumberFormat = "#.00"; this.rampSlider2.Orientation = System.Windows.Forms.Orientation.Horizontal; this.rampSlider2.RampRadius = 10F; this.rampSlider2.RampText = "Opacity"; this.rampSlider2.RampTextAlignment = System.Drawing.ContentAlignment.MiddleCenter; this.rampSlider2.RampTextBehindRamp = true; this.rampSlider2.RampTextColor = System.Drawing.Color.Black; this.rampSlider2.RampTextFont = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rampSlider2.ShowMaximum = false; this.rampSlider2.ShowMinimum = false; this.rampSlider2.ShowTicks = false; this.rampSlider2.ShowValue = false; this.rampSlider2.Size = new System.Drawing.Size(97, 25); this.rampSlider2.SliderColor = System.Drawing.Color.Blue; this.rampSlider2.SliderRadius = 4F; this.rampSlider2.TabIndex = 5; this.rampSlider2.Text = "rampSlider2"; this.rampSlider2.TickColor = System.Drawing.Color.DarkGray; this.rampSlider2.TickSpacing = 5F; this.rampSlider2.Value = 1D; // // cbEndColor // this.cbEndColor.BevelRadius = 2; this.cbEndColor.Color = System.Drawing.Color.Navy; this.cbEndColor.LaunchDialogOnClick = true; this.cbEndColor.Location = new System.Drawing.Point(33, 106); this.cbEndColor.Name = "cbEndColor"; this.cbEndColor.RoundingRadius = 4; this.cbEndColor.Size = new System.Drawing.Size(40, 25); this.cbEndColor.TabIndex = 2; this.cbEndColor.Text = "colorButton2"; this.cbEndColor.ColorChanged += new System.EventHandler(this.cbEndColor_ColorChanged); // // rampSlider1 // this.rampSlider1.ColorButton = this.cbStartColor; this.rampSlider1.FlipRamp = false; this.rampSlider1.FlipText = false; this.rampSlider1.InvertRamp = false; this.rampSlider1.Location = new System.Drawing.Point(93, 38); this.rampSlider1.Maximum = 1D; this.rampSlider1.MaximumColor = System.Drawing.Color.Blue; this.rampSlider1.Minimum = 0D; this.rampSlider1.MinimumColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); this.rampSlider1.Name = "rampSlider1"; this.rampSlider1.NumberFormat = "#.00"; this.rampSlider1.Orientation = System.Windows.Forms.Orientation.Horizontal; this.rampSlider1.RampRadius = 10F; this.rampSlider1.RampText = "Opacity"; this.rampSlider1.RampTextAlignment = System.Drawing.ContentAlignment.MiddleCenter; this.rampSlider1.RampTextBehindRamp = true; this.rampSlider1.RampTextColor = System.Drawing.Color.Black; this.rampSlider1.RampTextFont = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.rampSlider1.ShowMaximum = false; this.rampSlider1.ShowMinimum = false; this.rampSlider1.ShowTicks = false; this.rampSlider1.ShowValue = false; this.rampSlider1.Size = new System.Drawing.Size(97, 25); this.rampSlider1.SliderColor = System.Drawing.Color.Blue; this.rampSlider1.SliderRadius = 4F; this.rampSlider1.TabIndex = 4; this.rampSlider1.Text = "rampSlider1"; this.rampSlider1.TickColor = System.Drawing.Color.DarkGray; this.rampSlider1.TickSpacing = 5F; this.rampSlider1.Value = 1D; // // cbStartColor // this.cbStartColor.BevelRadius = 2; this.cbStartColor.Color = System.Drawing.Color.LightBlue; this.cbStartColor.LaunchDialogOnClick = true; this.cbStartColor.Location = new System.Drawing.Point(33, 38); this.cbStartColor.Name = "cbStartColor"; this.cbStartColor.RoundingRadius = 4; this.cbStartColor.Size = new System.Drawing.Size(40, 25); this.cbStartColor.TabIndex = 0; this.cbStartColor.Text = "colorButton1"; this.cbStartColor.ColorChanged += new System.EventHandler(this.cbStartColor_ColorChanged); // // lblEndColor // this.lblEndColor.AutoSize = true; this.lblEndColor.Location = new System.Drawing.Point(8, 80); this.lblEndColor.Name = "lblEndColor"; this.lblEndColor.Size = new System.Drawing.Size(70, 17); this.lblEndColor.TabIndex = 3; this.lblEndColor.Text = "&End Color"; // // lblStartColor // this.lblStartColor.AutoSize = true; this.lblStartColor.Location = new System.Drawing.Point(8, 12); this.lblStartColor.Name = "lblStartColor"; this.lblStartColor.Size = new System.Drawing.Size(75, 17); this.lblStartColor.TabIndex = 1; this.lblStartColor.Text = "&Start Color"; // // chkUseColorRange // this.chkUseColorRange.AutoSize = true; this.chkUseColorRange.Checked = true; this.chkUseColorRange.CheckState = System.Windows.Forms.CheckState.Checked; this.chkUseColorRange.Location = new System.Drawing.Point(6, 0); this.chkUseColorRange.Name = "chkUseColorRange"; this.chkUseColorRange.Size = new System.Drawing.Size(138, 21); this.chkUseColorRange.TabIndex = 11; this.chkUseColorRange.Text = "Use Color &Range"; this.chkUseColorRange.UseVisualStyleBackColor = true; this.chkUseColorRange.CheckedChanged += new System.EventHandler(this.chkUseColorRange_CheckedChanged); // // TabColorControl // this.Controls.Add(this.groupBox1); this.Name = "TabColorControl"; this.Size = new System.Drawing.Size(227, 219); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.tabColorRange.ResumeLayout(false); this.tabHSL.ResumeLayout(false); this.tabHSL.PerformLayout(); this.tabRGB.ResumeLayout(false); this.tabRGB.PerformLayout(); this.ResumeLayout(false); } #endregion private void btnHueShift_MouseUp(object sender, MouseEventArgs e) { tmrHueShift.Stop(); } private void btnHueShift_MouseDown(object sender, MouseEventArgs e) { tmrHueShift.Start(); } private void sldHue_PositionChanging(object sender, EventArgs e) { SetHsl(); } private void tmrHueShift_Tick(object sender, EventArgs e) { int shift = sldHue.Inverted ? 36 : -36; _ignoreUpdates = true; sldHue.HueShift = (sldHue.HueShift + shift) % 360; //sldHue.LeftValue = sldHue.LeftValue; //sldHue.RightValue = sldHue.RightValue; SetHsl(); } private void btnReverseHue_Click(object sender, EventArgs e) { sldHue.Inverted = !sldHue.Inverted; SetHsl(); } private void btnReverseSat_Click(object sender, EventArgs e) { sldSaturation.Inverted = !sldSaturation.Inverted; SetHsl(); } private void btnReverseLight_Click(object sender, EventArgs e) { sldLightness.Inverted = !sldLightness.Inverted; SetHsl(); } private void sldSaturation_PositionChanging(object sender, EventArgs e) { SetHsl(); } private void sldLightness_PositionChanging(object sender, EventArgs e) { SetHsl(); } private void cbStartColor_ColorChanged(object sender, EventArgs e) { SetRgb(); } private void cbEndColor_ColorChanged(object sender, EventArgs e) { SetRgb(); } // Reads the current control settings to the cached values. private void SetHsl() { if (_ignoreUpdates) return; _hueShift = sldHue.HueShift; int h = (int)(sldHue.LeftValue + (_hueShift) % 360); float s = sldSaturation.LeftValue; float l = sldLightness.LeftValue; float a = _startColor.A / 255f; _startColor = SymbologyGlobal.ColorFromHsl(h, s, l).ToTransparent(a); _startHue = h; _startSat = s; _startLight = l; h = (int)(sldHue.RightValue + _hueShift) % 360; s = sldSaturation.RightValue; l = sldLightness.RightValue; a = _endColor.A / 255f; _endHue = h; _endSat = s; _endLight = l; _endColor = SymbologyGlobal.ColorFromHsl(h, s, l).ToTransparent(a); _hsl = true; chkUseColorRange.Checked = true; _ignoreUpdates = true; cbStartColor.Color = _startColor; cbEndColor.Color = _endColor; _ignoreUpdates = false; UpdateControls(); } // Updates private void SetRgb() { if (_ignoreUpdates) return; _startColor = cbStartColor.Color; _endColor = cbEndColor.Color; SetStartHsl(); SetEndHsl(); chkUseColorRange.Checked = true; _hsl = false; UpdateControls(); } private void UpdateControls() { // Prevent infinite loops if (_ignoreUpdates) return; _ignoreUpdates = true; if (_hsl) { // Don't use the colors directly, here mainly because saturation // loses information when going back and forth from a color. if (_startHue != _endHue) sldHue.Inverted = _startHue > _endHue; sldHue.LeftValue = _startHue; sldHue.RightValue = _endHue; if (_startSat != _endSat) sldSaturation.Inverted = _startSat > _endSat; sldSaturation.LeftValue = _startSat; sldSaturation.RightValue = _endSat; if (_startLight != _endLight) sldLightness.Inverted = _startLight > _endLight; sldLightness.LeftValue = _startLight; sldLightness.RightValue = _endLight; } else { sldHue.SetRange(_startColor, _endColor); sldSaturation.SetSaturation(_startColor, _endColor); sldLightness.SetLightness(_startColor, _endColor); sldHue.HueShift = _hueShift; cbStartColor.Color = _startColor; cbEndColor.Color = _endColor; } tabColorRange.SelectedTab = _hsl ? tabHSL : tabRGB; _ignoreUpdates = false; OnColorChanged(); } /// <summary> /// Fires the ColorChanged event /// </summary> protected virtual void OnColorChanged() { if (ColorChanged != null) ColorChanged(this, new ColorRangeEventArgs(_startColor, _endColor, _hueShift, _hsl, chkUseColorRange.Checked)); } private void chkUseColorRange_CheckedChanged(object sender, EventArgs e) { OnColorChanged(); } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Geometry; using FlatRedBall.Math.Splines; using Cursor = FlatRedBall.Gui.Cursor; using GuiManager = FlatRedBall.Gui.GuiManager; using FlatRedBall.Localization; using FlatRedBall.Instructions; #if FRB_XNA || SILVERLIGHT using Keys = Microsoft.Xna.Framework.Input.Keys; using Vector3 = Microsoft.Xna.Framework.Vector3; using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; using GlueTestProject.Entities; using FlatRedBall.ManagedSpriteGroups; #endif namespace GlueTestProject.Screens { public partial class FlatRedBallTypeScreen { #region Fields bool mHasCheckedX = false; bool mHasCheckedPosition = false; bool mHasCheckedTextInterpolation = false; SpriteFrame layeredSpriteFrameInstantiatedInCode; SpriteFrame unlayeredSpriteFrameInstantiatedInCode; Sprite managedInvisiblTestSprite1; #endregion void CustomInitialize() { if (!SpriteManager.OrderedSprites.Contains(this.SpriteObject)) { throw new Exception("The Sprite object is not being added to the managers but it should be."); } if (ShapeCollectionFile.AxisAlignedRectangles.Contains(this.InvisibleRectangle) == false) { throw new Exception("The ShapeCollection does not contain the rectangle - possibly because it's being improperly cloned"); } if (this.InvisibleRectangle.Visible) { throw new Exception("Rectangles that come from files that have their Visible set to false are still visible"); } this.SceneInstanceSetFromFileAtRuntime = SceneFile; SpriteWithInstructions.Set("X").To(4.0f).After(.1f); SpriteWithInstructions.Set("Position").To(Vector3.One).After(.25); TestingTextInterpolationInstance.CurrentTextValuesState = InterpolationEntity.TextValues.Transparent; TestingTextInterpolationInstance.InterpolateToState(InterpolationEntity.TextValues.Opaque, 1); this.DynamicallyAssignedSceneSourceFile = SceneOption1; if(this.DynamicallyAssignedSceneSourceFile != SceneOption1) { throw new Exception("Setting the source file does not do anything"); } // The CameraModifyingEntity sets the Z. This should persist if (SpriteManager.Camera.Z != CameraModifyingEntity.CameraZToSet) { throw new Exception("The CameraModifyingEntity should modify the Camera's Z, but it's not!"); } ManuallyUpdatedEntityInstance.ConvertToManuallyUpdated(); // let's make sure that this thing actually has a collision function: bool didCollide = CollisionEntityInstance.CollideAgainst(CollisionEntityInstance2); // And that it worked if (!didCollide) { throw new Exception("ICollidable entities aren't properly detecting collisions"); } CollisionEntityInstance.CollideAgainstMove(CollisionEntityInstance2, 1, 0); CollisionEntityInstance.CollideAgainstBounce(CollisionEntityInstance2, 1, 0, 1); if (this.LayerInstance.Sprites.Contains(SpriteFrameInheritingEntityInstanceLayered.CenterSprite) == false) { throw new Exception("SpriteFrame-inheriting entities do not get put on Layers properly"); } if (this.LayerInstance.Sprites.Contains(this.SpriteInheritingEntityInstanceLayered) == false) { throw new Exception("SpriteFrame-inheriting entities do not get put on Layers properly"); } if (this.LayerInstance.Texts.Contains(TextInheritingEntityInstanceLayered) == false) { throw new Exception("SpriteFrame-inheriting entities do not get put on Layers properly"); } SpriteFrameInheritingEntityInstanceLayered.MoveToLayer(LayerInstance2); SpriteInheritingEntityInstanceLayered.MoveToLayer(LayerInstance2); TextInheritingEntityInstanceLayered.MoveToLayer(LayerInstance2); // Make sure that entities with objects that are not instantiated an be moved to layers: NoInstantiationForMoveToLayer.MoveToLayer(LayerInstance2); if (this.LayerInstance2.Sprites.Contains(SpriteFrameInheritingEntityInstanceLayered.CenterSprite) == false) { throw new Exception("SpriteFrame-inheriting entities aren't moved to other layers properly"); } if (this.LayerInstance2.Sprites.Contains(this.SpriteInheritingEntityInstanceLayered) == false) { throw new Exception("SpriteFrame-inheriting entities aren't moved to other layers properly"); } if (this.LayerInstance2.Texts.Contains(TextInheritingEntityInstanceLayered) == false) { throw new Exception("SpriteFrame-inheriting entities aren't moved to other layers properly"); } SetToInvisibleTestTextVisibility.Visible = false; if (SetToInvisibleTestTextVisibility.TextInstance.Visible) { throw new Exception("Setting an Entity that inherits from a FRB type to Invisible should set its IsContainer NOS to invisible too"); } SpriteManager.AddToLayer(UnlayeredSpriteFrameNotAllSidesMoveToLayer, this.LayerInstance); // Now let's test SpriteFrames that we instantiate and add to layer right away layeredSpriteFrameInstantiatedInCode = new SpriteFrame(Aura, SpriteFrame.BorderSides.Left); SpriteManager.AddToLayer(layeredSpriteFrameInstantiatedInCode, LayerInstance); unlayeredSpriteFrameInstantiatedInCode = new SpriteFrame(Aura, SpriteFrame.BorderSides.Left); SpriteManager.AddToLayer(unlayeredSpriteFrameInstantiatedInCode, null); // Make sure AARects have the "all" reposition direction initially: var rectangle = new AxisAlignedRectangle(); if(rectangle.RepositionDirections != RepositionDirections.All) { throw new Exception("AARects should have the All reposition direction, but they don't."); } managedInvisiblTestSprite1 = new Sprite(); // January 25, 2015 // A FRB user found a // crash bug occurring // if adding a Sprite as // a ManagedInvisibleSprite, // then later adding it to a Layer. // I was able to reproduce it in the // test project. Before the bug was fixed // the engine would crash internall. SpriteManager.AddManagedInvisibleSprite(managedInvisiblTestSprite1); SpriteManager.AddToLayer(managedInvisiblTestSprite1, this.LayerInstance); // The IDrawableBatchEntity depends on draw calls happening, and we // want to make sure that they don't get skipped on platforms like iOS // where performance may be lower than PC. We're going to force draw calls // to happen after every activity. FlatRedBallServices.Game.IsFixedTimeStep = false; } void CustomActivity(bool firstTimeCalled) { // We need this screen to survive a while to make sure the emitter is emitting properly //if (!firstTimeCalled) //{ // IsActivityFinished = true; //} if(!firstTimeCalled) { } if (!mHasCheckedX && this.PauseAdjustedSecondsSince(0) > .21f) { if (SpriteWithInstructions.X != 4.0f) { throw new Exception("Property instructions are not working"); } mHasCheckedX = true; } if (!mHasCheckedPosition && this.PauseAdjustedSecondsSince(0) > .51f) { if (SpriteWithInstructions.Position != Vector3.One) { throw new Exception("Field instructions are not working"); } mHasCheckedPosition = true; } if (!mHasCheckedTextInterpolation && this.PauseAdjustedSecondsSince(0) > .5f) { if (TestingTextInterpolationInstance.TextInstanceX == 0) { throw new Exception("Text position interpolation over time doesn't work"); } if (TestingTextInterpolationInstance.TextInstanceAlpha == 0) { throw new Exception("Text alpha interpolation over time doesn't work"); } mHasCheckedTextInterpolation = true; } const float secondsToLast = .6f; if (this.PauseAdjustedSecondsSince(0) > secondsToLast && this.IDrawableBatchEntityInstance.HasFinishedTests) { IsActivityFinished = true; } } void CustomDestroy() { SpriteManager.RemoveSpriteFrame(layeredSpriteFrameInstantiatedInCode); SpriteManager.RemoveSpriteFrame(unlayeredSpriteFrameInstantiatedInCode); SpriteManager.RemoveSprite(managedInvisiblTestSprite1); } static void CustomLoadStaticContent(string contentManagerName) { } } }
using System.Diagnostics.CodeAnalysis; using GraphQLParser.AST; namespace GraphQLParser.Visitors; /// <summary> /// Prints AST into the provided <see cref="TextWriter"/> as a SDL document. /// </summary> /// <typeparam name="TContext">Type of the context object passed into all VisitXXX methods.</typeparam> public class SDLPrinter<TContext> : ASTVisitor<TContext> where TContext : IPrintContext { /// <summary> /// Creates visitor with default options. /// </summary> public SDLPrinter() : this(new SDLPrinterOptions()) { } /// <summary> /// Creates visitor with the specified options. /// </summary> /// <param name="options">Visitor options.</param> public SDLPrinter(SDLPrinterOptions options) { Options = options; } /// <summary> /// Options used by visitor. /// </summary> public SDLPrinterOptions Options { get; } /// <inheritdoc/> protected override async ValueTask VisitDocumentAsync(GraphQLDocument document, TContext context) { await VisitAsync(document.Comments, context).ConfigureAwait(false); // Comments always null if (document.Definitions.Count > 0) // Definitions always > 0 { for (int i = 0; i < document.Definitions.Count; ++i) await VisitAsync(document.Definitions[i], context).ConfigureAwait(false); } } /// <inheritdoc/> protected override async ValueTask VisitCommentAsync(GraphQLComment comment, TContext context) { if (!Options.PrintComments) return; if (CommentedNodeShouldBeCloseToPreviousNode(context, comment, true)) await context.WriteLineAsync().ConfigureAwait(false); await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync("#").ConfigureAwait(false); await context.WriteAsync(comment.Value).ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); if (CommentedNodeShouldBeCloseToPreviousNode(context, comment, false)) await WriteIndentAsync(context).ConfigureAwait(false); static bool CommentedNodeShouldBeCloseToPreviousNode(TContext context, GraphQLComment comment, bool start) { return TryPeekParent(context, out var parent) && ReferenceEquals(parent.Comments![start ? 0 : parent.Comments.Count - 1], comment) && parent is GraphQLArguments || parent is GraphQLArgument || parent is GraphQLObjectField || parent is GraphQLName || parent is GraphQLUnionMemberTypes || parent is GraphQLEnumValuesDefinition || parent is GraphQLFieldsDefinition || parent is GraphQLInputFieldsDefinition || parent is GraphQLInputValueDefinition; } } /// <inheritdoc/> protected override async ValueTask VisitDescriptionAsync(GraphQLDescription description, TContext context) { bool ShouldBeMultilineBlockString() { bool newLineDetected = false; var span = description.Value.Span; for (int i = 0; i < span.Length; ++i) { char code = span[i]; if (code < 0x0020 && code != 0x0009 && code != 0x000A && code != 0x000D) return false; if (code == 0x000A) newLineDetected = true; } // Note that string value without escape symbols and newline symbols // MAY BE represented as a single-line BlockString, for example, // """SOME TEXT""", but it was decided to use more brief "SOME TEXT" // for such cases. WriteMultilineBlockString method ALWAYS builds // BlockString printing """ on new line. return newLineDetected; } async ValueTask WriteMultilineBlockString() { await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync("\"\"\"").ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); bool needStartNewLine = true; int length = description.Value.Span.Length; // http://spec.graphql.org/October2021/#BlockStringCharacter for (int i = 0; i < length; ++i) { if (needStartNewLine) { await WriteIndentAsync(context).ConfigureAwait(false); needStartNewLine = false; } char code = description.Value.Span[i]; switch (code) { case '\r': break; case '\n': await context.WriteLineAsync().ConfigureAwait(false); needStartNewLine = true; break; case '"': if (i < length - 2 && description.Value.Span[i + 1] == '"' && description.Value.Span[i + 2] == '"') { await context.WriteAsync("\\\"").ConfigureAwait(false); } else { await context.WriteAsync(description.Value.Slice(i, 1)/*code*/).ConfigureAwait(false); //TODO: change } break; default: await context.WriteAsync(description.Value.Slice(i, 1)/*code*/).ConfigureAwait(false); //TODO: change break; } } await context.WriteLineAsync().ConfigureAwait(false); await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync("\"\"\"").ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); } async ValueTask WriteString() { await WriteIndentAsync(context).ConfigureAwait(false); await WriteEncodedStringAsync(context, description.Value).ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); } static bool DescribedNodeShouldBeCloseToPreviousNode(TContext context) { return TryPeekParent(context, out var parent) && parent is GraphQLInputValueDefinition; } if (DescribedNodeShouldBeCloseToPreviousNode(context)) await context.WriteLineAsync().ConfigureAwait(false); // http://spec.graphql.org/October2021/#StringValue if (ShouldBeMultilineBlockString()) await WriteMultilineBlockString(); else await WriteString(); if (DescribedNodeShouldBeCloseToPreviousNode(context)) await WriteIndentAsync(context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitNameAsync(GraphQLName name, TContext context) { await VisitAsync(name.Comments, context).ConfigureAwait(false); await context.WriteAsync(name.Value).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitFragmentNameAsync(GraphQLFragmentName fragmentName, TContext context) { await VisitAsync(fragmentName.Comments, context).ConfigureAwait(false); await VisitAsync(fragmentName.Name, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitFragmentDefinitionAsync(GraphQLFragmentDefinition fragmentDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(fragmentDefinition.Comments, context).ConfigureAwait(false); await context.WriteAsync("fragment ").ConfigureAwait(false); await VisitAsync(fragmentDefinition.FragmentName, context).ConfigureAwait(false); await context.WriteAsync(" ").ConfigureAwait(false); await VisitAsync(fragmentDefinition.TypeCondition, context).ConfigureAwait(false); await VisitAsync(fragmentDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(fragmentDefinition.SelectionSet, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitFragmentSpreadAsync(GraphQLFragmentSpread fragmentSpread, TContext context) { await VisitAsync(fragmentSpread.Comments, context).ConfigureAwait(false); await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync("...").ConfigureAwait(false); await VisitAsync(fragmentSpread.FragmentName, context).ConfigureAwait(false); await VisitAsync(fragmentSpread.Directives, context).ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitInlineFragmentAsync(GraphQLInlineFragment inlineFragment, TContext context) { await VisitAsync(inlineFragment.Comments, context).ConfigureAwait(false); await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync("... ").ConfigureAwait(false); await VisitAsync(inlineFragment.TypeCondition, context).ConfigureAwait(false); await VisitAsync(inlineFragment.Directives, context).ConfigureAwait(false); await VisitAsync(inlineFragment.SelectionSet, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitTypeConditionAsync(GraphQLTypeCondition typeCondition, TContext context) { await VisitAsync(typeCondition.Comments, context).ConfigureAwait(false); await context.WriteAsync("on ").ConfigureAwait(false); await VisitAsync(typeCondition.Type, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitImplementsInterfacesAsync(GraphQLImplementsInterfaces implementsInterfaces, TContext context) { await VisitAsync(implementsInterfaces.Comments, context).ConfigureAwait(false); await context.WriteAsync(" implements ").ConfigureAwait(false); for (int i = 0; i < implementsInterfaces.Items.Count; ++i) { await VisitAsync(implementsInterfaces.Items[i], context).ConfigureAwait(false); if (i < implementsInterfaces.Items.Count - 1) await context.WriteAsync(" & ").ConfigureAwait(false); } } /// <inheritdoc/> protected override async ValueTask VisitSelectionSetAsync(GraphQLSelectionSet selectionSet, TContext context) { await VisitAsync(selectionSet.Comments, context).ConfigureAwait(false); bool freshLine = selectionSet.Comments != null && Options.PrintComments; bool hasParent = TryPeekParent(context, out var parent); if (!freshLine && hasParent && (parent is GraphQLOperationDefinition op && op.Name is not null || parent is not GraphQLOperationDefinition)) { await context.WriteAsync(" {").ConfigureAwait(false); } else { await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync("{").ConfigureAwait(false); } await context.WriteLineAsync().ConfigureAwait(false); foreach (var selection in selectionSet.Selections) await VisitAsync(selection, context).ConfigureAwait(false); await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync("}").ConfigureAwait(false); if (parent is not GraphQLOperationDefinition && parent is not GraphQLFragmentDefinition) await context.WriteLineAsync().ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitAliasAsync(GraphQLAlias alias, TContext context) { await VisitAsync(alias.Comments, context).ConfigureAwait(false); await WriteIndentAsync(context).ConfigureAwait(false); await VisitAsync(alias.Name, context).ConfigureAwait(false); await context.WriteAsync(":").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitFieldAsync(GraphQLField field, TContext context) { await VisitAsync(field.Comments, context).ConfigureAwait(false); await VisitAsync(field.Alias, context).ConfigureAwait(false); if (field.Alias == null) await WriteIndentAsync(context).ConfigureAwait(false); else if (field.Name.Comments == null || !Options.PrintComments) await context.WriteAsync(" ").ConfigureAwait(false); await VisitAsync(field.Name, context).ConfigureAwait(false); await VisitAsync(field.Arguments, context).ConfigureAwait(false); await VisitAsync(field.Directives, context).ConfigureAwait(false); await VisitAsync(field.SelectionSet, context).ConfigureAwait(false); if (field.SelectionSet == null) await context.WriteLineAsync().ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitOperationDefinitionAsync(GraphQLOperationDefinition operationDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(operationDefinition.Comments, context).ConfigureAwait(false); if (operationDefinition.Name is not null) { await context.WriteAsync(GetOperationType(operationDefinition.Operation)).ConfigureAwait(false); await context.WriteAsync(" ").ConfigureAwait(false); await VisitAsync(operationDefinition.Name, context).ConfigureAwait(false); } await VisitAsync(operationDefinition.Variables, context).ConfigureAwait(false); await VisitAsync(operationDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(operationDefinition.SelectionSet, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitDirectiveDefinitionAsync(GraphQLDirectiveDefinition directiveDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(directiveDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(directiveDefinition.Description, context).ConfigureAwait(false); await context.WriteAsync("directive @").ConfigureAwait(false); await VisitAsync(directiveDefinition.Name, context).ConfigureAwait(false); await VisitAsync(directiveDefinition.Arguments, context).ConfigureAwait(false); if (directiveDefinition.Repeatable) await context.WriteAsync(" repeatable").ConfigureAwait(false); await VisitAsync(directiveDefinition.Locations, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitDirectiveLocationsAsync(GraphQLDirectiveLocations directiveLocations, TContext context) { await VisitAsync(directiveLocations.Comments, context).ConfigureAwait(false); if (Options.EachDirectiveLocationOnNewLine) { await context.WriteAsync(" on").ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); for (int i = 0; i < directiveLocations.Items.Count; ++i) { await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync("| ").ConfigureAwait(false); await context.WriteAsync(GetDirectiveLocation(directiveLocations.Items[i])).ConfigureAwait(false); if (i < directiveLocations.Items.Count - 1) await context.WriteLineAsync().ConfigureAwait(false); } } else { await context.WriteAsync(" on ").ConfigureAwait(false); for (int i = 0; i < directiveLocations.Items.Count; ++i) { await context.WriteAsync(GetDirectiveLocation(directiveLocations.Items[i])).ConfigureAwait(false); if (i < directiveLocations.Items.Count - 1) await context.WriteAsync(" | ").ConfigureAwait(false); } } } /// <inheritdoc/> protected override async ValueTask VisitVariableDefinitionAsync(GraphQLVariableDefinition variableDefinition, TContext context) { await VisitAsync(variableDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(variableDefinition.Variable, context).ConfigureAwait(false); await context.WriteAsync(": ").ConfigureAwait(false); await VisitAsync(variableDefinition.Type, context).ConfigureAwait(false); if (variableDefinition.DefaultValue != null) { await context.WriteAsync(" = ").ConfigureAwait(false); await VisitAsync(variableDefinition.DefaultValue, context).ConfigureAwait(false); } await VisitAsync(variableDefinition.Directives, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitVariablesDefinitionAsync(GraphQLVariablesDefinition variablesDefinition, TContext context) { await VisitAsync(variablesDefinition.Comments, context).ConfigureAwait(false); await context.WriteAsync("(").ConfigureAwait(false); for (int i = 0; i < variablesDefinition.Items.Count; ++i) { await VisitAsync(variablesDefinition.Items[i], context).ConfigureAwait(false); if (i < variablesDefinition.Items.Count - 1) await context.WriteAsync(", ").ConfigureAwait(false); } await context.WriteAsync(")").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitVariableAsync(GraphQLVariable variable, TContext context) { await VisitAsync(variable.Comments, context).ConfigureAwait(false); await context.WriteAsync("$").ConfigureAwait(false); await VisitAsync(variable.Name, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitBooleanValueAsync(GraphQLBooleanValue booleanValue, TContext context) { await VisitAsync(booleanValue.Comments, context).ConfigureAwait(false); await context.WriteAsync(booleanValue.Value).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitScalarTypeDefinitionAsync(GraphQLScalarTypeDefinition scalarTypeDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(scalarTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(scalarTypeDefinition.Description, context).ConfigureAwait(false); await context.WriteAsync("scalar ").ConfigureAwait(false); await VisitAsync(scalarTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(scalarTypeDefinition.Directives, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitSchemaExtensionAsync(GraphQLSchemaExtension schemaExtension, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(schemaExtension.Comments, context).ConfigureAwait(false); await context.WriteAsync("extend schema").ConfigureAwait(false); await VisitAsync(schemaExtension.Directives, context).ConfigureAwait(false); //TODO: https://github.com/graphql/graphql-spec/issues/921 if (schemaExtension.OperationTypes?.Count > 0) { //bool freshLine = schemaExtension.Comments != null && Options.PrintComments; always false await context.WriteAsync(/*freshLine ? "{" :*/" {").ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); for (int i = 0; i < schemaExtension.OperationTypes.Count; ++i) { await VisitAsync(schemaExtension.OperationTypes[i], context).ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); } await context.WriteAsync("}").ConfigureAwait(false); } context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitScalarTypeExtensionAsync(GraphQLScalarTypeExtension scalarTypeExtension, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(scalarTypeExtension.Comments, context).ConfigureAwait(false); await context.WriteAsync("extend scalar ").ConfigureAwait(false); await VisitAsync(scalarTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(scalarTypeExtension.Directives, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitEnumTypeDefinitionAsync(GraphQLEnumTypeDefinition enumTypeDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(enumTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(enumTypeDefinition.Description, context).ConfigureAwait(false); await context.WriteAsync("enum ").ConfigureAwait(false); await VisitAsync(enumTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(enumTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(enumTypeDefinition.Values, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitEnumTypeExtensionAsync(GraphQLEnumTypeExtension enumTypeExtension, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(enumTypeExtension.Comments, context).ConfigureAwait(false); await context.WriteAsync("extend enum ").ConfigureAwait(false); await VisitAsync(enumTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(enumTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(enumTypeExtension.Values, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitEnumValueDefinitionAsync(GraphQLEnumValueDefinition enumValueDefinition, TContext context) { await VisitAsync(enumValueDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(enumValueDefinition.Description, context).ConfigureAwait(false); await WriteIndentAsync(context).ConfigureAwait(false); await VisitAsync(enumValueDefinition.Name, context).ConfigureAwait(false); await VisitAsync(enumValueDefinition.Directives, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitEnumValuesDefinitionAsync(GraphQLEnumValuesDefinition enumValuesDefinition, TContext context) { await VisitAsync(enumValuesDefinition.Comments, context).ConfigureAwait(false); bool freshLine = enumValuesDefinition.Comments != null && Options.PrintComments; await context.WriteAsync(freshLine ? "{" : " {").ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); foreach (var enumValueDefinition in enumValuesDefinition.Items) { await VisitAsync(enumValueDefinition, context).ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); } await context.WriteAsync("}").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitInputObjectTypeDefinitionAsync(GraphQLInputObjectTypeDefinition inputObjectTypeDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(inputObjectTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeDefinition.Description, context).ConfigureAwait(false); await context.WriteAsync("input ").ConfigureAwait(false); await VisitAsync(inputObjectTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeDefinition.Fields, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitInputObjectTypeExtensionAsync(GraphQLInputObjectTypeExtension inputObjectTypeExtension, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(inputObjectTypeExtension.Comments, context).ConfigureAwait(false); await context.WriteAsync("extend input ").ConfigureAwait(false); await VisitAsync(inputObjectTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(inputObjectTypeExtension.Fields, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitInputValueDefinitionAsync(GraphQLInputValueDefinition inputValueDefinition, TContext context) { bool hasParent = TryPeekParent(context, out var parent); if (hasParent && parent is GraphQLArgumentsDefinition argsDef && argsDef.Items.IndexOf(inputValueDefinition) > 0) { await context.WriteAsync(inputValueDefinition.Description == null ? ", " : ",").ConfigureAwait(false); } await VisitAsync(inputValueDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(inputValueDefinition.Description, context).ConfigureAwait(false); // Indent only input fields since for arguments indentation is always handled in VisitCommentAsync/VisitDescriptionAsync if (hasParent && parent is GraphQLInputFieldsDefinition) await WriteIndentAsync(context).ConfigureAwait(false); await VisitAsync(inputValueDefinition.Name, context).ConfigureAwait(false); await context.WriteAsync(": ").ConfigureAwait(false); await VisitAsync(inputValueDefinition.Type, context).ConfigureAwait(false); if (inputValueDefinition.DefaultValue != null) { await context.WriteAsync(" = ").ConfigureAwait(false); await VisitAsync(inputValueDefinition.DefaultValue, context).ConfigureAwait(false); } await VisitAsync(inputValueDefinition.Directives, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitInputFieldsDefinitionAsync(GraphQLInputFieldsDefinition inputFieldsDefinition, TContext context) { await VisitAsync(inputFieldsDefinition.Comments, context).ConfigureAwait(false); bool freshLine = inputFieldsDefinition.Comments != null && Options.PrintComments; await context.WriteAsync(freshLine ? "{" : " {").ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); foreach (var inputFieldDefinition in inputFieldsDefinition.Items) { await VisitAsync(inputFieldDefinition, context).ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); } await context.WriteAsync("}").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitObjectTypeDefinitionAsync(GraphQLObjectTypeDefinition objectTypeDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(objectTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Description, context).ConfigureAwait(false); await context.WriteAsync("type ").ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Interfaces, context).ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(objectTypeDefinition.Fields, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitObjectTypeExtensionAsync(GraphQLObjectTypeExtension objectTypeExtension, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(objectTypeExtension.Comments, context).ConfigureAwait(false); await context.WriteAsync("extend type ").ConfigureAwait(false); await VisitAsync(objectTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(objectTypeExtension.Interfaces, context).ConfigureAwait(false); await VisitAsync(objectTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(objectTypeExtension.Fields, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitInterfaceTypeDefinitionAsync(GraphQLInterfaceTypeDefinition interfaceTypeDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(interfaceTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Description, context).ConfigureAwait(false); await context.WriteAsync("interface ").ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Interfaces, context).ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(interfaceTypeDefinition.Fields, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitInterfaceTypeExtensionAsync(GraphQLInterfaceTypeExtension interfaceTypeExtension, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(interfaceTypeExtension.Comments, context).ConfigureAwait(false); await context.WriteAsync("extend interface ").ConfigureAwait(false); await VisitAsync(interfaceTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(interfaceTypeExtension.Interfaces, context).ConfigureAwait(false); await VisitAsync(interfaceTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(interfaceTypeExtension.Fields, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitFieldDefinitionAsync(GraphQLFieldDefinition fieldDefinition, TContext context) { await VisitAsync(fieldDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(fieldDefinition.Description, context).ConfigureAwait(false); await WriteIndentAsync(context).ConfigureAwait(false); await VisitAsync(fieldDefinition.Name, context).ConfigureAwait(false); await VisitAsync(fieldDefinition.Arguments, context).ConfigureAwait(false); await context.WriteAsync(": ").ConfigureAwait(false); await VisitAsync(fieldDefinition.Type, context).ConfigureAwait(false); await VisitAsync(fieldDefinition.Directives, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitFieldsDefinitionAsync(GraphQLFieldsDefinition fieldsDefinition, TContext context) { await VisitAsync(fieldsDefinition.Comments, context).ConfigureAwait(false); bool freshLine = fieldsDefinition.Comments != null && Options.PrintComments; await context.WriteAsync(freshLine ? "{" : " {").ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); foreach (var fieldDefinition in fieldsDefinition) { await VisitAsync(fieldDefinition, context).ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); } await context.WriteAsync("}").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitSchemaDefinitionAsync(GraphQLSchemaDefinition schemaDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(schemaDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(schemaDefinition.Description, context).ConfigureAwait(false); await context.WriteAsync("schema").ConfigureAwait(false); await VisitAsync(schemaDefinition.Directives, context).ConfigureAwait(false); //bool freshLine = schemaDefinition.Comments != null && Options.PrintComments; always false await context.WriteAsync(/*freshLine? "{" : */" {").ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); if (schemaDefinition.OperationTypes.Count > 0) { for (int i = 0; i < schemaDefinition.OperationTypes.Count; ++i) { await VisitAsync(schemaDefinition.OperationTypes[i], context).ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); } } await context.WriteAsync("}").ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitRootOperationTypeDefinitionAsync(GraphQLRootOperationTypeDefinition rootOperationTypeDefinition, TContext context) { await VisitAsync(rootOperationTypeDefinition.Comments, context).ConfigureAwait(false); await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync(GetOperationType(rootOperationTypeDefinition.Operation)).ConfigureAwait(false); await context.WriteAsync(": ").ConfigureAwait(false); await VisitAsync(rootOperationTypeDefinition.Type, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitUnionTypeDefinitionAsync(GraphQLUnionTypeDefinition unionTypeDefinition, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(unionTypeDefinition.Comments, context).ConfigureAwait(false); await VisitAsync(unionTypeDefinition.Description, context).ConfigureAwait(false); await context.WriteAsync("union ").ConfigureAwait(false); await VisitAsync(unionTypeDefinition.Name, context).ConfigureAwait(false); await VisitAsync(unionTypeDefinition.Directives, context).ConfigureAwait(false); await VisitAsync(unionTypeDefinition.Types, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitUnionTypeExtensionAsync(GraphQLUnionTypeExtension unionTypeExtension, TContext context) { if (context.LastDefinitionPrinted) { await context.WriteDoubleLineAsync().ConfigureAwait(false); context.LastDefinitionPrinted = false; } await VisitAsync(unionTypeExtension.Comments, context).ConfigureAwait(false); await context.WriteAsync("extend union ").ConfigureAwait(false); await VisitAsync(unionTypeExtension.Name, context).ConfigureAwait(false); await VisitAsync(unionTypeExtension.Directives, context).ConfigureAwait(false); await VisitAsync(unionTypeExtension.Types, context).ConfigureAwait(false); context.LastDefinitionPrinted = true; } /// <inheritdoc/> protected override async ValueTask VisitUnionMemberTypesAsync(GraphQLUnionMemberTypes unionMemberTypes, TContext context) { await VisitAsync(unionMemberTypes.Comments, context).ConfigureAwait(false); if (unionMemberTypes.Comments == null || !Options.PrintComments) await context.WriteAsync(" ").ConfigureAwait(false); if (Options.EachUnionMemberOnNewLine) { await context.WriteAsync("=").ConfigureAwait(false); await context.WriteLineAsync().ConfigureAwait(false); for (int i = 0; i < unionMemberTypes.Items.Count; ++i) { await WriteIndentAsync(context).ConfigureAwait(false); await context.WriteAsync("| ").ConfigureAwait(false); await VisitAsync(unionMemberTypes.Items[i], context).ConfigureAwait(false); if (i < unionMemberTypes.Items.Count - 1) await context.WriteLineAsync().ConfigureAwait(false); } } else { await context.WriteAsync("= ").ConfigureAwait(false); for (int i = 0; i < unionMemberTypes.Items.Count; ++i) { await VisitAsync(unionMemberTypes.Items[i], context).ConfigureAwait(false); if (i < unionMemberTypes.Items.Count - 1) await context.WriteAsync(" | ").ConfigureAwait(false); } } } /// <inheritdoc/> protected override async ValueTask VisitDirectiveAsync(GraphQLDirective directive, TContext context) { await VisitAsync(directive.Comments, context).ConfigureAwait(false); await context.WriteAsync(TryPeekParent(context, out _) ? " @" : "@").ConfigureAwait(false); await VisitAsync(directive.Name, context).ConfigureAwait(false); await VisitAsync(directive.Arguments, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitDirectivesAsync(GraphQLDirectives directives, TContext context) { await VisitAsync(directives.Comments, context).ConfigureAwait(false); // Comment always null - see ParserContext.ParseDirectives foreach (var directive in directives.Items) await VisitAsync(directive, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitArgumentAsync(GraphQLArgument argument, TContext context) { await VisitAsync(argument.Comments, context).ConfigureAwait(false); await VisitAsync(argument.Name, context).ConfigureAwait(false); await context.WriteAsync(": ").ConfigureAwait(false); await VisitAsync(argument.Value, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitArgumentsDefinitionAsync(GraphQLArgumentsDefinition argumentsDefinition, TContext context) { await VisitAsync(argumentsDefinition.Comments, context).ConfigureAwait(false); await context.WriteAsync("(").ConfigureAwait(false); foreach (var argumentDefinition in argumentsDefinition.Items) await VisitAsync(argumentDefinition, context).ConfigureAwait(false); await context.WriteAsync(")").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitArgumentsAsync(GraphQLArguments arguments, TContext context) { await VisitAsync(arguments.Comments, context).ConfigureAwait(false); await context.WriteAsync("(").ConfigureAwait(false); for (int i = 0; i < arguments.Items.Count; ++i) { await VisitAsync(arguments.Items[i], context).ConfigureAwait(false); if (i < arguments.Items.Count - 1) await context.WriteAsync(", ").ConfigureAwait(false); } await context.WriteAsync(")").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitNonNullTypeAsync(GraphQLNonNullType nonNullType, TContext context) { await VisitAsync(nonNullType.Comments, context).ConfigureAwait(false); await VisitAsync(nonNullType.Type, context).ConfigureAwait(false); await context.WriteAsync("!").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitListTypeAsync(GraphQLListType listType, TContext context) { await VisitAsync(listType.Comments, context).ConfigureAwait(false); await context.WriteAsync("[").ConfigureAwait(false); await VisitAsync(listType.Type, context).ConfigureAwait(false); await context.WriteAsync("]").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitListValueAsync(GraphQLListValue listValue, TContext context) { await VisitAsync(listValue.Comments, context).ConfigureAwait(false); await context.WriteAsync("[").ConfigureAwait(false); if (listValue.Values?.Count > 0) { for (int i = 0; i < listValue.Values.Count; ++i) { await VisitAsync(listValue.Values[i], context).ConfigureAwait(false); if (i < listValue.Values.Count - 1) await context.WriteAsync(", ").ConfigureAwait(false); } } await context.WriteAsync("]").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitNullValueAsync(GraphQLNullValue nullValue, TContext context) { await VisitAsync(nullValue.Comments, context).ConfigureAwait(false); await context.WriteAsync("null").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitStringValueAsync(GraphQLStringValue stringValue, TContext context) { await VisitAsync(stringValue.Comments, context).ConfigureAwait(false); await WriteEncodedStringAsync(context, stringValue.Value); } /// <inheritdoc/> protected override async ValueTask VisitIntValueAsync(GraphQLIntValue intValue, TContext context) { await VisitAsync(intValue.Comments, context).ConfigureAwait(false); await context.WriteAsync(intValue.Value).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitFloatValueAsync(GraphQLFloatValue floatValue, TContext context) { await VisitAsync(floatValue.Comments, context).ConfigureAwait(false); await context.WriteAsync(floatValue.Value).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitEnumValueAsync(GraphQLEnumValue enumValue, TContext context) { await VisitAsync(enumValue.Comments, context).ConfigureAwait(false); await VisitAsync(enumValue.Name, context).ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitObjectValueAsync(GraphQLObjectValue objectValue, TContext context) { await VisitAsync(objectValue.Comments, context).ConfigureAwait(false); await context.WriteAsync("{").ConfigureAwait(false); if (objectValue.Fields?.Count > 0) { for (int i = 0; i < objectValue.Fields.Count; ++i) { await VisitAsync(objectValue.Fields[i], context).ConfigureAwait(false); if (i < objectValue.Fields.Count - 1) await context.WriteAsync(", ").ConfigureAwait(false); } } await context.WriteAsync("}").ConfigureAwait(false); } /// <inheritdoc/> protected override async ValueTask VisitObjectFieldAsync(GraphQLObjectField objectField, TContext context) { await VisitAsync(objectField.Comments, context).ConfigureAwait(false); await VisitAsync(objectField.Name, context).ConfigureAwait(false); await context.WriteAsync(": ").ConfigureAwait(false); await VisitAsync(objectField.Value, context).ConfigureAwait(false); } /// <inheritdoc/> protected override ValueTask VisitNamedTypeAsync(GraphQLNamedType namedType, TContext context) { return base.VisitNamedTypeAsync(namedType, context); } /// <inheritdoc/> public override async ValueTask VisitAsync(ASTNode? node, TContext context) { if (node == null) return; int prevLevel = context.IndentLevel; if (node is GraphQLField || node is GraphQLFieldDefinition || node is GraphQLEnumValueDefinition || node is GraphQLFragmentSpread || node is GraphQLInlineFragment || node is GraphQLRootOperationTypeDefinition) ++context.IndentLevel; if (node is GraphQLInputValueDefinition && (context.Parents.Count > 0 && context.Parents.Peek() is GraphQLInputFieldsDefinition)) ++context.IndentLevel; if (node is GraphQLDescription && TryPeekParent(context, out var parent) && parent is GraphQLArgumentsDefinition) ++context.IndentLevel; if (node is GraphQLDirectiveLocations && Options.EachDirectiveLocationOnNewLine) ++context.IndentLevel; if (node is GraphQLUnionMemberTypes && Options.EachUnionMemberOnNewLine) ++context.IndentLevel; context.Parents.Push(node); await base.VisitAsync(node, context).ConfigureAwait(false); context.Parents.Pop(); context.IndentLevel = prevLevel; } private static string GetOperationType(OperationType type) => type switch { OperationType.Query => "query", OperationType.Mutation => "mutation", OperationType.Subscription => "subscription", _ => throw new NotSupportedException($"Unknown operation {type}"), }; private static string GetDirectiveLocation(DirectiveLocation location) => location switch { // http://spec.graphql.org/October2021/#ExecutableDirectiveLocation DirectiveLocation.Query => "QUERY", DirectiveLocation.Mutation => "MUTATION", DirectiveLocation.Subscription => "SUBSCRIPTION", DirectiveLocation.Field => "FIELD", DirectiveLocation.FragmentDefinition => "FRAGMENT_DEFINITION", DirectiveLocation.FragmentSpread => "FRAGMENT_SPREAD", DirectiveLocation.InlineFragment => "INLINE_FRAGMENT", DirectiveLocation.VariableDefinition => "VARIABLE_DEFINITION", // http://spec.graphql.org/October2021/#TypeSystemDirectiveLocation DirectiveLocation.Schema => "SCHEMA", DirectiveLocation.Scalar => "SCALAR", DirectiveLocation.Object => "OBJECT", DirectiveLocation.FieldDefinition => "FIELD_DEFINITION", DirectiveLocation.ArgumentDefinition => "ARGUMENT_DEFINITION", DirectiveLocation.Interface => "INTERFACE", DirectiveLocation.Union => "UNION", DirectiveLocation.Enum => "ENUM", DirectiveLocation.EnumValue => "ENUM_VALUE", DirectiveLocation.InputObject => "INPUT_OBJECT", DirectiveLocation.InputFieldDefinition => "INPUT_FIELD_DEFINITION", _ => throw new NotSupportedException($"Unknown directive location {location}"), }; private static async ValueTask WriteIndentAsync(TContext context) { for (int i = 0; i < context.IndentLevel; ++i) await context.WriteAsync(" ").ConfigureAwait(false); } // Returns parent if called inside ViisitXXX i.e. after context.Parents.Push(node); // Returns grand-parent if called inside ViisitAsync i.e. before context.Parents.Push(node); private static bool TryPeekParent(TContext context, [NotNullWhen(true)] out ASTNode? node) { node = null; using var e = context.Parents.GetEnumerator(); for (int i = 0; i < 2; ++i) if (!e.MoveNext()) return false; node = e.Current; return true; } private static readonly string[] _hex32 = new[] { "\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", "\\u0008", "\\u0009", "\\u000A", "\\u000B", "\\u000C", "\\u000D", "\\u000E", "\\u000F", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001A", "\\u001B", "\\u001C", "\\u001D", "\\u001E", "\\u001F" }; // http://spec.graphql.org/October2021/#StringCharacter private static async ValueTask WriteEncodedStringAsync(TContext context, ROM value) { await context.WriteAsync("\"").ConfigureAwait(false); int startIndexOfNotEncodedString = 0; for (int i = 0; i < value.Span.Length; ++i) { char code = value.Span[i]; if (code < ' ') { if (startIndexOfNotEncodedString != i) await context.WriteAsync(value.Slice(startIndexOfNotEncodedString, i - startIndexOfNotEncodedString)).ConfigureAwait(false); startIndexOfNotEncodedString = i + 1; if (code == '\b') await context.WriteAsync("\\b").ConfigureAwait(false); else if (code == '\f') await context.WriteAsync("\\f").ConfigureAwait(false); else if (code == '\n') await context.WriteAsync("\\n").ConfigureAwait(false); else if (code == '\r') await context.WriteAsync("\\r").ConfigureAwait(false); else if (code == '\t') await context.WriteAsync("\\t").ConfigureAwait(false); else await context.WriteAsync(_hex32[code]).ConfigureAwait(false); } else if (code == '\\') { if (startIndexOfNotEncodedString != i) await context.WriteAsync(value.Slice(startIndexOfNotEncodedString, i - startIndexOfNotEncodedString)).ConfigureAwait(false); startIndexOfNotEncodedString = i + 1; await context.WriteAsync("\\\\").ConfigureAwait(false); } else if (code == '"') { if (startIndexOfNotEncodedString != i) await context.WriteAsync(value.Slice(startIndexOfNotEncodedString, i - startIndexOfNotEncodedString)).ConfigureAwait(false); startIndexOfNotEncodedString = i + 1; await context.WriteAsync("\\\"").ConfigureAwait(false); } } if (startIndexOfNotEncodedString != value.Span.Length) await context.WriteAsync(value.Slice(startIndexOfNotEncodedString, value.Span.Length - startIndexOfNotEncodedString)).ConfigureAwait(false); await context.WriteAsync("\"").ConfigureAwait(false); } } /// <inheritdoc/> public class SDLPrinter : SDLPrinter<SDLPrinter.DefaultPrintContext> { /// <summary> /// Default implementation for <see cref="IPrintContext"/>. /// </summary> public class DefaultPrintContext : IPrintContext { /// <summary> /// Creates an instance with the specified <see cref="TextWriter"/>. /// </summary> public DefaultPrintContext(TextWriter writer) { Writer = writer; } /// <inheritdoc/> public TextWriter Writer { get; } /// <inheritdoc/> public Stack<ASTNode> Parents { get; init; } = new Stack<ASTNode>(); /// <inheritdoc/> public CancellationToken CancellationToken { get; init; } /// <inheritdoc/> public int IndentLevel { get; set; } /// <inheritdoc/> public bool LastDefinitionPrinted { get; set; } } /// <inheritdoc/> public SDLPrinter() : base() { } /// <inheritdoc/> public SDLPrinter(SDLPrinterOptions options) : base(options) { } /// <inheritdoc cref="SDLPrinter{TContext}"/> public virtual ValueTask PrintAsync(ASTNode node, TextWriter writer, CancellationToken cancellationToken = default) { var context = new DefaultPrintContext(writer) { CancellationToken = cancellationToken, }; return VisitAsync(node, context); } } /// <summary> /// Options for <see cref="SDLPrinter{TContext}"/>. /// </summary> public class SDLPrinterOptions { /// <summary> /// Print comments into the output. /// </summary> public bool PrintComments { get; init; } /// <summary> /// Whether to print each directive location on its own line. /// </summary> public bool EachDirectiveLocationOnNewLine { get; init; } /// <summary> /// Whether to print each union member on its own line. /// </summary> public bool EachUnionMemberOnNewLine { get; init; } }
/******************************************************************** * * PropertyBag.cs * -------------- * Derived from PropertyBag.cs by Tony Allowatt * CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp * Last Update: 04/05/2005 * ********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; using System.Reflection; using CslaGenerator.Attributes; using CslaGenerator.Metadata; namespace CslaGenerator.Util.PropertyBags { /// <summary> /// Represents a collection of custom properties that can be selected into a /// PropertyGrid to provide functionality beyond that of the simple reflection /// normally used to query an object's properties. /// </summary> public class ConvertValuePropertyBag : ICustomTypeDescriptor { #region PropertySpecCollection class definition /// <summary> /// Encapsulates a collection of PropertySpec objects. /// </summary> [Serializable] public class PropertySpecCollection : IList { private readonly ArrayList _innerArray; /// <summary> /// Initializes a new instance of the PropertySpecCollection class. /// </summary> public PropertySpecCollection() { _innerArray = new ArrayList(); } /// <summary> /// Gets or sets the element at the specified index. /// In C#, this property is the indexer for the PropertySpecCollection class. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <value> /// The element at the specified index. /// </value> public PropertySpec this[int index] { get { return (PropertySpec) _innerArray[index]; } set { _innerArray[index] = value; } } #region IList Members /// <summary> /// Gets the number of elements in the PropertySpecCollection. /// </summary> /// <value> /// The number of elements contained in the PropertySpecCollection. /// </value> public int Count { get { return _innerArray.Count; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection has a fixed size. /// </summary> /// <value> /// true if the PropertySpecCollection has a fixed size; otherwise, false. /// </value> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection is read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value> /// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false. /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> /// <value> /// An object that can be used to synchronize access to the collection. /// </value> object ICollection.SyncRoot { get { return null; } } /// <summary> /// Removes all elements from the PropertySpecCollection. /// </summary> public void Clear() { _innerArray.Clear(); } /// <summary> /// Returns an enumerator that can iterate through the PropertySpecCollection. /// </summary> /// <returns>An IEnumerator for the entire PropertySpecCollection.</returns> public IEnumerator GetEnumerator() { return _innerArray.GetEnumerator(); } /// <summary> /// Removes the object at the specified index of the PropertySpecCollection. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> public void RemoveAt(int index) { _innerArray.RemoveAt(index); } #endregion /// <summary> /// Adds a PropertySpec to the end of the PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param> /// <returns>The PropertySpecCollection index at which the value has been added.</returns> public int Add(PropertySpec value) { int index = _innerArray.Add(value); return index; } /// <summary> /// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection. /// </summary> /// <param name="array">The PropertySpec array whose elements should be added to the end of the /// PropertySpecCollection.</param> public void AddRange(PropertySpec[] array) { _innerArray.AddRange(array); } /// <summary> /// Determines whether a PropertySpec is in the PropertySpecCollection. /// </summary> /// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate /// can be a null reference (Nothing in Visual Basic).</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(PropertySpec item) { return _innerArray.Contains(item); } /// <summary> /// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(string name) { foreach (PropertySpec spec in _innerArray) if (spec.Name == name) return true; return false; } /// <summary> /// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the /// beginning of the target array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from PropertySpecCollection. The Array must have zero-based indexing.</param> public void CopyTo(PropertySpec[] array) { _innerArray.CopyTo(array); } /// <summary> /// Copies the PropertySpecCollection or a portion of it to a one-dimensional array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from the collection.</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public void CopyTo(PropertySpec[] array, int index) { _innerArray.CopyTo(array, index); } /// <summary> /// Searches for the specified PropertySpec and returns the zero-based index of the first /// occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(PropertySpec value) { return _innerArray.IndexOf(value); } /// <summary> /// Searches for the PropertySpec with the specified name and returns the zero-based index of /// the first occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(string name) { int i = 0; foreach (PropertySpec spec in _innerArray) { //if (spec.Name == name) if (spec.TargetProperty == name) return i; i++; } return -1; } /// <summary> /// Inserts a PropertySpec object into the PropertySpecCollection at the specified index. /// </summary> /// <param name="index">The zero-based index at which value should be inserted.</param> /// <param name="value">The PropertySpec to insert.</param> public void Insert(int index, PropertySpec value) { _innerArray.Insert(index, value); } /// <summary> /// Removes the first occurrence of a specific object from the PropertySpecCollection. /// </summary> /// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(PropertySpec obj) { _innerArray.Remove(obj); } /// <summary> /// Removes the property with the specified name from the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(string name) { int index = IndexOf(name); RemoveAt(index); } /// <summary> /// Copies the elements of the PropertySpecCollection to a new PropertySpec array. /// </summary> /// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns> public PropertySpec[] ToArray() { return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec)); } #region Explicit interface implementations for ICollection and IList /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void ICollection.CopyTo(Array array, int index) { CopyTo((PropertySpec[]) array, index); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.Add(object value) { return Add((PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> bool IList.Contains(object obj) { return Contains((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (PropertySpec) value; } } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.IndexOf(object obj) { return IndexOf((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Insert(int index, object value) { Insert(index, (PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Remove(object value) { Remove((PropertySpec) value); } #endregion } #endregion #region PropertySpecDescriptor class definition private class PropertySpecDescriptor : PropertyDescriptor { private readonly ConvertValuePropertyBag _bag; private readonly PropertySpec _item; public PropertySpecDescriptor(PropertySpec item, ConvertValuePropertyBag bag, string name, Attribute[] attrs) : base(name, attrs) { _bag = bag; _item = item; } public override Type ComponentType { get { return _item.GetType(); } } public override bool IsReadOnly { get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); } } public override Type PropertyType { get { return Type.GetType(_item.TypeName); } } public override bool CanResetValue(object component) { if (_item.DefaultValue == null) return false; return !GetValue(component).Equals(_item.DefaultValue); } public override object GetValue(object component) { // Have the property bag raise an event to get the current value // of the property. var e = new PropertySpecEventArgs(_item, null); _bag.OnGetValue(e); return e.Value; } public override void ResetValue(object component) { SetValue(component, _item.DefaultValue); } public override void SetValue(object component, object value) { // Have the property bag raise an event to set the current value // of the property. var e = new PropertySpecEventArgs(_item, value); _bag.OnSetValue(e); } public override bool ShouldSerializeValue(object component) { object val = GetValue(component); if (_item.DefaultValue == null && val == null) return false; return !val.Equals(_item.DefaultValue); } } #endregion #region Properties and Events private readonly PropertySpecCollection _properties; private string _defaultProperty; private ConvertValueProperty[] _selectedObject; /// <summary> /// Initializes a new instance of the ConvertValuePropertyBag class. /// </summary> public ConvertValuePropertyBag() { _defaultProperty = null; _properties = new PropertySpecCollection(); } public ConvertValuePropertyBag(ConvertValueProperty obj) : this(new[] {obj}) { } public ConvertValuePropertyBag(ConvertValueProperty[] obj) { _defaultProperty = "BaseName"; _properties = new PropertySpecCollection(); _selectedObject = obj; InitPropertyBag(); } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public string DefaultProperty { get { return _defaultProperty; } set { _defaultProperty = value; } } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public ConvertValueProperty[] SelectedObject { get { return _selectedObject; } set { _selectedObject = value; InitPropertyBag(); } } /// <summary> /// Gets the collection of properties contained within this ConvertValuePropertyBag. /// </summary> public PropertySpecCollection Properties { get { return _properties; } } /// <summary> /// Occurs when a PropertyGrid requests the value of a property. /// </summary> public event PropertySpecEventHandler GetValue; /// <summary> /// Occurs when the user changes the value of a property in a PropertyGrid. /// </summary> public event PropertySpecEventHandler SetValue; /// <summary> /// Raises the GetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnGetValue(PropertySpecEventArgs e) { if (e.Value != null) GetValue(this, e); e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue); } /// <summary> /// Raises the SetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnSetValue(PropertySpecEventArgs e) { if (SetValue != null) SetValue(this, e); SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value); } #endregion #region Initialize Propertybag private void InitPropertyBag() { PropertyInfo pi; Type t = typeof (ConvertValueProperty); // _selectedObject.GetType(); PropertyInfo[] props = t.GetProperties(); // Display information for all properties. for (int i = 0; i < props.Length; i++) { pi = props[i]; object[] myAttributes = pi.GetCustomAttributes(true); string category = ""; string description = ""; bool isreadonly = false; bool isbrowsable = true; object defaultvalue = null; string userfriendlyname = ""; string typeconverter = ""; string designertypename = ""; string helptopic = ""; bool bindable = true; string editor = ""; for (int n = 0; n < myAttributes.Length; n++) { var a = (Attribute) myAttributes[n]; switch (a.GetType().ToString()) { case "System.ComponentModel.CategoryAttribute": category = ((CategoryAttribute) a).Category; break; case "System.ComponentModel.DescriptionAttribute": description = ((DescriptionAttribute) a).Description; break; case "System.ComponentModel.ReadOnlyAttribute": isreadonly = ((ReadOnlyAttribute) a).IsReadOnly; break; case "System.ComponentModel.BrowsableAttribute": isbrowsable = ((BrowsableAttribute) a).Browsable; break; case "System.ComponentModel.DefaultValueAttribute": defaultvalue = ((DefaultValueAttribute) a).Value; break; case "CslaGenerator.Attributes.UserFriendlyNameAttribute": userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName; break; case "CslaGenerator.Attributes.HelpTopicAttribute": helptopic = ((HelpTopicAttribute) a).HelpTopic; break; case "System.ComponentModel.TypeConverterAttribute": typeconverter = ((TypeConverterAttribute) a).ConverterTypeName; break; case "System.ComponentModel.DesignerAttribute": designertypename = ((DesignerAttribute) a).DesignerTypeName; break; case "System.ComponentModel.BindableAttribute": bindable = ((BindableAttribute) a).Bindable; break; case "System.ComponentModel.EditorAttribute": editor = ((EditorAttribute) a).EditorTypeName; break; } } userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : pi.Name; var types = new List<string>(); foreach (var obj in _selectedObject) { if (!types.Contains(obj.Name)) types.Add(obj.Name); } // here get rid of ComponentName and Parent bool isValidProperty = (pi.Name != "Properties" && pi.Name != "ComponentName" && pi.Name != "Parent"); if (isValidProperty && IsBrowsable(types.ToArray(), pi.Name)) { // CR added missing parameters //this.Properties.Add(new PropertySpec(userfriendlyname,pi.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, pi.Name,helptopic)); Properties.Add(new PropertySpec(userfriendlyname, pi.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, _selectedObject, pi.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable)); } } } #endregion private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>(); private PropertyInfo GetPropertyInfoCache(string propertyName) { if (!propertyInfoCache.ContainsKey(propertyName)) { propertyInfoCache.Add(propertyName, typeof (ConvertValueProperty).GetProperty(propertyName)); } return propertyInfoCache[propertyName]; } private bool IsEnumerable(PropertyInfo prop) { if (prop.PropertyType == typeof (string)) return false; Type[] interfaces = prop.PropertyType.GetInterfaces(); foreach (Type typ in interfaces) if (typ.Name.Contains("IEnumerable")) return true; return false; } #region IsBrowsable map objectType:propertyName -> true | false private bool IsBrowsable(string[] objectType, string propertyName) { try { /*if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None || GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.ObjectLevel) && (propertyName == "ReadRoles" || propertyName == "WriteRoles")) return false;*/ if (GeneratorController.Current.CurrentUnit.GenerationParams.TargetIsCsla4All && propertyName == "MarkDirtyOnChange") return false; if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName))) return false; return true; } catch //(Exception e) { Debug.WriteLine(objectType + ":" + propertyName); return true; } } #endregion #region Reflection functions private object GetField(Type t, string name, object target) { object obj = null; Type tx; FieldInfo[] fields; //fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); fields = target.GetType().GetFields(BindingFlags.Public); tx = target.GetType(); obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {}); return obj; } private object SetField(Type t, string name, object value, object target) { object obj; obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value}); return obj; } private bool SetProperty(object obj, string propertyName, object val) { try { // get a reference to the PropertyInfo, exit if no property with that // name PropertyInfo pi = typeof (ConvertValueProperty).GetProperty(propertyName); if (pi == null) return false; // convert the value to the expected type val = Convert.ChangeType(val, pi.PropertyType); // attempt the assignment foreach (ConvertValueProperty bo in (ConvertValueProperty[]) obj) pi.SetValue(bo, val, null); return true; } catch { return false; } } private object GetProperty(object obj, string propertyName, object defaultValue) { try { PropertyInfo pi = GetPropertyInfoCache(propertyName); if (!(pi == null)) { var objs = (ConvertValueProperty[]) obj; var valueList = new ArrayList(); foreach (ConvertValueProperty bo in objs) { object value = pi.GetValue(bo, null); if (!valueList.Contains(value)) { valueList.Add(value); } } switch (valueList.Count) { case 1: return valueList[0]; default: return string.Empty; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } // if property doesn't exist or throws return defaultValue; } #endregion #region ICustomTypeDescriptor explicit interface definitions // Most of the functions required by the ICustomTypeDescriptor are // merely pssed on to the default TypeDescriptor for this type, // which will do something appropriate. The exceptions are noted // below. AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { // This function searches the property list for the property // with the same name as the DefaultProperty specified, and // returns a property descriptor for it. If no property is // found that matches DefaultProperty, a null reference is // returned instead. PropertySpec propertySpec = null; if (_defaultProperty != null) { int index = _properties.IndexOf(_defaultProperty); propertySpec = _properties[index]; } if (propertySpec != null) return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null); return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { // Rather than passing this function on to the default TypeDescriptor, // which would return the actual properties of ConvertValuePropertyBag, I construct // a list here that contains property descriptors for the elements of the // Properties list in the bag. var props = new ArrayList(); foreach (PropertySpec property in _properties) { var attrs = new ArrayList(); // If a category, description, editor, or type converter are specified // in the PropertySpec, create attributes to define that relationship. if (property.Category != null) attrs.Add(new CategoryAttribute(property.Category)); if (property.Description != null) attrs.Add(new DescriptionAttribute(property.Description)); if (property.EditorTypeName != null) attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor))); if (property.ConverterTypeName != null) attrs.Add(new TypeConverterAttribute(property.ConverterTypeName)); // Additionally, append the custom attributes associated with the // PropertySpec, if any. if (property.Attributes != null) attrs.AddRange(property.Attributes); if (property.DefaultValue != null) attrs.Add(new DefaultValueAttribute(property.DefaultValue)); attrs.Add(new BrowsableAttribute(property.Browsable)); attrs.Add(new ReadOnlyAttribute(property.ReadOnly)); attrs.Add(new BindableAttribute(property.Bindable)); var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute)); // Create a new property descriptor for the property item, and add // it to the list. var pd = new PropertySpecDescriptor(property, this, property.Name, attrArray); props.Add(pd); } // Convert the list of PropertyDescriptors to a collection that the // ICustomTypeDescriptor can use, and return it. var propArray = (PropertyDescriptor[]) props.ToArray( typeof (PropertyDescriptor)); return new PropertyDescriptorCollection(propArray); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion } }
/* * AnimatedModelProcessor.cs * Copyright (c) 2006 David Astle * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Processors; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics.PackedVector; using System.IO; using System.Collections; using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler; using Microsoft.Xna.Framework.Content; using System.Globalization; using System.Xml; using System.Collections.ObjectModel; using System.ComponentModel; namespace FlatRedBall.Graphics.Model.Animation.Content { /// <summary> /// Processes a NodeContent object that was imported by SkinnedModelImporter /// and attaches animation data to its tag /// </summary> [ContentProcessor(DisplayName="Model - Animation Library")] public class AnimatedModelProcessor : ModelProcessor { private ContentProcessorContext context; // stores all animations for the model private AnimationContentDictionary animations = new AnimationContentDictionary(); private NodeContent input; private SkinInfoContentCollection[] skinInfo = null; private bool modelSplit = false; private BoneIndexer[] indexers = null; List<Matrix> absoluteMeshTransforms = null; List<MeshContent> meshes = new List<MeshContent>(); private int numMeshes = 0; const int maximumNumberOfPCBones = 56; const int maximumNumberOfWiiBones = 40; /// <summary>Processes a SkinnedModelImporter NodeContent root</summary> /// <param name="input">The root of the X file tree</param> /// <param name="context">The context for this processor</param> /// <returns>A model with animation data on its tag</returns> public override ModelContent Process(NodeContent input, ContentProcessorContext context) { //try //{ ModelSplitter splitter; if (context.TargetPlatform != TargetPlatform.Xbox360) { splitter = new ModelSplitter(input, maximumNumberOfPCBones); } else { splitter = new ModelSplitter(input, maximumNumberOfWiiBones); } modelSplit = splitter.Split(); splitter = null; this.input = input; this.context = context; FindMeshes(input); indexers = new BoneIndexer[numMeshes]; for (int i = 0; i < indexers.Length; i++) { indexers[i] = new BoneIndexer(); } foreach (MeshContent meshContent in meshes) { CreatePaletteIndices(meshContent); } // Get the process model minus the animation data ModelContent c = base.Process(input, context); if (!modelSplit && input.OpaqueData.ContainsKey("AbsoluteMeshTransforms")) { absoluteMeshTransforms = (List<Matrix>)input.OpaqueData["AbsoluteMeshTransforms"]; } else { foreach (MeshContent mesh in meshes) { if (!ValidateMeshSkeleton(mesh)) { context.Logger.LogWarning(null, mesh.Identity, "Warning: Mesh found that has a parent that exists as " + "one of the bones in the skeleton attached to the mesh. Change the mesh " + "skeleton structure or use X - File Animation Library importer if transforms are incorrect."); } } } Dictionary<string, object> dict = new Dictionary<string, object>(); // Attach the animation and skinning data to the models tag FindAnimations(input); // Test to see if any animations have zero duration foreach (AnimationContent anim in animations.Values) { string errorMsg = "One or more AnimationContent objects have an extremely small duration. If the animation " + "was intended to last more than one frame, please add \n AnimTicksPerSecond \n{0} \nY; \n{1}\n to your .X " + "file, where Y is a positive integer."; if (anim.Duration.Ticks < ContentUtil.TICKS_PER_60FPS) { context.Logger.LogWarning("", anim.Identity, errorMsg, "{", "}"); break; } } XmlDocument xmlDoc = ReadAnimationXML(input); if (xmlDoc != null) { SubdivideAnimations(animations, xmlDoc); } AnimationContentDictionary processedAnims = new AnimationContentDictionary(); try { foreach (KeyValuePair<string, AnimationContent> animKey in animations) { AnimationContent processedAnim = ProcessAnimation(animKey.Value); processedAnims.Add(animKey.Key, processedAnim); } dict.Add("Animations", processedAnims); } catch { throw new Exception("Error processing animations."); } foreach (ModelMeshContent meshContent in c.Meshes) ReplaceBasicEffects(meshContent); skinInfo = ProcessSkinInfo(c); dict.Add("SkinInfo", skinInfo); c.Tag = dict; return c; //} //catch (Exception e) //{ // System.IO.File.WriteAllText(@"AnimatedModelProcessorError.txt", e.Message); // throw e; //} return null; } private void FindMeshes (NodeContent root) { if (root is MeshContent) { MeshContent mesh = (MeshContent)root; mesh.OpaqueData.Add("MeshIndex", numMeshes); numMeshes++; meshes.Add(mesh); } foreach (NodeContent child in root.Children) FindMeshes(child); } private void CreatePaletteIndices(MeshContent mesh) { foreach (GeometryContent meshPart in mesh.Geometry) { int meshIndex = (int)mesh.OpaqueData["MeshIndex"]; BoneIndexer indexer = indexers[meshIndex]; foreach (VertexChannel channel in meshPart.Vertices.Channels) { if (channel.Name == VertexChannelNames.Weights()) { VertexChannel<BoneWeightCollection> vc = (VertexChannel<BoneWeightCollection>)channel; foreach (BoneWeightCollection boneWeights in vc) { foreach (BoneWeight weight in boneWeights) { indexer.GetBoneIndex(weight.BoneName); } } } } } } // returns true if the model contains meshes that have a parent bone as a child of // a bone in the skeleton attached to the mesh. private bool ValidateMeshSkeleton (MeshContent meshContent) { List<string> meshParentHierarchy = new List<string>(); int meshIndex = (int)meshContent.OpaqueData["MeshIndex"]; BoneIndexer indexer = indexers[meshIndex]; if (meshContent.Parent != null && indexer.SkinnedBoneNames.Contains(meshContent.Parent.Name)) { // Warning return false; } // skeleton is fine return true; } private void CalculateAbsoluteTransforms(ModelBoneContent bone, Matrix[] transforms) { if (bone.Parent == null) transforms[bone.Index] = bone.Transform; else { transforms[bone.Index] = bone.Transform * transforms[bone.Parent.Index]; } foreach (ModelBoneContent child in bone.Children) CalculateAbsoluteTransforms(child, transforms); } private SkinInfoContentCollection[] ProcessSkinInfo(ModelContent model) { SkinInfoContentCollection[] info = new SkinInfoContentCollection[model.Meshes.Count]; Dictionary<string, int> boneDict = new Dictionary<string,int>(); //if (model.Bones.Count > maximumNumberOfPCBones) //{ // throw new Exception("There are too many bones! You have " + model.Bones.Count + " and you can only have " + maximumNumberOfPCBones); //} foreach (ModelBoneContent b in model.Bones) { if (b.Name != null && !boneDict.ContainsKey(b.Name)) boneDict.Add(b.Name, b.Index); } for (int i = 0; i < info.Length; i++) { info[i] = new SkinInfoContentCollection(); BoneIndexer indexer = indexers[i]; ReadOnlyCollection<string> skinnedBoneNames = indexer.SkinnedBoneNames; Matrix[] absoluteTransforms = new Matrix[model.Bones.Count]; CalculateAbsoluteTransforms(model.Bones[0], absoluteTransforms); Matrix absoluteMeshTransform; if (absoluteMeshTransforms == null) { absoluteMeshTransform = absoluteTransforms[model.Meshes[i].ParentBone.Index]; } else { absoluteMeshTransform = absoluteMeshTransforms[i]; } for (int j = 0; j < skinnedBoneNames.Count; j++) { string name = skinnedBoneNames[j]; SkinInfoContent content = new SkinInfoContent(); try { content.BoneIndex = boneDict[name]; } catch (KeyNotFoundException knfe) { string error = "Could not find a bone by the name of " + name + ". This is skinned bone index " + j + "."; error += "\nThere are " + skinnedBoneNames.Count + " skinned bones:"; for (int boneIndex = 0; boneIndex < skinnedBoneNames.Count; boneIndex++) { error += "\n " + skinnedBoneNames[boneIndex]; } error += "\nThere are " + model.Bones.Count + " bones:"; foreach (ModelBoneContent b in model.Bones) { error += "\n " + b.Name; } throw new KeyNotFoundException(error); } content.PaletteIndex = indexer.GetBoneIndex(name); content.InverseBindPoseTransform = absoluteMeshTransform * Matrix.Invert(absoluteTransforms[boneDict[name]]); content.BoneName = name; info[i].Add(content); } } return info; } /// <summary> /// Gets the names of the bones that should be used by the palette. /// </summary> protected ReadOnlyCollection<SkinInfoContentCollection> SkinnedBones { get { return new ReadOnlyCollection<SkinInfoContentCollection>(skinInfo); } } /// <summary> /// Gets the processor context. /// </summary> protected ContentProcessorContext ProcessorContext { get { return context; } } /// <summary> /// Called when an AnimationContent is processed. /// </summary> /// <param name="animation">The AnimationContent to be processed.</param> /// <returns>The processed AnimationContent.</returns> protected virtual AnimationContent ProcessAnimation(AnimationContent animation) { // M * M = F // AnimationProcessor ap = new AnimationProcessor(); AnimationContent newAnim = ap.Interpolate(animation); newAnim.Name = animation.Name; return newAnim; ; } /// <summary> /// Called when an XML document is read that specifies how animations /// should be split. /// </summary> /// <param name="animDict">The dictionary of animation name/AnimationContent /// pairs. </param> /// <param name="doc">The Xml document that contains info on how to split /// the animations.</param> protected virtual void SubdivideAnimations( AnimationContentDictionary animDict, XmlDocument doc) { string[] animNames = new string[animDict.Keys.Count]; animDict.Keys.CopyTo(animNames, 0); if (animNames.Length == 0) return; // Traverse each xml node that represents an animation to be subdivided foreach (XmlNode node in doc) { XmlElement child = node as XmlElement; if (child == null || child.Name != "animation") continue; string animName = null; if (child["name"] != null) { // The name of the animation to be split animName = child["name"].InnerText; } else if (child["index"] != null) { animName = animNames[int.Parse(child["index"].InnerText)]; } else { animName = animNames[0]; } // If the tickspersecond node is filled, use that to calculate seconds per tick double animTicksPerSecond = 1.0, secondsPerTick = 0; try { if (child["tickspersecond"] != null) { animTicksPerSecond = double.Parse(child["tickspersecond"].InnerText); } } catch { throw new Exception("Error parsing tickspersecond in xml file."); } if (animTicksPerSecond <= 0) throw new InvalidDataException("AnimTicksPerSecond in XML file must be " + "a positive number."); secondsPerTick = 1.0 / animTicksPerSecond; AnimationContent anim = null; // Get the animation and remove it from the dict // Check to see if the animation specified in the xml file exists try { anim = animDict[animName]; } catch { throw new Exception("Animation named " + animName + " specified in XML file does not exist in model."); } animDict.Remove(anim.Name); // Get the list of new animations XmlNodeList subAnimations = child.GetElementsByTagName("animationsubset"); foreach (XmlElement subAnim in subAnimations) { // Create the new sub animation AnimationContent newAnim = new AnimationContent(); XmlElement subAnimNameElement = subAnim["name"]; if (subAnimNameElement != null) newAnim.Name = subAnimNameElement.InnerText; // If a starttime node exists, use that to get the start time long startTime, endTime; if (subAnim["starttime"] != null) { try { startTime = TimeSpan.FromSeconds(double.Parse(subAnim["starttime"].InnerText)).Ticks; } catch { throw new Exception("Error parsing starttime node in XML file. Node inner text " + "must be a non negative number."); } } else if (subAnim["startframe"] != null)// else use the secondspertick combined with the startframe node value { try { double seconds = double.Parse(subAnim["startframe"].InnerText) * secondsPerTick; startTime = TimeSpan.FromSeconds( seconds).Ticks; } catch { throw new Exception("Error parsing startframe node in XML file. Node inner text " + "must be a non negative number."); } } else throw new Exception("Sub animation in XML file must have either a starttime or startframe node."); // Same with endtime/endframe if (subAnim["endtime"] != null) { try { endTime = TimeSpan.FromSeconds(double.Parse(subAnim["endtime"].InnerText)).Ticks; } catch { throw new Exception("Error parsing endtime node in XML file. Node inner text " + "must be a non negative number."); } } else if (subAnim["endframe"] != null) { try { double seconds = double.Parse(subAnim["endframe"].InnerText) * secondsPerTick; endTime = TimeSpan.FromSeconds( seconds).Ticks; } catch { throw new Exception("Error parsing endframe node in XML file. Node inner text " + "must be a non negative number."); } } else throw new Exception("Sub animation in XML file must have either an endtime or endframe node."); if (endTime < startTime) throw new Exception("Start time must be <= end time in XML file."); // Now that we have the start and end times, we associate them with // start and end indices for each animation track/channel foreach (KeyValuePair<string, AnimationChannel> k in anim.Channels) { // The current difference between the start time and the // time at the current index long currentStartDiff; // The current difference between the end time and the // time at the current index long currentEndDiff; // The difference between the start time and the time // at the start index long bestStartDiff=long.MaxValue; // The difference between the end time and the time at // the end index long bestEndDiff=long.MaxValue; // The start and end indices int startIndex = -1; int endIndex = -1; // Create a new channel and reference the old channel AnimationChannel newChan = new AnimationChannel(); AnimationChannel oldChan = k.Value; // Iterate through the keyframes in the channel for (int i = 0; i < oldChan.Count; i++) { // Update the startIndex, endIndex, bestStartDiff, // and bestEndDiff long ticks = oldChan[i].Time.Ticks; currentStartDiff = System.Math.Abs(startTime - ticks); currentEndDiff = System.Math.Abs(endTime - ticks); if (startIndex == -1 || currentStartDiff<bestStartDiff) { startIndex = i; bestStartDiff = currentStartDiff; } if (endIndex == -1 || currentEndDiff<bestEndDiff) { endIndex = i; bestEndDiff = currentEndDiff; } } // Now we have our start and end index for the channel for (int i = startIndex; i <= endIndex; i++) { AnimationKeyframe frame = oldChan[i]; long time; // Clamp the time so that it can't be less than the // start time if (frame.Time.Ticks < startTime) time = 0; // Clamp the time so that it can't be greater than the // end time else if (frame.Time.Ticks > endTime) time = endTime - startTime; else // Else get the time time = frame.Time.Ticks - startTime; // Finally... create the new keyframe and add it to the new channel AnimationKeyframe keyframe = new AnimationKeyframe( TimeSpan.FromTicks(time), frame.Transform); newChan.Add(keyframe); } // Add the channel and update the animation duration based on the // length of the animation track. newAnim.Channels.Add(k.Key, newChan); if (newChan[newChan.Count - 1].Time > newAnim.Duration) newAnim.Duration = newChan[newChan.Count - 1].Time; } try { // Add the subdived animation to the dictionary. animDict.Add(newAnim.Name, newAnim); } catch { throw new Exception("Attempt to add an animation when one by the same name already exists. " + "Name: " + newAnim.Name); } } } } // Reads the XML document associated with the model if it exists. private XmlDocument ReadAnimationXML(NodeContent root) { XmlDocument doc = null; string filePath = Path.GetFullPath(root.Identity.SourceFilename); string fileName = Path.GetFileName(filePath); fileName = Path.GetDirectoryName(filePath); if (fileName!="") fileName += "\\"; fileName += System.IO.Path.GetFileNameWithoutExtension(filePath) + "animation.xml"; bool animXMLExists = File.Exists(fileName); if (animXMLExists) { doc = new XmlDocument(); doc.Load(fileName); } return doc; } /// <summary> /// Called when a basic effect is encountered and potentially replaced by /// BasicPaletteEffect (if not overridden). This is called afer effects have been processed. /// </summary> /// <param name="skinningType">The the skinning type of the meshpart.</param> /// <param name="meshPart">The MeshPart that contains the BasicMaterialContent.</param> protected virtual void ReplaceBasicEffect(SkinningType skinningType, ModelMeshPartContent meshPart) { BasicMaterialContent basic = meshPart.Material as BasicMaterialContent; if (basic != null) { // Create a new PaletteSourceCode object and set its palette size // based on the platform since xbox has fewer registers. PaletteSourceCode source; if (context.TargetPlatform != TargetPlatform.Xbox360) { source = new PaletteSourceCode(56); } else { source = new PaletteSourceCode(40); } // Process the material and set the meshPart material to the new // material. PaletteInfoProcessor processor = new PaletteInfoProcessor(); meshPart.Material = processor.Process( new PaletteInfo(source.SourceCode4BonesPerVertex, source.PALETTE_SIZE, basic), context); } } // Go through the modelmeshes and replace all basic effects for skinned models // with BasicPaletteEffect. private void ReplaceBasicEffects(ModelMeshContent input) { foreach (ModelMeshPartContent part in input.MeshParts) { #if XNA4 SkinningType skinType = ContentUtil.GetSkinningType(part.VertexBuffer.VertexDeclaration.VertexElements); #else SkinningType skinType = ContentUtil.GetSkinningType(part.GetVertexDeclaration()); #endif if (skinType != SkinningType.None) { ReplaceBasicEffect(skinType, part); } } } /// <summary> /// Searches through the NodeContent tree for all animations and puts them in /// one AnimationContentDictionary /// </summary> /// <param name="node">The root of the tree</param> private void FindAnimations(NodeContent node) { foreach (KeyValuePair<string, AnimationContent> k in node.Animations) { if (animations.ContainsKey(k.Key)) { foreach (KeyValuePair<string, AnimationChannel> c in k.Value.Channels) { animations[k.Key].Channels.Add(c.Key, c.Value); } } else { animations.Add(k.Key, k.Value); } } foreach (NodeContent child in node.Children) FindAnimations(child); } /// <summary> /// Go through the vertex channels in the geometry and replace the /// BoneWeightCollection objects with weight and index channels. /// </summary> /// <param name="geometry">The geometry to process.</param> /// <param name="vertexChannelIndex">The index of the vertex channel to process.</param> /// <param name="context">The processor context.</param> protected override void ProcessVertexChannel(GeometryContent geometry, int vertexChannelIndex, ContentProcessorContext context) { bool boneCollectionsWithZeroWeights = false; if (geometry.Vertices.Channels[vertexChannelIndex].Name == VertexChannelNames.Weights()) { int meshIndex = (int)geometry.Parent.OpaqueData["MeshIndex"]; BoneIndexer indexer = indexers[meshIndex]; // Skin channels are passed in from importers as BoneWeightCollection objects VertexChannel<BoneWeightCollection> vc = (VertexChannel<BoneWeightCollection>) geometry.Vertices.Channels[vertexChannelIndex]; int maxBonesPerVertex = 0; for (int i = 0; i < vc.Count; i++) { int count = vc[i].Count; if (count > maxBonesPerVertex) maxBonesPerVertex = count; } // Add weights as colors (Converts well to 4 floats) // and indices as packed 4byte vectors. Color[] weightsToAdd = new Color[vc.Count]; Byte4[] indicesToAdd = new Byte4[vc.Count]; // Go through the BoneWeightCollections and create a new // weightsToAdd and indicesToAdd array for each BoneWeightCollection. for (int i = 0; i < vc.Count; i++) { BoneWeightCollection bwc = vc[i]; if (bwc.Count == 0) { boneCollectionsWithZeroWeights = true; continue; } bwc.NormalizeWeights(4); int count = bwc.Count; if (count>maxBonesPerVertex) maxBonesPerVertex = count; // Add the appropriate bone indices based on the bone names in the // BoneWeightCollection Vector4 bi = new Vector4(); bi.X = count > 0 ? indexer.GetBoneIndex(bwc[0].BoneName) : (byte)0; bi.Y = count > 1 ? indexer.GetBoneIndex(bwc[1].BoneName) : (byte)0; bi.Z = count > 2 ? indexer.GetBoneIndex(bwc[2].BoneName) : (byte)0; bi.W = count > 3 ? indexer.GetBoneIndex(bwc[3].BoneName) : (byte)0; indicesToAdd[i] = new Byte4(bi); Vector4 bw = new Vector4(); bw.X = count > 0 ? bwc[0].Weight : 0; bw.Y = count > 1 ? bwc[1].Weight : 0; bw.Z = count > 2 ? bwc[2].Weight : 0; bw.W = count > 3 ? bwc[3].Weight : 0; weightsToAdd[i] = new Color(bw); } // Remove the old BoneWeightCollection channel geometry.Vertices.Channels.Remove(vc); // Add the new channels geometry.Vertices.Channels.Add<Byte4>(VertexElementUsage.BlendIndices.ToString(), indicesToAdd); geometry.Vertices.Channels.Add<Color>(VertexElementUsage.BlendWeight.ToString(), weightsToAdd); } else { // No skinning info, so we let the base class process the channel base.ProcessVertexChannel(geometry, vertexChannelIndex, context); } if (boneCollectionsWithZeroWeights) context.Logger.LogWarning("", geometry.Identity, "BonesWeightCollections with zero weights found in geometry."); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Management.Automation; using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { /// <summary> /// The valid values for the -PathType parameter for test-path /// </summary> public enum TestPathType { /// <summary> /// If the item at the path exists, true will be returned. /// </summary> Any, /// <summary> /// If the item at the path exists and is a container, true will be returned. /// </summary> Container, /// <summary> /// If the item at the path exists and is not a container, true will be returned. /// </summary> Leaf } /// <summary> /// A command to determine if an item exists at a specified path /// </summary> [Cmdlet(VerbsDiagnostic.Test, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113418")] [OutputType(typeof(bool))] public class TestPathCommand : CoreCommandWithCredentialsBase { #region Parameters /// <summary> /// Gets or sets the path parameter to the command /// </summary> [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { return _paths; } set { _paths = value; } } /// <summary> /// Gets or sets the literal path parameter to the command /// </summary> [Parameter(ParameterSetName = "LiteralPath", Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { return _paths; } set { base.SuppressWildcardExpansion = true; _paths = value; } } /// <summary> /// Gets or sets the filter property /// </summary> [Parameter] public override string Filter { get { return base.Filter; } set { base.Filter = value; } } /// <summary> /// Gets or sets the include property /// </summary> [Parameter] public override string[] Include { get { return base.Include; } set { base.Include = value; } } /// <summary> /// Gets or sets the exclude property /// </summary> [Parameter] public override string[] Exclude { get { return base.Exclude; } set { base.Exclude = value; } } /// <summary> /// Gets or sets the isContainer property /// </summary> [Parameter] [Alias("Type")] public TestPathType PathType { get; set; } = TestPathType.Any; /// <summary> /// Gets or sets the IsValid parameter /// </summary> [Parameter] public SwitchParameter IsValid { get; set; } = new SwitchParameter(); /// <summary> /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets /// that require dynamic parameters should override this method and return the /// dynamic parameter object. /// </summary> /// /// <param name="context"> /// The context under which the command is running. /// </param> /// /// <returns> /// An object representing the dynamic parameters for the cmdlet or null if there /// are none. /// </returns> /// internal override object GetDynamicParameters(CmdletProviderContext context) { object result = null; if (this.PathType == TestPathType.Any && !IsValid) { if (Path != null && Path.Length > 0) { result = InvokeProvider.Item.ItemExistsDynamicParameters(Path[0], context); } else { result = InvokeProvider.Item.ItemExistsDynamicParameters(".", context); } } return result; } // GetDynamicParameters #endregion Parameters #region parameter data /// <summary> /// The path to the item to ping /// </summary> private string[] _paths; #endregion parameter data #region Command code /// <summary> /// Determines if an item at the specified path exists. /// </summary> protected override void ProcessRecord() { CmdletProviderContext currentContext = CmdletProviderContext; foreach (string path in _paths) { bool result = false; try { if (IsValid) { result = SessionState.Path.IsValid(path, currentContext); } else { if (this.PathType == TestPathType.Container) { result = InvokeProvider.Item.IsContainer(path, currentContext); } else if (this.PathType == TestPathType.Leaf) { result = InvokeProvider.Item.Exists(path, currentContext) && !InvokeProvider.Item.IsContainer(path, currentContext); } else { result = InvokeProvider.Item.Exists(path, currentContext); } } } // Any of the known exceptions means the path does not exist. catch (PSNotSupportedException) { } catch (DriveNotFoundException) { } catch (ProviderNotFoundException) { } catch (ItemNotFoundException) { } WriteObject(result); } } // ProcessRecord #endregion Command code } // PingPathCommand } // namespace Microsoft.PowerShell.Commands
using AutoMapper; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Commands.Compute.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute.Models; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Newtonsoft.Json; using System; using System.Collections; using System.Globalization; using System.IO; using System.Management.Automation; using System.Text.RegularExpressions; namespace Microsoft.Azure.Commands.Compute.Extension.DSC { [Cmdlet( VerbsCommon.Set, ProfileNouns.VirtualMachineDscExtension, SupportsShouldProcess = true, DefaultParameterSetName = AzureBlobDscExtensionParamSet)] [OutputType(typeof(PSAzureOperationResponse))] public class SetAzureVMDscExtensionCommand : VirtualMachineExtensionBaseCmdlet { protected const string AzureBlobDscExtensionParamSet = "AzureBlobDscExtension"; [Parameter( Mandatory = true, Position = 2, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the resource group that contains the virtual machine.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( Mandatory = true, Position = 3, ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the virtual machine where dsc extension handler would be installed.")] [ValidateNotNullOrEmpty] public string VMName { get; set; } [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the ARM resource that represents the extension. This is defaulted to 'Microsoft.Powershell.DSC'")] [ValidateNotNullOrEmpty] public string Name { get; set; } /// <summary> /// The name of the configuration archive that was previously uploaded by /// Publish-AzureRmVMDSCConfiguration. This parameter must specify only the name /// of the file, without any path. /// A null value or empty string indicate that the VM extension should install DSC, /// but not start any configuration /// </summary> [Alias("ConfigurationArchiveBlob")] [Parameter( Mandatory = true, Position = 5, ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The name of the configuration file that was previously uploaded by Publish-AzureRmVMDSCConfiguration")] [AllowEmptyString] [AllowNull] public string ArchiveBlobName { get; set; } /// <summary> /// The Azure Storage Account name used to upload the configuration script to the container specified by ArchiveContainerName. /// </summary> [Alias("StorageAccountName")] [Parameter( Mandatory = true, Position = 4, ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The Azure Storage Account name used to download the ArchiveBlobName")] [ValidateNotNullOrEmpty] public String ArchiveStorageAccountName { get; set; } [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The name of the resource group that contains the storage account containing the configuration archive. " + "This param is optional if storage account and virtual machine both exists in the same resource group name, " + "specified by ResourceGroupName param.")] [ValidateNotNullOrEmpty] public string ArchiveResourceGroupName { get; set; } /// <summary> /// The DNS endpoint suffix for all storage services, e.g. "core.windows.net". /// </summary> [Alias("StorageEndpointSuffix")] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The Storage Endpoint Suffix.")] [ValidateNotNullOrEmpty] public string ArchiveStorageEndpointSuffix { get; set; } /// <summary> /// Name of the Azure Storage Container where the configuration script is located. /// </summary> [Alias("ContainerName")] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "Name of the Azure Storage Container where the configuration archive is located")] [ValidateNotNullOrEmpty] public string ArchiveContainerName { get; set; } /// <summary> /// Name of the configuration that will be invoked by the DSC Extension. The value of this parameter should be the name of one of the configurations /// contained within the file specified by ArchiveBlobName. /// /// If omitted, this parameter will default to the name of the file given by the ArchiveBlobName parameter, excluding any extension, for example if /// ArchiveBlobName is "SalesWebSite.ps1", the default value for ConfigurationName will be "SalesWebSite". /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the configuration that will be invoked by the DSC Extension")] [ValidateNotNullOrEmpty] public string ConfigurationName { get; set; } /// <summary> /// A hashtable specifying the arguments to the ConfigurationFunction. The keys /// correspond to the parameter names and the values to the parameter values. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable specifying the arguments to the ConfigurationFunction")] [ValidateNotNullOrEmpty] public Hashtable ConfigurationArgument { get; set; } /// <summary> /// Path to a .psd1 file that specifies the data for the Configuration. This /// file must contain a hashtable with the items described in /// http://technet.microsoft.com/en-us/library/dn249925.aspx. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration")] [ValidateNotNullOrEmpty] public string ConfigurationData { get; set; } /// <summary> /// The specific version of the DSC extension that Set-AzureRmVMDSCExtension will /// apply the settings to. /// </summary> [Alias("HandlerVersion")] [Parameter( Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true, HelpMessage = "The version of the DSC extension that Set-AzureRmVMDSCExtension will apply the settings to. " + "Allowed format N.N")] [ValidateNotNullOrEmpty] public string Version { get; set; } /// <summary> /// By default Set-AzureRmVMDscExtension will not overwrite any existing blobs. Use -Force to overwrite them. /// </summary> [Parameter( HelpMessage = "Use this parameter to overwrite any existing blobs")] public SwitchParameter Force { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Location of the resource.")] [ValidateNotNullOrEmpty] public string Location { get; set; } /// <summary> /// We install the extension handler version specified by the version param. By default extension handler is not autoupdated. /// Use -AutoUpdate to enable auto update of extension handler to the latest version as and when it is available. /// </summary> [Parameter( HelpMessage = "Extension handler gets auto updated to the latest version if this switch is present.")] public SwitchParameter AutoUpdate { get; set; } /// <summary> /// Specifies the version of the Windows Management Framework (WMF) to install /// on the VM. /// /// The DSC Azure Extension depends on DSC features that are only available in /// the WMF updates. This parameter specifies which version of the update to /// install on the VM. The possible values are "4.0","5.0" ,"5.1" and "latest". /// /// A value of "4.0" will install WMF 4.0 Update packages /// (https://support.microsoft.com/en-us/kb/3119938) on Windows 8.1 or Windows Server /// 2012 R2, or /// (https://support.microsoft.com/en-us/kb/3109118) on Windows Server 2008 R2 /// and on other versions of Windows if newer version is not already installed. /// /// A value of "5.0" will install the latest release of WMF 5.0 /// (https://www.microsoft.com/en-us/download/details.aspx?id=50395). /// /// A value of "5.1" will install the WMF 5.1 /// (https://www.microsoft.com/en-us/download/details.aspx?id=54616). /// /// A value of "latest" will install the latest WMF, currently WMF 5.1 /// /// The default value is "latest" /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateSetAttribute(new[] {"4.0", "5.0", "5.1", "latest"})] public string WmfVersion { get; set; } /// <summary> /// The Extension Data Collection state /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, HelpMessage = "Enables or Disables Data Collection in the extension. It is enabled if it is not specified. " + "The value is persisted in the extension between calls.") ] [ValidateSet("Enable", "Disable")] [AllowNull] public string DataCollection { get; set; } //Private Variables private const string VersionRegexExpr = @"^(([0-9])\.)\d+$"; /// <summary> /// Credentials used to access Azure Storage /// </summary> private StorageCredentials _storageCredentials; public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ValidateParameters(); CreateConfiguration(); } //Private Methods private void ValidateParameters() { if (string.IsNullOrEmpty(ArchiveBlobName)) { if (ConfigurationName != null || ConfigurationArgument != null || ConfigurationData != null) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoConfiguragionParameters); } if (ArchiveContainerName != null || ArchiveStorageEndpointSuffix != null) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoStorageParameters); } } else { if (string.Compare( Path.GetFileName(ArchiveBlobName), ArchiveBlobName, StringComparison.InvariantCultureIgnoreCase) != 0) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscConfigurationDataFileShouldNotIncludePath); } if (ConfigurationData != null) { ConfigurationData = GetUnresolvedProviderPathFromPSPath(ConfigurationData); if (!File.Exists(ConfigurationData)) { this.ThrowInvalidArgumentError( Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscCannotFindConfigurationDataFile, ConfigurationData); } if (string.Compare( Path.GetExtension(ConfigurationData), ".psd1", StringComparison.InvariantCultureIgnoreCase) != 0) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscInvalidConfigurationDataFile); } } if (ArchiveResourceGroupName == null) { ArchiveResourceGroupName = ResourceGroupName; } _storageCredentials = this.GetStorageCredentials(ArchiveResourceGroupName, ArchiveStorageAccountName); if (ConfigurationName == null) { ConfigurationName = Path.GetFileNameWithoutExtension(ArchiveBlobName); } if (ArchiveContainerName == null) { ArchiveContainerName = DscExtensionCmdletConstants.DefaultContainerName; } if (ArchiveStorageEndpointSuffix == null) { ArchiveStorageEndpointSuffix = DefaultProfile.DefaultContext.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix); } if (!(Regex.Match(Version, VersionRegexExpr).Success)) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscExtensionInvalidVersion); } } } private void CreateConfiguration() { var publicSettings = new DscExtensionPublicSettings(); var privateSettings = new DscExtensionPrivateSettings(); if (!string.IsNullOrEmpty(ArchiveBlobName)) { ConfigurationUris configurationUris = UploadConfigurationDataToBlob(); publicSettings.SasToken = configurationUris.SasToken; publicSettings.ModulesUrl = configurationUris.ModulesUrl; Hashtable privacySetting = new Hashtable(); privacySetting.Add("DataCollection", DataCollection); publicSettings.Privacy = privacySetting; publicSettings.ConfigurationFunction = string.Format( CultureInfo.InvariantCulture, "{0}\\{1}", Path.GetFileNameWithoutExtension(ArchiveBlobName), ConfigurationName); Tuple<DscExtensionPublicSettings.Property[], Hashtable> settings = DscExtensionSettingsSerializer.SeparatePrivateItems(ConfigurationArgument); publicSettings.Properties = settings.Item1; privateSettings.Items = settings.Item2; privateSettings.DataBlobUri = configurationUris.DataBlobUri; if (!string.IsNullOrEmpty(WmfVersion)) { publicSettings.WmfVersion = WmfVersion; } } if (string.IsNullOrEmpty(this.Location)) { this.Location = GetLocationFromVm(this.ResourceGroupName, this.VMName); } var parameters = new VirtualMachineExtension { Location = this.Location, Publisher = DscExtensionCmdletConstants.ExtensionPublishedNamespace, VirtualMachineExtensionType = DscExtensionCmdletConstants.ExtensionPublishedName, TypeHandlerVersion = Version, // Define the public and private property bags that will be passed to the extension. Settings = publicSettings, //PrivateConfuguration contains sensitive data in a plain text ProtectedSettings = privateSettings, AutoUpgradeMinorVersion = AutoUpdate.IsPresent }; //Add retry logic due to CRP service restart known issue CRP bug: 3564713 var count = 1; Rest.Azure.AzureOperationResponse<VirtualMachineExtension> op = null; while (true) { try { op = VirtualMachineExtensionClient.CreateOrUpdateWithHttpMessagesAsync( ResourceGroupName, VMName, Name ?? DscExtensionCmdletConstants.ExtensionPublishedNamespace + "." + DscExtensionCmdletConstants.ExtensionPublishedName, parameters).GetAwaiter().GetResult(); break; } catch (Rest.Azure.CloudException ex) { var errorReturned = JsonConvert.DeserializeObject<PSComputeLongRunningOperation>( ex.Response.Content); if ("Failed".Equals(errorReturned.Status) && errorReturned.Error != null && "InternalExecutionError".Equals(errorReturned.Error.Code)) { count++; if (count <= 2) { continue; } } ThrowTerminatingError(new ErrorRecord(ex, "InvalidResult", ErrorCategory.InvalidResult, null)); } } var result = ComputeAutoMapperProfile.Mapper.Map<PSAzureOperationResponse>(op); WriteObject(result); } /// <summary> /// Uploading configuration data to blob storage. /// </summary> /// <returns>ConfigurationUris collection that represent artifacts of uploading</returns> private ConfigurationUris UploadConfigurationDataToBlob() { // // Get a reference to the container in blob storage // var storageAccount = new CloudStorageAccount(_storageCredentials, ArchiveStorageEndpointSuffix, true); var blobClient = storageAccount.CreateCloudBlobClient(); var containerReference = blobClient.GetContainerReference(ArchiveContainerName); // // Get a reference to the configuration blob and create a SAS token to access it // var blobAccessPolicy = new SharedAccessBlobPolicy { SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1), Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Delete }; var configurationBlobName = ArchiveBlobName; var configurationBlobReference = containerReference.GetBlockBlobReference(configurationBlobName); var configurationBlobSasToken = configurationBlobReference.GetSharedAccessSignature(blobAccessPolicy); // // Upload the configuration data to blob storage and get a SAS token // string configurationDataBlobUri = null; if (ConfigurationData != null) { var guid = Guid.NewGuid(); // there may be multiple VMs using the same configuration var configurationDataBlobName = string.Format( CultureInfo.InvariantCulture, "{0}-{1}.psd1", ConfigurationName, guid); var configurationDataBlobReference = containerReference.GetBlockBlobReference(configurationDataBlobName); ConfirmAction( true, string.Empty, string.Format( CultureInfo.CurrentUICulture, Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscUploadToBlobStorageAction, ConfigurationData), configurationDataBlobReference.Uri.AbsoluteUri, () => { if (!Force && configurationDataBlobReference.ExistsAsync().ConfigureAwait(false).GetAwaiter().GetResult()) { ThrowTerminatingError( new ErrorRecord( new UnauthorizedAccessException( string.Format( CultureInfo.CurrentUICulture, Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscStorageBlobAlreadyExists, configurationDataBlobName)), "StorageBlobAlreadyExists", ErrorCategory.PermissionDenied, null)); } configurationDataBlobReference.UploadFromFileAsync(ConfigurationData).ConfigureAwait(false).GetAwaiter().GetResult(); var configurationDataBlobSasToken = configurationDataBlobReference.GetSharedAccessSignature(blobAccessPolicy); configurationDataBlobUri = configurationDataBlobReference.StorageUri.PrimaryUri.AbsoluteUri + configurationDataBlobSasToken; }); } return new ConfigurationUris { ModulesUrl = configurationBlobReference.StorageUri.PrimaryUri.AbsoluteUri, SasToken = configurationBlobSasToken, DataBlobUri = configurationDataBlobUri }; } /// <summary> /// Class represent info about uploaded Configuration. /// </summary> private class ConfigurationUris { public string SasToken { get; set; } public string DataBlobUri { get; set; } public string ModulesUrl { get; set; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.ClientStack.LindenUDP; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Avatar.Appearance { /// <summary> /// A module that just holds commands for inspecting avatar appearance. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AppearanceInfoModule")] public class AppearanceInfoModule : ISharedRegionModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_scenes = new List<Scene>(); // private IAvatarFactoryModule m_avatarFactory; public string Name { get { return "Appearance Information Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: INITIALIZED MODULE"); } public void PostInitialise() { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: POST INITIALIZED MODULE"); } public void Close() { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: CLOSED MODULE"); } public void AddRegion(Scene scene) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); lock (m_scenes) m_scenes.Remove(scene); } public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); lock (m_scenes) m_scenes.Add(scene); scene.AddCommand( "Users", this, "show appearance", "show appearance [<first-name> <last-name>]", "Synonym for 'appearance show'", HandleShowAppearanceCommand); scene.AddCommand( "Users", this, "appearance show", "appearance show [<first-name> <last-name>]", "Show appearance information for avatars.", "This command checks whether the simulator has all the baked textures required to display an avatar to other viewers. " + "\nIf not, then appearance is 'corrupt' and other avatars will continue to see it as a cloud." + "\nOptionally, you can view just a particular avatar's appearance information." + "\nIn this case, the texture UUID for each bake type is also shown and whether the simulator can find the referenced texture.", HandleShowAppearanceCommand); scene.AddCommand( "Users", this, "appearance send", "appearance send [<first-name> <last-name>]", "Send appearance data for each avatar in the simulator to other viewers.", "Optionally, you can specify that only a particular avatar's appearance data is sent.", HandleSendAppearanceCommand); scene.AddCommand( "Users", this, "appearance rebake", "appearance rebake <first-name> <last-name>", "Send a request to the user's viewer for it to rebake and reupload its appearance textures.", "This is currently done for all baked texture references previously received, whether the simulator can find the asset or not." + "\nThis will only work for texture ids that the viewer has already uploaded." + "\nIf the viewer has not yet sent the server any texture ids then nothing will happen" + "\nsince requests can only be made for ids that the client has already sent us", HandleRebakeAppearanceCommand); scene.AddCommand( "Users", this, "appearance find", "appearance find <uuid-or-start-of-uuid>", "Find out which avatar uses the given asset as a baked texture, if any.", "You can specify just the beginning of the uuid, e.g. 2008a8d. A longer UUID must be in dashed format.", HandleFindAppearanceCommand); scene.AddCommand( "Users", this, "wearables show", "wearables show [<first-name> <last-name>]", "Show information about wearables for avatars.", "If no avatar name is given then a general summary for all avatars in the scene is shown.\n" + "If an avatar name is given then specific information about current wearables is shown.", HandleShowWearablesCommand); scene.AddCommand( "Users", this, "wearables check", "wearables check <first-name> <last-name>", "Check that the wearables of a given avatar in the scene are valid.", "This currently checks that the wearable assets themselves and any assets referenced by them exist.", HandleCheckWearablesCommand); } private void HandleSendAppearanceCommand(string module, string[] cmd) { if (cmd.Length != 2 && cmd.Length < 4) { MainConsole.Instance.OutputFormat("Usage: appearance send [<first-name> <last-name>]"); return; } bool targetNameSupplied = false; string optionalTargetFirstName = null; string optionalTargetLastName = null; if (cmd.Length >= 4) { targetNameSupplied = true; optionalTargetFirstName = cmd[2]; optionalTargetLastName = cmd[3]; } lock (m_scenes) { foreach (Scene scene in m_scenes) { if (targetNameSupplied) { ScenePresence sp = scene.GetScenePresence(optionalTargetFirstName, optionalTargetLastName); if (sp != null && !sp.IsChildAgent) { MainConsole.Instance.OutputFormat( "Sending appearance information for {0} to all other avatars in {1}", sp.Name, scene.RegionInfo.RegionName); scene.AvatarFactory.SendAppearance(sp.UUID); } } else { scene.ForEachRootScenePresence( sp => { MainConsole.Instance.OutputFormat( "Sending appearance information for {0} to all other avatars in {1}", sp.Name, scene.RegionInfo.RegionName); scene.AvatarFactory.SendAppearance(sp.UUID); } ); } } } } private void HandleShowAppearanceCommand(string module, string[] cmd) { if (cmd.Length != 2 && cmd.Length < 4) { MainConsole.Instance.OutputFormat("Usage: appearance show [<first-name> <last-name>]"); return; } bool targetNameSupplied = false; string optionalTargetFirstName = null; string optionalTargetLastName = null; if (cmd.Length >= 4) { targetNameSupplied = true; optionalTargetFirstName = cmd[2]; optionalTargetLastName = cmd[3]; } lock (m_scenes) { foreach (Scene scene in m_scenes) { if (targetNameSupplied) { ScenePresence sp = scene.GetScenePresence(optionalTargetFirstName, optionalTargetLastName); if (sp != null && !sp.IsChildAgent) scene.AvatarFactory.WriteBakedTexturesReport(sp, MainConsole.Instance.OutputFormat); } else { scene.ForEachRootScenePresence( sp => { bool bakedTextureValid = scene.AvatarFactory.ValidateBakedTextureCache(sp); MainConsole.Instance.OutputFormat( "{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete"); } ); } } } } private void HandleRebakeAppearanceCommand(string module, string[] cmd) { if (cmd.Length != 4) { MainConsole.Instance.OutputFormat("Usage: appearance rebake <first-name> <last-name>"); return; } string firstname = cmd[2]; string lastname = cmd[3]; lock (m_scenes) { foreach (Scene scene in m_scenes) { ScenePresence sp = scene.GetScenePresence(firstname, lastname); if (sp != null && !sp.IsChildAgent) { int rebakesRequested = scene.AvatarFactory.RequestRebake(sp, false); if (rebakesRequested > 0) MainConsole.Instance.OutputFormat( "Requesting rebake of {0} uploaded textures for {1} in {2}", rebakesRequested, sp.Name, scene.RegionInfo.RegionName); else MainConsole.Instance.OutputFormat( "No texture IDs available for rebake request for {0} in {1}", sp.Name, scene.RegionInfo.RegionName); } } } } private void HandleFindAppearanceCommand(string module, string[] cmd) { if (cmd.Length != 3) { MainConsole.Instance.OutputFormat("Usage: appearance find <uuid-or-start-of-uuid>"); return; } string rawUuid = cmd[2]; HashSet<ScenePresence> matchedAvatars = new HashSet<ScenePresence>(); lock (m_scenes) { foreach (Scene scene in m_scenes) { scene.ForEachRootScenePresence( sp => { Dictionary<BakeType, Primitive.TextureEntryFace> bakedFaces = scene.AvatarFactory.GetBakedTextureFaces(sp.UUID); foreach (Primitive.TextureEntryFace face in bakedFaces.Values) { if (face != null && face.TextureID.ToString().StartsWith(rawUuid)) matchedAvatars.Add(sp); } }); } } if (matchedAvatars.Count == 0) { MainConsole.Instance.OutputFormat("{0} did not match any baked avatar textures in use", rawUuid); } else { MainConsole.Instance.OutputFormat( "{0} matched {1}", rawUuid, string.Join(", ", matchedAvatars.ToList().ConvertAll<string>(sp => sp.Name).ToArray())); } } protected void HandleShowWearablesCommand(string module, string[] cmd) { if (cmd.Length != 2 && cmd.Length < 4) { MainConsole.Instance.OutputFormat("Usage: wearables show [<first-name> <last-name>]"); return; } bool targetNameSupplied = false; string optionalTargetFirstName = null; string optionalTargetLastName = null; if (cmd.Length >= 4) { targetNameSupplied = true; optionalTargetFirstName = cmd[2]; optionalTargetLastName = cmd[3]; } StringBuilder sb = new StringBuilder(); if (targetNameSupplied) { lock (m_scenes) { foreach (Scene scene in m_scenes) { ScenePresence sp = scene.GetScenePresence(optionalTargetFirstName, optionalTargetLastName); if (sp != null && !sp.IsChildAgent) AppendWearablesDetailReport(sp, sb); } } } else { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Name", ConsoleDisplayUtil.UserNameSize); cdt.AddColumn("Wearables", 2); lock (m_scenes) { foreach (Scene scene in m_scenes) { scene.ForEachRootScenePresence( sp => { int count = 0; for (int i = (int)WearableType.Shape; i < (int)WearableType.Physics; i++) count += sp.Appearance.Wearables[i].Count; cdt.AddRow(sp.Name, count); } ); } } sb.Append(cdt.ToString()); } MainConsole.Instance.Output(sb.ToString()); } private void HandleCheckWearablesCommand(string module, string[] cmd) { if (cmd.Length != 4) { MainConsole.Instance.OutputFormat("Usage: wearables check <first-name> <last-name>"); return; } string firstname = cmd[2]; string lastname = cmd[3]; StringBuilder sb = new StringBuilder(); UuidGatherer uuidGatherer = new UuidGatherer(m_scenes[0].AssetService); lock (m_scenes) { foreach (Scene scene in m_scenes) { ScenePresence sp = scene.GetScenePresence(firstname, lastname); if (sp != null && !sp.IsChildAgent) { sb.AppendFormat("Wearables checks for {0}\n\n", sp.Name); for (int i = (int)WearableType.Shape; i < (int)WearableType.Physics; i++) { AvatarWearable aw = sp.Appearance.Wearables[i]; if (aw.Count > 0) { sb.Append(Enum.GetName(typeof(WearableType), i)); sb.Append("\n"); for (int j = 0; j < aw.Count; j++) { WearableItem wi = aw[j]; ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.Indent = 2; cdl.AddRow("Item UUID", wi.ItemID); cdl.AddRow("Assets", ""); sb.Append(cdl.ToString()); uuidGatherer.AddForInspection(wi.AssetID); uuidGatherer.GatherAll(); string[] assetStrings = Array.ConvertAll<UUID, string>(uuidGatherer.GatheredUuids.Keys.ToArray(), u => u.ToString()); bool[] existChecks = scene.AssetService.AssetsExist(assetStrings); ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.Indent = 4; cdt.AddColumn("Type", 10); cdt.AddColumn("UUID", ConsoleDisplayUtil.UuidSize); cdt.AddColumn("Found", 5); for (int k = 0; k < existChecks.Length; k++) cdt.AddRow( (AssetType)uuidGatherer.GatheredUuids[new UUID(assetStrings[k])], assetStrings[k], existChecks[k] ? "yes" : "no"); sb.Append(cdt.ToString()); sb.Append("\n"); } } } } } } MainConsole.Instance.Output(sb.ToString()); } private void AppendWearablesDetailReport(ScenePresence sp, StringBuilder sb) { sb.AppendFormat("\nWearables for {0}\n", sp.Name); ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Type", 10); cdt.AddColumn("Item UUID", ConsoleDisplayUtil.UuidSize); cdt.AddColumn("Asset UUID", ConsoleDisplayUtil.UuidSize); for (int i = (int)WearableType.Shape; i < (int)WearableType.Physics; i++) { AvatarWearable aw = sp.Appearance.Wearables[i]; for (int j = 0; j < aw.Count; j++) { WearableItem wi = aw[j]; cdt.AddRow(Enum.GetName(typeof(WearableType), i), wi.ItemID, wi.AssetID); } } sb.Append(cdt.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.Threading; using System.Threading.Tasks; using Infrastructure.Common; using Xunit; public class StreamingTests : ConditionalWcfTest { [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_StreamedRequest_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = binding = new NetTcpBinding(SecurityMode.Transport); binding.TransferMode = TransferMode.StreamedRequest; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var result = serviceProxy.GetStringFromStream(stream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_StreamedResponse_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.Transport); binding.TransferMode = TransferMode.StreamedResponse; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ var returnStream = serviceProxy.GetStreamFromString(testString); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_Streamed_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.Transport); binding.TransferMode = TransferMode.Streamed; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStream(stream); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_Streamed_MultipleReads() { string testString = ScenarioTestHelpers.CreateInterestingString(20001); NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.Transport); binding.TransferMode = TransferMode.Streamed; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStream(stream); var ms = new MemoryStream((int)stream.Length); var buffer = new byte[10]; int bytesRead = 0; while ((bytesRead = returnStream.ReadAsync(buffer, 0, buffer.Length).Result) != 0) { ms.Write(buffer, 0, bytesRead); } ms.Position = 0; var result = StreamToString(ms); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_Streamed_TimeOut_Long_Running_Operation() { string testString = "Hello"; NetTcpBinding binding = null; TimeSpan serviceOperationTimeout = TimeSpan.FromMilliseconds(10000); ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.Transport); binding.TransferMode = TransferMode.Streamed; binding.SendTimeout = TimeSpan.FromMilliseconds(5000); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address)); serviceProxy = factory.CreateChannel(); ((ICommunicationObject)serviceProxy).Open(); Stopwatch watch = new Stopwatch(); watch.Start(); // *** EXECUTE *** \\ try { Assert.Throws<TimeoutException>(() => { string returnString = serviceProxy.EchoWithTimeout(testString, serviceOperationTimeout); }); } finally { watch.Stop(); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } // *** VALIDATE *** \\ // want to assert that this completed in > 5 s as an upper bound since the SendTimeout is 5 sec // (usual case is around 5001-5005 ms) Assert.True(watch.ElapsedMilliseconds >= 4985 && watch.ElapsedMilliseconds < 6000, String.Format("Expected timeout was {0}ms but actual was {1}ms", serviceOperationTimeout.TotalMilliseconds, watch.ElapsedMilliseconds)); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_Streamed_Async_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.Transport); binding.TransferMode = TransferMode.Streamed; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStreamAsync(stream).Result; var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.True(String.Equals(testString, result), String.Format("Error: Expected test string: '{0}' but got '{1}'", testString, result)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_StreamedRequest_Async_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.Transport); binding.TransferMode = TransferMode.StreamedRequest; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStreamAsync(stream).Result; var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.True(String.Equals(testString, result), String.Format("Error: Expected test string: '{0}' but got '{1}'", testString, result)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_StreamedResponse_Async_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.Transport); binding.TransferMode = TransferMode.StreamedResponse; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStreamAsync(stream).Result; var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.True(String.Equals(testString, result), String.Format("Error: Expected test string: '{0}' but got '{1}'", testString, result)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_Streamed_RoundTrips_String_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { TestTypes.SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => StreamingTests.NetTcp_TransportSecurity_Streamed_RoundTrips_String(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: NetTcp_TransportSecurity_String_Streamed_RoundTrips_WithSingleThreadedSyncContext timed-out."); } [WcfFact] [Condition(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed), nameof(Windows_Authentication_Available), nameof(Ambient_Credentials_Available))] [Issue(832, Framework = FrameworkID.NetNative)] // Windows Stream Security is not supported in NET Native [OuterLoop] public static void NetTcp_TransportSecurity_Streamed_Async_RoundTrips_String_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { TestTypes.SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => StreamingTests.NetTcp_TransportSecurity_Streamed_Async_RoundTrips_String(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: NetTcp_TransportSecurity_Streamed_Async_RoundTrips_String_WithSingleThreadedSyncContext timed-out."); } //private static void PrintInnerExceptionsHresult(Exception e, StringBuilder errorBuilder) //{ // if (e.InnerException != null) // { // errorBuilder.AppendLine(string.Format("\r\n InnerException type: '{0}', Hresult:'{1}'", e.InnerException, e.InnerException.HResult)); // PrintInnerExceptionsHresult(e.InnerException, errorBuilder); // } //} private static string StreamToString(Stream stream) { var reader = new StreamReader(stream, Encoding.UTF8); return reader.ReadToEnd(); } private static Stream StringToStream(string str) { var ms = new MemoryStream(); var sw = new StreamWriter(ms, Encoding.UTF8); sw.Write(str); sw.Flush(); ms.Position = 0; return ms; } }
// 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 System.Text; using Microsoft.VisualStudio.Debugger.Interop; using MICore; using System.Diagnostics; // This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event. // These are used in EngineCallback.cs. // The events are how the engine tells the debugger about what is happening in the debuggee process. // There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These // each implement the IDebugEvent2.GetAttributes method for the type of event they represent. // Most events sent the debugger are asynchronous events. namespace Microsoft.MIDebugEngine { #region Event base classes internal class AD7AsynchronousEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return Constants.S_OK; } } internal class AD7StoppingEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return Constants.S_OK; } } internal class AD7SynchronousEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return Constants.S_OK; } } internal class AD7SynchronousStoppingEvent : IDebugEvent2 { public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_STOPPING | (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS; int IDebugEvent2.GetAttributes(out uint eventAttributes) { eventAttributes = Attributes; return Constants.S_OK; } } #endregion // The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created. internal sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2 { public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06"; private IDebugEngine2 _engine; private AD7EngineCreateEvent(AD7Engine engine) { _engine = engine; } public static void Send(AD7Engine engine) { AD7EngineCreateEvent eventObject = new AD7EngineCreateEvent(engine); engine.Callback.Send(eventObject, IID, null, null); } int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine) { engine = _engine; return Constants.S_OK; } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to. internal sealed class AD7ProgramCreateEvent : AD7SynchronousEvent, IDebugProgramCreateEvent2 { public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139"; internal static void Send(AD7Engine engine) { AD7ProgramCreateEvent eventObject = new AD7ProgramCreateEvent(); engine.Callback.Send(eventObject, IID, engine, null); } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded. internal sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2 { public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2"; private readonly AD7Module _module; private readonly bool _fLoad; public AD7ModuleLoadEvent(AD7Module module, bool fLoad) { _module = module; _fLoad = fLoad; } int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad) { module = _module; if (_fLoad) { debugMessage = String.Concat("Loaded '", _module.DebuggedModule.Name, "'"); fIsLoad = 1; } else { debugMessage = String.Concat("Unloaded '", _module.DebuggedModule.Name, "'"); fIsLoad = 0; } return Constants.S_OK; } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion // or is otherwise destroyed. internal sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2 { public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5"; private readonly uint _exitCode; public AD7ProgramDestroyEvent(uint exitCode) { _exitCode = exitCode; } #region IDebugProgramDestroyEvent2 Members int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode) { exitCode = _exitCode; return Constants.S_OK; } #endregion } internal sealed class AD7MessageEvent : IDebugEvent2, IDebugMessageEvent2 { public const string IID = "3BDB28CF-DBD2-4D24-AF03-01072B67EB9E"; private readonly OutputMessage _outputMessage; private readonly bool _isAsync; public AD7MessageEvent(OutputMessage outputMessage, bool isAsync) { _outputMessage = outputMessage; _isAsync = isAsync; } int IDebugEvent2.GetAttributes(out uint eventAttributes) { if (_isAsync) eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS; else eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE; return Constants.S_OK; } int IDebugMessageEvent2.GetMessage(enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId) { return ConvertMessageToAD7(_outputMessage, pMessageType, out pbstrMessage, out pdwType, out pbstrHelpFileName, out pdwHelpId); } internal static int ConvertMessageToAD7(OutputMessage outputMessage, enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId) { const uint MB_ICONERROR = 0x00000010; const uint MB_ICONWARNING = 0x00000030; pMessageType[0] = outputMessage.MessageType; pbstrMessage = outputMessage.Message; pdwType = 0; if ((outputMessage.MessageType & enum_MESSAGETYPE.MT_TYPE_MASK) == enum_MESSAGETYPE.MT_MESSAGEBOX) { switch (outputMessage.SeverityValue) { case OutputMessage.Severity.Error: pdwType |= MB_ICONERROR; break; case OutputMessage.Severity.Warning: pdwType |= MB_ICONWARNING; break; } } pbstrHelpFileName = null; pdwHelpId = 0; return Constants.S_OK; } int IDebugMessageEvent2.SetResponse(uint dwResponse) { return Constants.S_OK; } } internal sealed class AD7ErrorEvent : IDebugEvent2, IDebugErrorEvent2 { public const string IID = "FDB7A36C-8C53-41DA-A337-8BD86B14D5CB"; private readonly OutputMessage _outputMessage; private readonly bool _isAsync; public AD7ErrorEvent(OutputMessage outputMessage, bool isAsync) { _outputMessage = outputMessage; _isAsync = isAsync; } int IDebugEvent2.GetAttributes(out uint eventAttributes) { if (_isAsync) eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS; else eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE; return Constants.S_OK; } int IDebugErrorEvent2.GetErrorMessage(enum_MESSAGETYPE[] pMessageType, out string errorFormat, out int hrErrorReason, out uint pdwType, out string helpFilename, out uint pdwHelpId) { hrErrorReason = unchecked((int)_outputMessage.ErrorCode); return AD7MessageEvent.ConvertMessageToAD7(_outputMessage, pMessageType, out errorFormat, out pdwType, out helpFilename, out pdwHelpId); } } internal sealed class AD7BreakpointErrorEvent : AD7AsynchronousEvent, IDebugBreakpointErrorEvent2 { public const string IID = "ABB0CA42-F82B-4622-84E4-6903AE90F210"; private AD7ErrorBreakpoint _error; public AD7BreakpointErrorEvent(AD7ErrorBreakpoint error) { _error = error; } public int GetErrorBreakpoint(out IDebugErrorBreakpoint2 ppErrorBP) { ppErrorBP = _error; return Constants.S_OK; } } internal sealed class AD7BreakpointUnboundEvent : AD7AsynchronousEvent, IDebugBreakpointUnboundEvent2 { public const string IID = "78d1db4f-c557-4dc5-a2dd-5369d21b1c8c"; private readonly enum_BP_UNBOUND_REASON _reason; private AD7BoundBreakpoint _bp; public AD7BreakpointUnboundEvent(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason) { _reason = reason; _bp = bp; } public int GetBreakpoint(out IDebugBoundBreakpoint2 ppBP) { ppBP = _bp; return Constants.S_OK; } public int GetReason(enum_BP_UNBOUND_REASON[] pdwUnboundReason) { pdwUnboundReason[0] = _reason; return Constants.S_OK; } } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged. internal sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2 { public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA"; } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited. internal sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2 { public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541"; private readonly uint _exitCode; public AD7ThreadDestroyEvent(uint exitCode) { _exitCode = exitCode; } #region IDebugThreadDestroyEvent2 Members int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode) { exitCode = _exitCode; return Constants.S_OK; } #endregion } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed. internal sealed class AD7LoadCompleteEvent : AD7StoppingEvent, IDebugLoadCompleteEvent2 { public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B"; public AD7LoadCompleteEvent() { } } internal sealed class AD7EntryPointEvent : AD7StoppingEvent, IDebugEntryPointEvent2 { public const string IID = "E8414A3E-1642-48EC-829E-5F4040E16DA9"; public AD7EntryPointEvent() { } } internal sealed class AD7ExpressionCompleteEvent : AD7AsynchronousEvent, IDebugExpressionEvaluationCompleteEvent2 { private AD7Engine _engine; public const string IID = "C0E13A85-238A-4800-8315-D947C960A843"; public AD7ExpressionCompleteEvent(AD7Engine engine, IVariableInformation var, IDebugProperty2 prop = null) { _engine = engine; _var = var; _prop = prop; } public int GetExpression(out IDebugExpression2 expr) { expr = new AD7Expression(_engine, _var); return Constants.S_OK; } public int GetResult(out IDebugProperty2 prop) { prop = _prop != null ? _prop : new AD7Property(_engine, _var); return Constants.S_OK; } private IVariableInformation _var; private IDebugProperty2 _prop; } // This interface tells the session debug manager (SDM) that an exception has occurred in the debuggee. internal sealed class AD7ExceptionEvent : AD7StoppingEvent, IDebugExceptionEvent2 { public const string IID = "51A94113-8788-4A54-AE15-08B74FF922D0"; public AD7ExceptionEvent(string name, string description, uint code, Guid? exceptionCategory, ExceptionBreakpointState state) { _name = name; _code = code; _description = description ?? name; _category = exceptionCategory ?? new Guid(EngineConstants.EngineId); switch (state) { case ExceptionBreakpointState.None: _state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE; break; case ExceptionBreakpointState.BreakThrown: _state = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE; break; case ExceptionBreakpointState.BreakUserHandled: _state = enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT; break; default: Debug.Fail("Unexpected state value"); _state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE; break; } } #region IDebugExceptionEvent2 Members public int CanPassToDebuggee() { // Cannot pass it on return Constants.S_FALSE; } public int GetException(EXCEPTION_INFO[] pExceptionInfo) { EXCEPTION_INFO ex = new EXCEPTION_INFO(); ex.bstrExceptionName = _name; ex.dwCode = _code; ex.dwState = _state; ex.guidType = _category; pExceptionInfo[0] = ex; return Constants.S_OK; } public int GetExceptionDescription(out string pbstrDescription) { pbstrDescription = _description; return Constants.S_OK; } public int PassToDebuggee(int fPass) { return Constants.S_OK; } private string _name; private uint _code; private string _description; private Guid _category; private enum_EXCEPTION_STATE _state; #endregion } // This interface tells the session debug manager (SDM) that a step has completed internal sealed class AD7StepCompleteEvent : AD7StoppingEvent, IDebugStepCompleteEvent2 { public const string IID = "0f7f24c1-74d9-4ea6-a3ea-7edb2d81441d"; } // This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed. internal sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2 { public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b"; } // This interface is sent by the debug engine (DE) to the session debug manager (SDM) to output a string for debug tracing. internal sealed class AD7OutputDebugStringEvent : AD7AsynchronousEvent, IDebugOutputStringEvent2 { public const string IID = "569c4bb1-7b82-46fc-ae28-4536ddad753e"; private string _str; public AD7OutputDebugStringEvent(string str) { _str = str; } #region IDebugOutputStringEvent2 Members int IDebugOutputStringEvent2.GetString(out string pbstrString) { pbstrString = _str; return Constants.S_OK; } #endregion } // This interface is sent by the debug engine (DE) to indicate the results of searching for symbols for a module in the debuggee internal sealed class AD7SymbolSearchEvent : AD7AsynchronousEvent, IDebugSymbolSearchEvent2 { public const string IID = "638F7C54-C160-4c7b-B2D0-E0337BC61F8C"; private AD7Module _module; private string _searchInfo; private enum_MODULE_INFO_FLAGS _symbolFlags; public AD7SymbolSearchEvent(AD7Module module, string searchInfo, enum_MODULE_INFO_FLAGS symbolFlags) { _module = module; _searchInfo = searchInfo; _symbolFlags = symbolFlags; } #region IDebugSymbolSearchEvent2 Members int IDebugSymbolSearchEvent2.GetSymbolSearchInfo(out IDebugModule3 pModule, ref string pbstrDebugMessage, enum_MODULE_INFO_FLAGS[] pdwModuleInfoFlags) { pModule = _module; pbstrDebugMessage = _searchInfo; pdwModuleInfoFlags[0] = _symbolFlags; return Constants.S_OK; } #endregion } // This interface is sent when a pending breakpoint has been bound in the debuggee. internal sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2 { public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0"; private AD7PendingBreakpoint _pendingBreakpoint; private AD7BoundBreakpoint _boundBreakpoint; public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint) { _pendingBreakpoint = pendingBreakpoint; _boundBreakpoint = boundBreakpoint; } #region IDebugBreakpointBoundEvent2 Members int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) { IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[1]; boundBreakpoints[0] = _boundBreakpoint; ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints); return Constants.S_OK; } int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP) { ppPendingBP = _pendingBreakpoint; return Constants.S_OK; } #endregion } // This Event is sent when a breakpoint is hit in the debuggee internal sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2 { public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74"; private IEnumDebugBoundBreakpoints2 _boundBreakpoints; public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints) { _boundBreakpoints = boundBreakpoints; } #region IDebugBreakpointEvent2 Members int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) { ppEnum = _boundBreakpoints; return Constants.S_OK; } #endregion } internal sealed class AD7CustomDebugEvent : AD7AsynchronousEvent, IDebugCustomEvent110 { public const string IID = "2615D9BC-1948-4D21-81EE-7A963F20CF59"; private readonly Guid _guidVSService; private readonly Guid _sourceId; private readonly int _messageCode; private readonly object _parameter1; private readonly object _parameter2; public AD7CustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2) { _guidVSService = guidVSService; _sourceId = sourceId; _messageCode = messageCode; _parameter1 = parameter1; _parameter2 = parameter2; } int IDebugCustomEvent110.GetCustomEventInfo(out Guid guidVSService, VsComponentMessage[] message) { guidVSService = _guidVSService; message[0].SourceId = _sourceId; message[0].MessageCode = (uint)_messageCode; message[0].Parameter1 = _parameter1; message[0].Parameter2 = _parameter2; return Constants.S_OK; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Threading; namespace Newtonsoft.Json.Utilities { internal interface IWrappedDictionary : IDictionary { object UnderlyingDictionary { get; } } internal class DictionaryWrapper<TKey, TValue> : IDictionary<TKey, TValue>, IWrappedDictionary { private readonly IDictionary _dictionary; private readonly IDictionary<TKey, TValue> _genericDictionary; private object _syncRoot; public DictionaryWrapper(IDictionary dictionary) { ValidationUtils.ArgumentNotNull(dictionary, "dictionary"); _dictionary = dictionary; } public DictionaryWrapper(IDictionary<TKey, TValue> dictionary) { ValidationUtils.ArgumentNotNull(dictionary, "dictionary"); _genericDictionary = dictionary; } public void Add(TKey key, TValue value) { if (_genericDictionary != null) _genericDictionary.Add(key, value); else _dictionary.Add(key, value); } public bool ContainsKey(TKey key) { if (_genericDictionary != null) return _genericDictionary.ContainsKey(key); else return _dictionary.Contains(key); } public ICollection<TKey> Keys { get { if (_genericDictionary != null) return _genericDictionary.Keys; else return _dictionary.Keys.Cast<TKey>().ToList(); } } public bool Remove(TKey key) { if (_genericDictionary != null) { return _genericDictionary.Remove(key); } else { if (_dictionary.Contains(key)) { _dictionary.Remove(key); return true; } else { return false; } } } public bool TryGetValue(TKey key, out TValue value) { if (_genericDictionary != null) { return _genericDictionary.TryGetValue(key, out value); } else { if (!_dictionary.Contains(key)) { value = default(TValue); return false; } else { value = (TValue)_dictionary[key]; return true; } } } public ICollection<TValue> Values { get { if (_genericDictionary != null) return _genericDictionary.Values; else return _dictionary.Values.Cast<TValue>().ToList(); } } public TValue this[TKey key] { get { if (_genericDictionary != null) return _genericDictionary[key]; else return (TValue)_dictionary[key]; } set { if (_genericDictionary != null) _genericDictionary[key] = value; else _dictionary[key] = value; } } public void Add(KeyValuePair<TKey, TValue> item) { if (_genericDictionary != null) _genericDictionary.Add(item); else ((IList)_dictionary).Add(item); } public void Clear() { if (_genericDictionary != null) _genericDictionary.Clear(); else _dictionary.Clear(); } public bool Contains(KeyValuePair<TKey, TValue> item) { if (_genericDictionary != null) return _genericDictionary.Contains(item); else return ((IList)_dictionary).Contains(item); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (_genericDictionary != null) { _genericDictionary.CopyTo(array, arrayIndex); } else { foreach (DictionaryEntry item in _dictionary) { array[arrayIndex++] = new KeyValuePair<TKey, TValue>((TKey)item.Key, (TValue)item.Value); } } } public int Count { get { if (_genericDictionary != null) return _genericDictionary.Count; else return _dictionary.Count; } } public bool IsReadOnly { get { if (_genericDictionary != null) return _genericDictionary.IsReadOnly; else return _dictionary.IsReadOnly; } } public bool Remove(KeyValuePair<TKey, TValue> item) { if (_genericDictionary != null) { return _genericDictionary.Remove(item); } else { if (_dictionary.Contains(item.Key)) { object value = _dictionary[item.Key]; if (object.Equals(value, item.Value)) { _dictionary.Remove(item.Key); return true; } else { return false; } } else { return true; } } } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { if (_genericDictionary != null) return _genericDictionary.GetEnumerator(); else return _dictionary.Cast<DictionaryEntry>().Select(de => new KeyValuePair<TKey, TValue>((TKey)de.Key, (TValue)de.Value)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IDictionary.Add(object key, object value) { if (_genericDictionary != null) _genericDictionary.Add((TKey)key, (TValue)value); else _dictionary.Add(key, value); } bool IDictionary.Contains(object key) { if (_genericDictionary != null) return _genericDictionary.ContainsKey((TKey)key); else return _dictionary.Contains(key); } private struct DictionaryEnumerator<TEnumeratorKey, TEnumeratorValue> : IDictionaryEnumerator { private readonly IEnumerator<KeyValuePair<TEnumeratorKey, TEnumeratorValue>> _e; public DictionaryEnumerator(IEnumerator<KeyValuePair<TEnumeratorKey, TEnumeratorValue>> e) { ValidationUtils.ArgumentNotNull(e, "e"); _e = e; } public DictionaryEntry Entry { get { return (DictionaryEntry)Current; } } public object Key { get { return Entry.Key; } } public object Value { get { return Entry.Value; } } public object Current { get { return new DictionaryEntry(_e.Current.Key, _e.Current.Value); } } public bool MoveNext() { return _e.MoveNext(); } public void Reset() { _e.Reset(); } } IDictionaryEnumerator IDictionary.GetEnumerator() { if (_genericDictionary != null) return new DictionaryEnumerator<TKey, TValue>(_genericDictionary.GetEnumerator()); else return _dictionary.GetEnumerator(); } bool IDictionary.IsFixedSize { get { if (_genericDictionary != null) return false; else return _dictionary.IsFixedSize; } } ICollection IDictionary.Keys { get { if (_genericDictionary != null) return _genericDictionary.Keys.ToList(); else return _dictionary.Keys; } } public void Remove(object key) { if (_genericDictionary != null) _genericDictionary.Remove((TKey)key); else _dictionary.Remove(key); } ICollection IDictionary.Values { get { if (_genericDictionary != null) return _genericDictionary.Values.ToList(); else return _dictionary.Values; } } object IDictionary.this[object key] { get { if (_genericDictionary != null) return _genericDictionary[(TKey)key]; else return _dictionary[key]; } set { if (_genericDictionary != null) _genericDictionary[(TKey)key] = (TValue)value; else _dictionary[key] = value; } } void ICollection.CopyTo(Array array, int index) { if (_genericDictionary != null) _genericDictionary.CopyTo((KeyValuePair<TKey, TValue>[])array, index); else _dictionary.CopyTo(array, index); } bool ICollection.IsSynchronized { get { if (_genericDictionary != null) return false; else return _dictionary.IsSynchronized; } } object ICollection.SyncRoot { get { if (_syncRoot == null) Interlocked.CompareExchange(ref _syncRoot, new object(), null); return _syncRoot; } } public object UnderlyingDictionary { get { if (_genericDictionary != null) return _genericDictionary; else return _dictionary; } } } }
#if DEBUG_HANDLECOLLECTOR using System.Diagnostics; #endif using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; [module: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope="namespace", Target="System.Internal")] namespace System.Internal { internal sealed class HandleCollector { private static HandleType[] handleTypes; private static int handleTypeCount; private static int suspendCount; internal static event HandleChangeEventHandler HandleAdded; internal static event HandleChangeEventHandler HandleRemoved; private static object internalSyncObject = new object(); /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.Add"]/*' /> /// <devdoc> /// Adds the given handle to the handle collector. This keeps the /// handle on a "hot list" of objects that may need to be garbage /// collected. /// </devdoc> internal static IntPtr Add(IntPtr handle, int type) { handleTypes[type - 1].Add(handle); return handle; } /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.Add"]/*' /> /// <devdoc> /// Suspends GC.Collect /// </devdoc> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal static void SuspendCollect() { lock(internalSyncObject) { suspendCount++; } } /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.Add"]/*' /> /// <devdoc> /// Resumes GC.Collect /// </devdoc> [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal static void ResumeCollect() { bool performCollect = false; lock(internalSyncObject) { if(suspendCount > 0){ suspendCount--; } if(suspendCount == 0) { for(int i=0; i < handleTypeCount; i++) { lock(handleTypes[i]) { if (handleTypes[i].NeedCollection()) { performCollect = true; } } } } } if(performCollect) { GC.Collect(); } } /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.RegisterType"]/*' /> /// <devdoc> /// Registers a new type of handle with the handle collector. /// </devdoc> internal static int RegisterType(string typeName, int expense, int initialThreshold) { lock (internalSyncObject){ if (handleTypeCount == 0 || handleTypeCount == handleTypes.Length) { HandleType[] newTypes = new HandleType[handleTypeCount + 10]; if (handleTypes != null) { Array.Copy(handleTypes, 0, newTypes, 0, handleTypeCount); } handleTypes = newTypes; } handleTypes[handleTypeCount++] = new HandleType(typeName, expense, initialThreshold); return handleTypeCount; } } /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.Remove"]/*' /> /// <devdoc> /// Removes the given handle from the handle collector. Removing a /// handle removes it from our "hot list" of objects that should be /// frequently garbage collected. /// </devdoc> internal static IntPtr Remove(IntPtr handle, int type) { return handleTypes[type - 1].Remove(handle); } /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.HandleType"]/*' /> /// <devdoc> /// Represents a specific type of handle. /// </devdoc> private class HandleType { internal readonly string name; private int initialThreshHold; private int threshHold; private int handleCount; private readonly int deltaPercent; #if DEBUG_HANDLECOLLECTOR private List<IntPtr> handles = new List<IntPtr>(); #endif /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.HandleType.HandleType"]/*' /> /// <devdoc> /// Creates a new handle type. /// </devdoc> internal HandleType(string name, int expense, int initialThreshHold) { this.name = name; this.initialThreshHold = initialThreshHold; this.threshHold = initialThreshHold; this.deltaPercent = 100 - expense; } /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.HandleType.Add"]/*' /> /// <devdoc> /// Adds a handle to this handle type for monitoring. /// </devdoc> [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] internal void Add(IntPtr handle) { if( handle == IntPtr.Zero ) { return; } bool performCollect = false; int currentCount = 0; lock(this) { handleCount++; #if DEBUG_HANDLECOLLECTOR Debug.Assert(!handles.Contains(handle)); handles.Add(handle); #endif performCollect = NeedCollection(); currentCount = handleCount; } lock (internalSyncObject){ if (HandleCollector.HandleAdded != null) { HandleCollector.HandleAdded(name, handle, currentCount); } } if (!performCollect) { return; } if (performCollect) { #if DEBUG_HANDLECOLLECTOR Debug.WriteLine("HC> Forcing garbage collect"); Debug.WriteLine("HC> name :" + name); Debug.WriteLine("HC> threshHold :" + (threshHold).ToString()); Debug.WriteLine("HC> handleCount :" + (handleCount).ToString()); Debug.WriteLine("HC> deltaPercent:" + (deltaPercent).ToString()); #endif GC.Collect(); // We just performed a GC. If the main thread is in a tight // loop there is a this will cause us to increase handles forever and prevent handle collector // from doing its job. Yield the thread here. This won't totally cause // a finalization pass but it will effectively elevate the priority // of the finalizer thread just for an instant. But how long should // we sleep? We base it on how expensive the handles are because the // more expensive the handle, the more critical that it be reclaimed. int sleep = (100 - deltaPercent) / 4; System.Threading.Thread.Sleep(sleep); } } /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.HandleType.GetHandleCount"]/*' /> /// <devdoc> /// Retrieves the outstanding handle count for this /// handle type. /// </devdoc> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal int GetHandleCount() { lock(this) { return handleCount; } } /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.HandleType.NeedCollection"]/*' /> /// <devdoc> /// Determines if this handle type needs a garbage collection pass. /// </devdoc> internal bool NeedCollection() { if (suspendCount > 0){ return false; } if (handleCount > threshHold) { threshHold = handleCount + ((handleCount * deltaPercent) / 100); #if DEBUG_HANDLECOLLECTOR Debug.WriteLine("HC> NeedCollection: increase threshHold to " + threshHold); #endif return true; } // If handle count < threshHold, we don't // need to collect, but if it 10% below the next lowest threshhold we // will bump down a rung. We need to choose a percentage here or else // we will oscillate. // int oldThreshHold = (100 * threshHold) / (100 + deltaPercent); if (oldThreshHold >= initialThreshHold && handleCount < (int)(oldThreshHold * .9F)) { #if DEBUG_HANDLECOLLECTOR Debug.WriteLine("HC> NeedCollection: throttle threshhold " + threshHold + " down to " + oldThreshHold); #endif threshHold = oldThreshHold; } return false; } /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="NativeMethods.HandleCollector.HandleType.Remove"]/*' /> /// <devdoc> /// Removes the given handle from our monitor list. /// </devdoc> internal IntPtr Remove(IntPtr handle) { if( handle == IntPtr.Zero ) { return handle; } int currentCount = 0; lock(this) { handleCount--; #if DEBUG_HANDLECOLLECTOR Debug.Assert(handles.Contains(handle)); handles.Remove(handle); #endif if (handleCount < 0) { System.Diagnostics.Debug.Fail("Handle collector underflow for type '" + name + "'"); handleCount = 0; } currentCount = handleCount; } lock (internalSyncObject){ if (HandleCollector.HandleRemoved != null) { HandleCollector.HandleRemoved(name, handle, currentCount); } } return handle; } } } internal delegate void HandleChangeEventHandler(string handleType, IntPtr handleValue, int currentHandleCount); }
#region Java Info /** * Class GifDecoder - Decodes a GIF file into one or more frames. * <br><pre> * Example: * GifDecoder d = new GifDecoder(); * d.read("sample.gif"); * int n = d.getFrameCount(); * for (int i = 0; i < n; i++) { * BufferedImage frame = d.getFrame(i); // frame i * int t = d.getDelay(i); // display duration of frame in milliseconds * // do something with frame * } * </pre> * No copyright asserted on the source code of this class. May be used for * any purpose, however, refer to the Unisys LZW patent for any additional * restrictions. Please forward any corrections to [email protected]. * * @author Kevin Weiner, FM Software; LZW decoder adapted from John Cristy's ImageMagick. * @version 1.03 November 2003 * */ #endregion using System; using System.Collections; using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace Aga.Controls { public class GifFrame { private Image _image; public Image Image { get { return _image; } } private int _delay; public int Delay { get { return _delay; } } public GifFrame(Image im, int del) { _image = im; _delay = del; } } public class GifDecoder { public const int StatusOK = 0;//File read status: No errors. public const int StatusFormatError = 1; //File read status: Error decoding file (may be partially decoded) public const int StatusOpenError = 2; //Unable to open source. private Stream inStream; private int status; private int width; // full image width private int height; // full image height private bool gctFlag; // global color table used private int gctSize; // size of global color table private int loopCount = 1; // iterations; 0 = repeat forever private int[] gct; // global color table private int[] lct; // local color table private int[] act; // active color table private int bgIndex; // background color index private int bgColor; // background color private int lastBgColor; // previous bg color private int pixelAspect; // pixel aspect ratio private bool lctFlag; // local color table flag private bool interlace; // interlace flag private int lctSize; // local color table size private int ix, iy, iw, ih; // current image rectangle private Rectangle lastRect; // last image rect private Image image; // current frame private Bitmap bitmap; private Image lastImage; // previous frame private byte[] block = new byte[256]; // current data block private int blockSize = 0; // block size // last graphic control extension info private int dispose = 0; // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev private int lastDispose = 0; private bool transparency = false; // use transparent color private int delay = 0; // delay in milliseconds private int transIndex; // transparent color index private const int MaxStackSize = 4096; // max decoder pixel stack size // LZW decoder working arrays private short[] prefix; private byte[] suffix; private byte[] pixelStack; private byte[] pixels; private ArrayList frames; // frames read from current file private int frameCount; private bool _makeTransparent; /** * Gets the number of frames read from file. * @return frame count */ public int FrameCount { get { return frameCount; } } /** * Gets the first (or only) image read. * * @return BufferedImage containing first frame, or null if none. */ public Image Image { get { return GetFrame(0).Image; } } /** * Gets the "Netscape" iteration count, if any. * A count of 0 means repeat indefinitiely. * * @return iteration count if one was specified, else 1. */ public int LoopCount { get { return loopCount; } } public GifDecoder(Stream stream, bool makeTransparent) { _makeTransparent = makeTransparent; if (Read(stream) != 0) throw new InvalidOperationException(); } /** * Creates new frame image from current data (and previous * frames as specified by their disposition codes). */ private int[] GetPixels(Bitmap bitmap) { int [] pixels = new int [ 3 * image.Width * image.Height ]; int count = 0; for (int th = 0; th < image.Height; th++) { for (int tw = 0; tw < image.Width; tw++) { Color color = bitmap.GetPixel(tw, th); pixels[count] = color.R; count++; pixels[count] = color.G; count++; pixels[count] = color.B; count++; } } return pixels; } private void SetPixels(int[] pixels) { int count = 0; for (int th = 0; th < image.Height; th++) { for (int tw = 0; tw < image.Width; tw++) { Color color = Color.FromArgb( pixels[count++] ); bitmap.SetPixel( tw, th, color ); } } if (_makeTransparent) bitmap.MakeTransparent(bitmap.GetPixel(0, 0)); } private void SetPixels() { // expose destination image's pixels as int array // int[] dest = // (( int ) image.getRaster().getDataBuffer()).getData(); int[] dest = GetPixels( bitmap ); // fill in starting image contents based on last image's dispose code if (lastDispose > 0) { if (lastDispose == 3) { // use image before last int n = frameCount - 2; if (n > 0) { lastImage = GetFrame(n - 1).Image; } else { lastImage = null; } } if (lastImage != null) { // int[] prev = // ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData(); int[] prev = GetPixels( new Bitmap( lastImage ) ); Array.Copy(prev, 0, dest, 0, width * height); // copy pixels if (lastDispose == 2) { // fill last image rect area with background color Graphics g = Graphics.FromImage( image ); Color c = Color.Empty; if (transparency) { c = Color.FromArgb( 0, 0, 0, 0 ); // assume background is transparent } else { c = Color.FromArgb( lastBgColor ) ; // c = new Color(lastBgColor); // use given background color } Brush brush = new SolidBrush( c ); g.FillRectangle( brush, lastRect ); brush.Dispose(); g.Dispose(); } } } // copy each source line to the appropriate place in the destination int pass = 1; int inc = 8; int iline = 0; for (int i = 0; i < ih; i++) { int line = i; if (interlace) { if (iline >= ih) { pass++; switch (pass) { case 2 : iline = 4; break; case 3 : iline = 2; inc = 4; break; case 4 : iline = 1; inc = 2; break; } } line = iline; iline += inc; } line += iy; if (line < height) { int k = line * width; int dx = k + ix; // start of line in dest int dlim = dx + iw; // end of dest line if ((k + width) < dlim) { dlim = k + width; // past dest edge } int sx = i * iw; // start of line in source while (dx < dlim) { // map color and insert in destination int index = ((int) pixels[sx++]) & 0xff; int c = act[index]; if (c != 0) { dest[dx] = c; } dx++; } } } SetPixels( dest ); } /** * Gets the image contents of frame n. * * @return BufferedImage representation of frame. */ public GifFrame GetFrame(int n) { if ((n >= 0) && (n < frameCount)) return (GifFrame)frames[n]; else throw new ArgumentOutOfRangeException(); } /** * Gets image size. * * @return GIF image dimensions */ public Size FrameSize { get { return new Size(width, height); } } /** * Reads GIF image from stream * * @param BufferedInputStream containing GIF file. * @return read status code (0 = no errors) */ private int Read( Stream inStream ) { Init(); if ( inStream != null) { this.inStream = inStream; ReadHeader(); if (!Error()) { ReadContents(); if (frameCount < 0) { status = StatusFormatError; } } inStream.Close(); } else { status = StatusOpenError; } return status; } /** * Decodes LZW image data into pixel array. * Adapted from John Cristy's ImageMagick. */ private void DecodeImageData() { int NullCode = -1; int npix = iw * ih; int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi; if ((pixels == null) || (pixels.Length < npix)) { pixels = new byte[npix]; // allocate new pixel array } if (prefix == null) prefix = new short[MaxStackSize]; if (suffix == null) suffix = new byte[MaxStackSize]; if (pixelStack == null) pixelStack = new byte[MaxStackSize + 1]; // Initialize GIF data stream decoder. data_size = Read(); clear = 1 << data_size; end_of_information = clear + 1; available = clear + 2; old_code = NullCode; code_size = data_size + 1; code_mask = (1 << code_size) - 1; for (code = 0; code < clear; code++) { prefix[code] = 0; suffix[code] = (byte) code; } // Decode GIF pixel stream. datum = bits = count = first = top = pi = bi = 0; for (i = 0; i < npix;) { if (top == 0) { if (bits < code_size) { // Load bytes until there are enough bits for a code. if (count == 0) { // Read a new data block. count = ReadBlock(); if (count <= 0) break; bi = 0; } datum += (((int) block[bi]) & 0xff) << bits; bits += 8; bi++; count--; continue; } // Get the next code. code = datum & code_mask; datum >>= code_size; bits -= code_size; // Interpret the code if ((code > available) || (code == end_of_information)) break; if (code == clear) { // Reset decoder. code_size = data_size + 1; code_mask = (1 << code_size) - 1; available = clear + 2; old_code = NullCode; continue; } if (old_code == NullCode) { pixelStack[top++] = suffix[code]; old_code = code; first = code; continue; } in_code = code; if (code == available) { pixelStack[top++] = (byte) first; code = old_code; } while (code > clear) { pixelStack[top++] = suffix[code]; code = prefix[code]; } first = ((int) suffix[code]) & 0xff; // Add a new string to the string table, if (available >= MaxStackSize) break; pixelStack[top++] = (byte) first; prefix[available] = (short) old_code; suffix[available] = (byte) first; available++; if (((available & code_mask) == 0) && (available < MaxStackSize)) { code_size++; code_mask += available; } old_code = in_code; } // Pop a pixel off the pixel stack. top--; pixels[pi++] = pixelStack[top]; i++; } for (i = pi; i < npix; i++) { pixels[i] = 0; // clear missing pixels } } /** * Returns true if an error was encountered during reading/decoding */ private bool Error() { return status != StatusOK; } /** * Initializes or re-initializes reader */ private void Init() { status = StatusOK; frameCount = 0; frames = new ArrayList(); gct = null; lct = null; } /** * Reads a single byte from the input stream. */ private int Read() { int curByte = 0; try { curByte = inStream.ReadByte(); } catch (IOException) { status = StatusFormatError; } return curByte; } /** * Reads next variable length block from input. * * @return number of bytes stored in "buffer" */ private int ReadBlock() { blockSize = Read(); int n = 0; if (blockSize > 0) { try { int count = 0; while (n < blockSize) { count = inStream.Read(block, n, blockSize - n); if (count == -1) break; n += count; } } catch (IOException) { } if (n < blockSize) { status = StatusFormatError; } } return n; } /** * Reads color table as 256 RGB integer values * * @param ncolors int number of colors to read * @return int array containing 256 colors (packed ARGB with full alpha) */ private int[] ReadColorTable(int ncolors) { int nbytes = 3 * ncolors; int[] tab = null; byte[] c = new byte[nbytes]; int n = 0; try { n = inStream.Read(c, 0, c.Length ); } catch (IOException) { } if (n < nbytes) { status = StatusFormatError; } else { tab = new int[256]; // max size to avoid bounds checks int i = 0; int j = 0; while (i < ncolors) { int r = ((int) c[j++]) & 0xff; int g = ((int) c[j++]) & 0xff; int b = ((int) c[j++]) & 0xff; tab[i++] = ( int ) ( 0xff000000 | (r << 16) | (g << 8) | b ); } } return tab; } /** * Main file parser. Reads GIF content blocks. */ private void ReadContents() { // read GIF file content blocks bool done = false; while (!(done || Error())) { int code = Read(); switch (code) { case 0x2C : // image separator ReadImage(); break; case 0x21 : // extension code = Read(); switch (code) { case 0xf9 : // graphics control extension ReadGraphicControlExt(); break; case 0xff : // application extension ReadBlock(); String app = ""; for (int i = 0; i < 11; i++) { app += (char) block[i]; } if (app.Equals("NETSCAPE2.0")) { ReadNetscapeExt(); } else Skip(); // don't care break; default : // uninteresting extension Skip(); break; } break; case 0x3b : // terminator done = true; break; case 0x00 : // bad byte, but keep going and see what happens break; default : status = StatusFormatError; break; } } } /** * Reads Graphics Control Extension values */ private void ReadGraphicControlExt() { Read(); // block size int packed = Read(); // packed fields dispose = (packed & 0x1c) >> 2; // disposal method if (dispose == 0) { dispose = 1; // elect to keep old image if discretionary } transparency = (packed & 1) != 0; delay = ReadShort() * 10; // delay in milliseconds transIndex = Read(); // transparent color index Read(); // block terminator } /** * Reads GIF file header information. */ private void ReadHeader() { String id = ""; for (int i = 0; i < 6; i++) { id += (char) Read(); } if (!id.StartsWith("GIF")) { status = StatusFormatError; return; } ReadLSD(); if (gctFlag && !Error()) { gct = ReadColorTable(gctSize); bgColor = gct[bgIndex]; } } /** * Reads next frame image */ private void ReadImage() { ix = ReadShort(); // (sub)image position & size iy = ReadShort(); iw = ReadShort(); ih = ReadShort(); int packed = Read(); lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace = (packed & 0x40) != 0; // 2 - interlace flag // 3 - sort flag // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color table size if (lctFlag) { lct = ReadColorTable(lctSize); // read table act = lct; // make local table active } else { act = gct; // make global table active if (bgIndex == transIndex) bgColor = 0; } int save = 0; if (transparency) { save = act[transIndex]; act[transIndex] = 0; // set transparent color if specified } if (act == null) { status = StatusFormatError; // no color table defined } if (Error()) return; DecodeImageData(); // decode pixel data Skip(); if (Error()) return; frameCount++; // create new image to receive frame data // image = // new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); bitmap = new Bitmap( width, height ); image = bitmap; SetPixels(); // transfer pixel data to image frames.Add(new GifFrame(bitmap, delay)); // add image to frame list if (transparency) { act[transIndex] = save; } ResetFrame(); } /** * Reads Logical Screen Descriptor */ private void ReadLSD() { // logical screen size width = ReadShort(); height = ReadShort(); // packed fields int packed = Read(); gctFlag = (packed & 0x80) != 0; // 1 : global color table flag // 2-4 : color resolution // 5 : gct sort flag gctSize = 2 << (packed & 7); // 6-8 : gct size bgIndex = Read(); // background color index pixelAspect = Read(); // pixel aspect ratio } /** * Reads Netscape extenstion to obtain iteration count */ private void ReadNetscapeExt() { do { ReadBlock(); if (block[0] == 1) { // loop count sub-block int b1 = ((int) block[1]) & 0xff; int b2 = ((int) block[2]) & 0xff; loopCount = (b2 << 8) | b1; } } while ((blockSize > 0) && !Error()); } /** * Reads next 16-bit value, LSB first */ private int ReadShort() { // read 16-bit value, LSB first return Read() | (Read() << 8); } /** * Resets frame state for reading next image. */ private void ResetFrame() { lastDispose = dispose; lastRect = new Rectangle(ix, iy, iw, ih); lastImage = image; lastBgColor = bgColor; // int dispose = 0; lct = null; } /** * Skips variable length blocks up to and including * next zero length block. */ private void Skip() { do { ReadBlock(); } while ((blockSize > 0) && !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. #pragma warning disable 0183 // The given expression is always of the provided ('X') type using System; using System.ComponentModel; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; // primitives / CLR Types // interfaces public interface IEmpty { } public interface INotEmpty { void DoNothing(); } // generic interfaces public interface IEmptyGen<T> { } public interface INotEmptyGen<T> { void DoNothing(); } // struct public struct EmptyStruct { } public struct NotEmptyStruct { public int Field; } public struct NotEmptyStructQ { public int? Field; } public struct NotEmptyStructA { public int[] Field; } public struct NotEmptyStructQA { public int?[] Field; } // generic structs public struct EmptyStructGen<T> { } public struct NotEmptyStructGen<T> { public T Field; } public struct NotEmptyStructConstrainedGen<T> where T : struct { public T Field; } public struct NotEmptyStructConstrainedGenA<T> where T : struct { public T[] Field; } public struct NotEmptyStructConstrainedGenQ<T> where T : struct { public T? Field; } public struct NotEmptyStructConstrainedGenQA<T> where T : struct { public T?[] Field; } // nested struct public struct NestedStruct { public struct Nested { } } public struct NestedStructGen<T> { public struct Nested { } } // struct with Field Offset [StructLayout(LayoutKind.Explicit)] public struct ExplicitFieldOffsetStruct { [FieldOffset(0)] public int Field00; [FieldOffset(0x0f)] public int Field15; } // struct with Attributes internal struct MarshalAsStruct { [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string StringField; } // struct implement interfaces internal struct ImplementOneInterface : IEmpty { } internal struct ImplementTwoInterface : IEmpty, INotEmpty { public void DoNothing() { } } internal struct ImplementOneInterfaceGen<T> : IEmptyGen<T> { } internal struct ImplementTwoInterfaceGen<T> : IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } } internal struct ImplementAllInterface<T> : IEmpty, INotEmpty, IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } void INotEmptyGen<T>.DoNothing() { } } // enums public enum IntE { start = 1, } public enum ByteE : byte { start = 1, } public enum LongE : long { start = 1, } // other intersting structs public struct WithMultipleGCHandleStruct { public GCHandle H1; public GCHandle H2; public GCHandle H3; public GCHandle H4; public GCHandle H5; } public struct WithOnlyFXTypeStruct { public Guid GUID; public decimal DECIMAL; } public struct MixedAllStruct { public int INT; public int? IntQ; public int?[] IntQA; public string STRING; public IntE INTE; public EmptyClass EMPTYCLASS; public IEmpty IEMPTY; public EmptyStruct EMPTYSTRUCT; public IEmptyGen<int> IEMPTYGEN; public EmptyStructGen<int> EMPTYSTRUCTGEN; public WithOnlyFXTypeStruct WITHONLYFXTYPESTRUCT; public GCHandle GCHANDLE; } // other types public struct EmptyClass { } public struct NotEmptyClass { public int Field; } public struct EmptyClassGen<T> { } public struct NotEmptyClassGen<T> { public T Field; } public struct NotEmptyClassConstrainedGen<T> where T : class { public T Field; } public struct NestedClass { public struct Nested { } } public struct NestedClassGen<T> { public struct Nested { } } internal class ImplementOneInterfaceC : IEmpty { } internal class ImplementTwoInterfaceC : IEmpty, INotEmpty { public void DoNothing() { } } internal class ImplementOneInterfaceGenC<T> : IEmptyGen<T> { } internal class ImplementTwoInterfaceGenC<T> : IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } } internal class ImplementAllInterfaceC<T> : IEmpty, INotEmpty, IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } void INotEmptyGen<T>.DoNothing() { } } public sealed class SealedClass { } public delegate void SimpleDelegate(); public delegate void GenericDelegate<T>(); // ExitCode public static class ExitCode { public static int Failed = 101; public static int Passed = 100; } // Create Value Instance internal static class Helper { public static GCHandle GCHANDLE; static Helper() { GCHANDLE = GCHandle.Alloc(Console.Out); AssemblyLoadContext currentContext = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); if (currentContext != null) { currentContext.Unloading += Context_Unloading; } } private static void Context_Unloading(AssemblyLoadContext obj) { GCHANDLE.Free(); } public static char Create(char val) { return 'c'; } public static bool Create(bool val) { return true; } public static byte Create(byte val) { return 0x08; } public static sbyte Create(sbyte val) { return -0x0e; } public static short Create(short val) { return -0x0f; } public static ushort Create(ushort val) { return 0xff; } public static int Create(int val) { return 100; } public static uint Create(uint val) { return 200; } public static long Create(long val) { return int.MaxValue; } public static ulong Create(ulong val) { return 300; } public static float Create(float val) { return 1.15f; } public static double Create(double val) { return 0.05; } public static decimal Create(decimal val) { return 1.0M; } public static IntPtr Create(IntPtr val) { return (IntPtr)1000; } public static UIntPtr Create(UIntPtr val) { return (UIntPtr)2000; } public static Guid Create(Guid val) { return new Guid("00020810-0001-0000-C000-000000000046"); } public static GCHandle Create(GCHandle val) { return GCHANDLE; } public static ByteE Create(ByteE val) { return (ByteE)9; } public static IntE Create(IntE val) { return (IntE)55; } public static LongE Create(LongE val) { return (LongE)34; } public static EmptyStruct Create(EmptyStruct val) { return new EmptyStruct(); } public static NotEmptyStruct Create(NotEmptyStruct val) { NotEmptyStruct ne = new NotEmptyStruct(); ne.Field = 100; return ne; } public static NotEmptyStructQ Create(NotEmptyStructQ val) { NotEmptyStructQ neq = new NotEmptyStructQ(); neq.Field = 101; return neq; } public static NotEmptyStructA Create(NotEmptyStructA val) { NotEmptyStructA nea = new NotEmptyStructA(); nea.Field = new int[] { 10 }; return nea; } public static NotEmptyStructQA Create(NotEmptyStructQA val) { NotEmptyStructQA neq = new NotEmptyStructQA(); neq.Field = new int?[] { 10 }; return neq; } public static EmptyStructGen<int> Create(EmptyStructGen<int> val) { return new EmptyStructGen<int>(); } public static NotEmptyStructGen<int> Create(NotEmptyStructGen<int> val) { NotEmptyStructGen<int> ne = new NotEmptyStructGen<int>(); ne.Field = 88; return ne; } public static NotEmptyStructConstrainedGen<int> Create(NotEmptyStructConstrainedGen<int> val) { NotEmptyStructConstrainedGen<int> ne = new NotEmptyStructConstrainedGen<int>(); ne.Field = 1010; return ne; } public static NotEmptyStructConstrainedGenA<int> Create(NotEmptyStructConstrainedGenA<int> val) { NotEmptyStructConstrainedGenA<int> neq = new NotEmptyStructConstrainedGenA<int>(); neq.Field = new int[] { 11 }; return neq; } public static NotEmptyStructConstrainedGenQ<int> Create(NotEmptyStructConstrainedGenQ<int> val) { NotEmptyStructConstrainedGenQ<int> neq = new NotEmptyStructConstrainedGenQ<int>(); neq.Field = 12; return neq; } public static NotEmptyStructConstrainedGenQA<int> Create(NotEmptyStructConstrainedGenQA<int> val) { NotEmptyStructConstrainedGenQA<int> neq = new NotEmptyStructConstrainedGenQA<int>(); neq.Field = new int?[] { 17 }; return neq; } public static NestedStruct Create(NestedStruct val) { NestedStruct ns = new NestedStruct(); return ns; } public static NestedStructGen<int> Create(NestedStructGen<int> val) { NestedStructGen<int> nsg = new NestedStructGen<int>(); return nsg; } public static ExplicitFieldOffsetStruct Create(ExplicitFieldOffsetStruct val) { ExplicitFieldOffsetStruct epl = new ExplicitFieldOffsetStruct(); epl.Field00 = 40; epl.Field15 = 15; return epl; } public static MarshalAsStruct Create(MarshalAsStruct val) { MarshalAsStruct ma = new MarshalAsStruct(); ma.StringField = "Nullable"; return ma; } public static ImplementOneInterface Create(ImplementOneInterface val) { ImplementOneInterface imp = new ImplementOneInterface(); return imp; } public static ImplementTwoInterface Create(ImplementTwoInterface val) { ImplementTwoInterface imp = new ImplementTwoInterface(); return imp; } public static ImplementOneInterfaceGen<int> Create(ImplementOneInterfaceGen<int> val) { ImplementOneInterfaceGen<int> imp = new ImplementOneInterfaceGen<int>(); return imp; } public static ImplementTwoInterfaceGen<int> Create(ImplementTwoInterfaceGen<int> val) { ImplementTwoInterfaceGen<int> imp = new ImplementTwoInterfaceGen<int>(); return imp; } public static ImplementAllInterface<int> Create(ImplementAllInterface<int> val) { ImplementAllInterface<int> imp = new ImplementAllInterface<int>(); return imp; } public static WithMultipleGCHandleStruct Create(WithMultipleGCHandleStruct val) { WithMultipleGCHandleStruct mgch = new WithMultipleGCHandleStruct(); mgch.H1 = GCHANDLE; mgch.H2 = GCHANDLE; mgch.H3 = GCHANDLE; mgch.H4 = GCHANDLE; mgch.H5 = GCHANDLE; return mgch; } public static WithOnlyFXTypeStruct Create(WithOnlyFXTypeStruct val) { WithOnlyFXTypeStruct wofx = new WithOnlyFXTypeStruct(); wofx.DECIMAL = 50.0m; wofx.GUID = Create(default(Guid)); return wofx; } public static MixedAllStruct Create(MixedAllStruct val) { MixedAllStruct mas; mas.INT = 10; mas.IntQ = null; mas.IntQA = new int?[] { 10 }; mas.STRING = "Nullable"; mas.INTE = Create(default(IntE)); mas.EMPTYCLASS = new EmptyClass(); mas.IEMPTY = Create(default(ImplementOneInterface)); mas.EMPTYSTRUCT = Create(default(EmptyStruct)); mas.IEMPTYGEN = Create(default(ImplementOneInterfaceGen<int>)); mas.EMPTYSTRUCTGEN = Create(default(EmptyStructGen<int>)); mas.WITHONLYFXTYPESTRUCT = Create(default(WithOnlyFXTypeStruct)); mas.GCHANDLE = Create(default(GCHandle)); return mas; } public static bool Compare(char val, char val1) { return val == val1; } public static bool Compare(bool val, bool val1) { return val == val1; } public static bool Compare(byte val, byte val1) { return val == val1; } public static bool Compare(sbyte val, sbyte val1) { return val == val1; } public static bool Compare(short val, short val1) { return val == val1; } public static bool Compare(ushort val, ushort val1) { return val == val1; } public static bool Compare(int val, int val1) { return val == val1; } public static bool Compare(uint val, uint val1) { return val == val1; } public static bool Compare(long val, long val1) { return val == val1; } public static bool Compare(ulong val, ulong val1) { return val == val1; } public static bool Compare(float val, float val1) { return val == val1; } public static bool Compare(double val, double val1) { return val == val1; } public static bool Compare(decimal val, decimal val1) { return val == val1; } public static bool Compare(IntPtr val, IntPtr val1) { return val == val1; } public static bool Compare(UIntPtr val, UIntPtr val1) { return val == val1; } public static bool Compare(Guid val, Guid val1) { return val == val1; } public static bool Compare(GCHandle val, GCHandle val1) { return val == val1; } public static bool Compare(ByteE val, ByteE val1) { return val == val1; } public static bool Compare(IntE val, IntE val1) { return val == val1; } public static bool Compare(LongE val, LongE val1) { return val == val1; } public static bool Compare(EmptyStruct val, EmptyStruct val1) { return val.Equals(val1); } public static bool Compare(NotEmptyStruct val, NotEmptyStruct val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructQ val, NotEmptyStructQ val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructA val, NotEmptyStructA val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(NotEmptyStructQA val, NotEmptyStructQA val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(EmptyStructGen<int> val, EmptyStructGen<int> val1) { return val.Equals(val1); } public static bool Compare(NotEmptyStructGen<int> val, NotEmptyStructGen<int> val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructConstrainedGen<int> val, NotEmptyStructConstrainedGen<int> val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructConstrainedGenA<int> val, NotEmptyStructConstrainedGenA<int> val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(NotEmptyStructConstrainedGenQ<int> val, NotEmptyStructConstrainedGenQ<int> val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructConstrainedGenQA<int> val, NotEmptyStructConstrainedGenQA<int> val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(NestedStruct val, NestedStruct val1) { return val.Equals(val1); } public static bool Compare(NestedStructGen<int> val, NestedStructGen<int> val1) { return val.Equals(val1); } public static bool Compare(ExplicitFieldOffsetStruct val, ExplicitFieldOffsetStruct val1) { return (val.Field00 == val1.Field00) && (val.Field15 == val1.Field15); } public static bool Compare(MarshalAsStruct val, MarshalAsStruct val1) { return val.Equals(val1); } public static bool Compare(ImplementOneInterface val, ImplementOneInterface val1) { return (val is IEmpty) && val.Equals(val1); } public static bool Compare(ImplementTwoInterface val, ImplementTwoInterface val1) { return (val is IEmpty) && val is INotEmpty && val.Equals(val1); } public static bool Compare(ImplementOneInterfaceGen<int> val, ImplementOneInterfaceGen<int> val1) { return val is IEmptyGen<int> && val.Equals(val1); } public static bool Compare(ImplementTwoInterfaceGen<int> val, ImplementTwoInterfaceGen<int> val1) { return val is IEmptyGen<int> && val is INotEmptyGen<int> && val.Equals(val1); } public static bool Compare(ImplementAllInterface<int> val, ImplementAllInterface<int> val1) { return val is IEmpty && val is INotEmpty && val is IEmptyGen<int> && val is INotEmptyGen<int> && val.Equals(val1); } public static bool Compare(WithMultipleGCHandleStruct val, WithMultipleGCHandleStruct val1) { return val.H1 == val1.H1 && val.H2 == val1.H2 && val.H3 == val1.H3 && val.H4 == val1.H4 && val.H5 == val1.H5; } public static bool Compare(WithOnlyFXTypeStruct val, WithOnlyFXTypeStruct val1) { return val.GUID == val1.GUID && val.DECIMAL == val1.DECIMAL; } public static bool Compare(MixedAllStruct val, MixedAllStruct val1) { return val.INT == val1.INT && val.IntQ == val1.IntQ && val.IntQA[0] == val1.IntQA[0] && val.STRING == val1.STRING && val.INTE == val1.INTE && val.EMPTYCLASS.Equals(val1.EMPTYCLASS) && val.IEMPTY.Equals(val1.IEMPTY) && Compare(val.EMPTYSTRUCT, val1.EMPTYSTRUCT) && val.IEMPTYGEN.Equals(val1.IEMPTYGEN) && Compare(val.EMPTYSTRUCTGEN, val1.EMPTYSTRUCTGEN) && Compare(val.WITHONLYFXTYPESTRUCT, val1.WITHONLYFXTYPESTRUCT) && Compare(val.GCHANDLE, val1.GCHANDLE); } public static bool Compare(char? val, char val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(bool? val, bool val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(byte? val, byte val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(sbyte? val, sbyte val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(short? val, short val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ushort? val, ushort val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(int? val, int val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(uint? val, uint val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(long? val, long val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ulong? val, ulong val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(float? val, float val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(double? val, double val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(decimal? val, decimal val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(IntPtr? val, IntPtr val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(UIntPtr? val, UIntPtr val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(Guid? val, Guid val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(GCHandle? val, GCHandle val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ByteE? val, ByteE val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(IntE? val, IntE val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(LongE? val, LongE val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(EmptyStruct? val, EmptyStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStruct? val, NotEmptyStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructQ? val, NotEmptyStructQ val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructA? val, NotEmptyStructA val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructQA? val, NotEmptyStructQA val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(EmptyStructGen<int>? val, EmptyStructGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructGen<int>? val, NotEmptyStructGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGen<int>? val, NotEmptyStructConstrainedGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGenA<int>? val, NotEmptyStructConstrainedGenA<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGenQ<int>? val, NotEmptyStructConstrainedGenQ<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGenQA<int>? val, NotEmptyStructConstrainedGenQA<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NestedStruct? val, NestedStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NestedStructGen<int>? val, NestedStructGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ExplicitFieldOffsetStruct? val, ExplicitFieldOffsetStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(MarshalAsStruct? val, MarshalAsStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementOneInterface? val, ImplementOneInterface val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementTwoInterface? val, ImplementTwoInterface val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementOneInterfaceGen<int>? val, ImplementOneInterfaceGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementTwoInterfaceGen<int>? val, ImplementTwoInterfaceGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementAllInterface<int>? val, ImplementAllInterface<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(WithMultipleGCHandleStruct? val, WithMultipleGCHandleStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(WithOnlyFXTypeStruct? val, WithOnlyFXTypeStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(MixedAllStruct? val, MixedAllStruct val1) { return val == null ? false : Compare(val.Value, val1); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.Mvc.Async; using Abp.Auditing; using Abp.Authorization; using Abp.Collections.Extensions; using Abp.Configuration; using Abp.Localization; using Abp.Localization.Sources; using Abp.Reflection; using Abp.Runtime.Session; using Abp.Timing; using Abp.Web.Models; using Abp.Web.Mvc.Controllers.Results; using Castle.Core.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Abp.Web.Mvc.Controllers { /// <summary> /// Base class for all MVC Controllers in Abp system. /// </summary> public abstract class AbpController : Controller { /// <summary> /// Gets current session information. /// </summary> public IAbpSession AbpSession { get; set; } /// <summary> /// Reference to the permission manager. /// </summary> public IPermissionManager PermissionManager { get; set; } /// <summary> /// Reference to the setting manager. /// </summary> public ISettingManager SettingManager { get; set; } /// <summary> /// Reference to the permission checker. /// </summary> public IPermissionChecker PermissionChecker { protected get; set; } /// <summary> /// Reference to the localization manager. /// </summary> public ILocalizationManager LocalizationManager { protected get; set; } /// <summary> /// Gets/sets name of the localization source that is used in this application service. /// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods. /// </summary> protected string LocalizationSourceName { get; set; } /// <summary> /// Gets localization source. /// It's valid if <see cref="LocalizationSourceName"/> is set. /// </summary> protected ILocalizationSource LocalizationSource { get { if (LocalizationSourceName == null) { throw new AbpException("Must set LocalizationSourceName before, in order to get LocalizationSource"); } if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName) { _localizationSource = LocalizationManager.GetSource(LocalizationSourceName); } return _localizationSource; } } private ILocalizationSource _localizationSource; /// <summary> /// Reference to the logger to write logs. /// </summary> public ILogger Logger { get; set; } /// <summary> /// Gets current session information. /// </summary> [Obsolete("Use AbpSession property instead. CurrentSetting will be removed in future releases.")] protected IAbpSession CurrentSession { get { return AbpSession; } } /// <summary> /// This object i used to measure an action execute duration. /// </summary> private Stopwatch _actionStopwatch; private AuditInfo _auditInfo; public IAuditingConfiguration AuditingConfiguration { get; set; } public IAuditInfoProvider AuditInfoProvider { get; set; } public IAuditingStore AuditingStore { get; set; } /// <summary> /// Constructor. /// </summary> protected AbpController() { AbpSession = NullAbpSession.Instance; Logger = NullLogger.Instance; LocalizationManager = NullLocalizationManager.Instance; PermissionChecker = NullPermissionChecker.Instance; AuditingStore = SimpleLogAuditingStore.Instance; } /// <summary> /// Gets localized string for given key name and current language. /// </summary> /// <param name="name">Key name</param> /// <returns>Localized string</returns> protected virtual string L(string name) { return LocalizationSource.GetString(name); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, params object[] args) { return LocalizationSource.GetString(name, args); } /// <summary> /// Gets localized string for given key name and specified culture information. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <returns>Localized string</returns> protected virtual string L(string name, CultureInfo culture) { return LocalizationSource.GetString(name, culture); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, CultureInfo culture, params object[] args) { return LocalizationSource.GetString(name, culture, args); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected Task<bool> IsGrantedAsync(string permissionName) { return PermissionChecker.IsGrantedAsync(permissionName); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected bool IsGranted(string permissionName) { return PermissionChecker.IsGranted(permissionName); } /// <summary> /// Json the specified data, contentType, contentEncoding and behavior. /// </summary> /// <param name="data">Data.</param> /// <param name="contentType">Content type.</param> /// <param name="contentEncoding">Content encoding.</param> /// <param name="behavior">Behavior.</param> protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { if (data == null) { data = new AjaxResponse(); } else if (!ReflectionHelper.IsAssignableToGenericType(data.GetType(), typeof(AjaxResponse<>))) { data = new AjaxResponse(data); } return new AbpJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; } protected override void OnActionExecuting(ActionExecutingContext filterContext) { HandleAuditingBeforeAction(filterContext); base.OnActionExecuting(filterContext); } protected override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HandleAuditingAfterAction(filterContext); } #region Auditing private static MethodInfo GetMethodInfo(ActionDescriptor actionDescriptor) { if (actionDescriptor is ReflectedActionDescriptor) { return ((ReflectedActionDescriptor)actionDescriptor).MethodInfo; } if (actionDescriptor is ReflectedAsyncActionDescriptor) { return ((ReflectedAsyncActionDescriptor)actionDescriptor).MethodInfo; } if (actionDescriptor is TaskAsyncActionDescriptor) { return ((TaskAsyncActionDescriptor)actionDescriptor).MethodInfo; } throw new AbpException("Could not get MethodInfo for the action '" + actionDescriptor.ActionName + "' of controller '" + actionDescriptor.ControllerDescriptor.ControllerName + "'."); } private void HandleAuditingBeforeAction(ActionExecutingContext filterContext) { if (!ShouldSaveAudit(filterContext)) { _auditInfo = null; return; } var methodInfo = GetMethodInfo(filterContext.ActionDescriptor); _actionStopwatch = Stopwatch.StartNew(); _auditInfo = new AuditInfo { TenantId = AbpSession.TenantId, UserId = AbpSession.UserId, ServiceName = methodInfo.DeclaringType != null ? methodInfo.DeclaringType.FullName : filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, MethodName = methodInfo.Name, Parameters = ConvertArgumentsToJson(filterContext.ActionParameters), ExecutionTime = Clock.Now }; } private void HandleAuditingAfterAction(ActionExecutedContext filterContext) { if (_auditInfo == null || _actionStopwatch == null) { return; } _actionStopwatch.Stop(); _auditInfo.ExecutionDuration = Convert.ToInt32(_actionStopwatch.Elapsed.TotalMilliseconds); _auditInfo.Exception = filterContext.Exception; if (AuditInfoProvider != null) { AuditInfoProvider.Fill(_auditInfo); } AuditingStore.Save(_auditInfo); } private bool ShouldSaveAudit(ActionExecutingContext filterContext) { if (AuditingConfiguration == null) { return false; } if (!AuditingConfiguration.MvcControllers.IsEnabled) { return false; } if (filterContext.IsChildAction && !AuditingConfiguration.MvcControllers.IsEnabledForChildActions) { return false; } return AuditingHelper.ShouldSaveAudit( GetMethodInfo(filterContext.ActionDescriptor), AuditingConfiguration, AbpSession, true ); } private string ConvertArgumentsToJson(IDictionary<string, object> arguments) { try { if (arguments.IsNullOrEmpty()) { return "{}"; } var dictionary = new Dictionary<string, object>(); foreach (var argument in arguments) { dictionary[argument.Key] = argument.Value; } return JsonConvert.SerializeObject( dictionary, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } catch (Exception ex) { Logger.Warn("Could not serialize arguments for method: " + _auditInfo.ServiceName + "." + _auditInfo.MethodName); Logger.Warn(ex.ToString(), ex); return "{}"; } } #endregion } }
//----------------------------------------------------------------------- // <copyright company="CoApp Project"> // ResourceLib Original Code from http://resourcelib.codeplex.com // Original Copyright (c) 2008-2009 Vestris Inc. // Changes Copyright (c) 2011 Garrett Serack . All rights reserved. // </copyright> // <license> // MIT License // You may freely use and distribute this software under the terms of the following license agreement. // // 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 // </license> //----------------------------------------------------------------------- namespace ClrPlus.Windows.PeBinary.ResourceLib { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using Api; using Api.Enumerations; using Core.Collections; /// <summary> /// Resource info manager. /// </summary> public class ResourceInfo : IEnumerable<Resource>, IDisposable { private IntPtr _hModule = IntPtr.Zero; private Exception _innerException; private List<ResourceId> _resourceTypes; private IDictionary<ResourceId, List<Resource>> _resources; /// <summary> /// A dictionary of resources, the key is the resource type, eg. "REGISTRY" or "16" (version). /// </summary> public IDictionary<ResourceId, List<Resource>> Resources { get { return _resources; } } /// <summary> /// A shortcut for available resource types. /// </summary> public List<ResourceId> ResourceTypes { get { return _resourceTypes; } } /// <summary> /// A collection of resources. /// </summary> /// <param name="type">Resource type.</param> /// <returns>A collection of resources of a given type.</returns> public List<Resource> this[ResourceTypes type] { get { return _resources[new ResourceId(type)]; } set { _resources[new ResourceId(type)] = value; } } /// <summary> /// A collection of resources. /// </summary> /// <param name="type">Resource type.</param> /// <returns>A collection of resources of a given type.</returns> public List<Resource> this[string type] { get { return _resources[new ResourceId(type)]; } set { _resources[new ResourceId(type)] = value; } } #region IDisposable Members /// <summary> /// Dispose resource info object. /// </summary> public void Dispose() { Unload(); } #endregion #region IEnumerable<Resource> Members /// <summary> /// Enumerates all resources within this resource info collection. /// </summary> /// <returns>Resources enumerator.</returns> public IEnumerator<Resource> GetEnumerator() { var resourceTypesEnumerator = _resources.GetEnumerator(); while (resourceTypesEnumerator.MoveNext()) { var resourceEnumerator = resourceTypesEnumerator.Current.Value.GetEnumerator(); while (resourceEnumerator.MoveNext()) { yield return resourceEnumerator.Current; } } } /// <summary> /// Enumerates all resources within this resource info collection. /// </summary> /// <returns>Resources enumerator.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Unload the previously loaded module. /// </summary> public void Unload() { if (_hModule != IntPtr.Zero) { Kernel32.FreeLibrary(_hModule); _hModule = IntPtr.Zero; } _innerException = null; } /// <summary> /// Load an executable or a DLL and read its resources. /// </summary> /// <param name="filename">Source filename.</param> public void Load(string filename) { Unload(); _resourceTypes = new List<ResourceId>(); _resources = new XDictionary<ResourceId, List<Resource>>(); // load DLL _hModule = Kernel32.LoadLibraryEx(filename, IntPtr.Zero, Kernel32Contants.DONT_RESOLVE_DLL_REFERENCES | Kernel32Contants.LOAD_LIBRARY_AS_DATAFILE); if (IntPtr.Zero == _hModule) { throw new Win32Exception(Marshal.GetLastWin32Error()); } try { // enumerate resource types // for each type, enumerate resource names // for each name, enumerate resource languages // for each resource language, enumerate actual resources if (!Kernel32.EnumResourceTypes(_hModule, EnumResourceTypesImpl, IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } catch (Exception ex) { throw new LoadException(string.Format("Error loading '{0}'.", filename), _innerException, ex); } } /// <summary> /// Enumerate resource types. /// </summary> /// <param name="hModule">Module handle.</param> /// <param name="lpszType">Resource type.</param> /// <param name="lParam">Additional parameter.</param> /// <returns>TRUE if successful.</returns> private bool EnumResourceTypesImpl(IntPtr hModule, IntPtr lpszType, IntPtr lParam) { var type = new ResourceId(lpszType); _resourceTypes.Add(type); // enumerate resource names if (!Kernel32.EnumResourceNames(hModule, lpszType, EnumResourceNamesImpl, IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return true; } /// <summary> /// Enumerate resource names within a resource by type /// </summary> /// <param name="hModule">Module handle.</param> /// <param name="lpszType">Resource type.</param> /// <param name="lpszName">Resource name.</param> /// <param name="lParam">Additional parameter.</param> /// <returns>TRUE if successful.</returns> private bool EnumResourceNamesImpl(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, IntPtr lParam) { if (!Kernel32.EnumResourceLanguages(hModule, lpszType, lpszName, EnumResourceLanguages, IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return true; } /// <summary> /// Create a resource of a given type. /// </summary> /// <param name="hModule">Module handle.</param> /// <param name="hResourceGlobal">Pointer to the resource in memory.</param> /// <param name="type">Resource type.</param> /// <param name="name">Resource name.</param> /// <param name="wIDLanguage">Language ID.</param> /// <param name="size">Size of resource.</param> /// <returns>A specialized or a generic resource.</returns> protected Resource CreateResource(IntPtr hModule, IntPtr hResourceGlobal, ResourceId type, ResourceId name, UInt16 wIDLanguage, int size) { if (type.IsIntResource()) { switch (type.ResourceType) { case Api.Enumerations.ResourceTypes.RT_VERSION: return new VersionResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_GROUP_CURSOR: return new CursorDirectoryResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_GROUP_ICON: return new IconDirectoryResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_MANIFEST: return new ManifestResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_BITMAP: return new BitmapResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_MENU: return new MenuResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_DIALOG: return new DialogResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_STRING: return new StringResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_FONTDIR: return new FontDirectoryResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_FONT: return new FontResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); case Api.Enumerations.ResourceTypes.RT_ACCELERATOR: return new AcceleratorResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); } } return new GenericResource(hModule, hResourceGlobal, type, name, wIDLanguage, size); } /// <summary> /// Enumerate resource languages within a resource by name /// </summary> /// <param name="hModule">Module handle.</param> /// <param name="lpszType">Resource type.</param> /// <param name="lpszName">Resource name.</param> /// <param name="wIDLanguage">Language ID.</param> /// <param name="lParam">Additional parameter.</param> /// <returns>TRUE if successful.</returns> private bool EnumResourceLanguages(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, UInt16 wIDLanguage, IntPtr lParam) { List<Resource> resources = null; var type = new ResourceId(lpszType); if (!_resources.TryGetValue(type, out resources)) { resources = new List<Resource>(); _resources[type] = resources; } var name = new ResourceId(lpszName); var hResource = Kernel32.FindResourceEx(hModule, lpszType, lpszName, wIDLanguage); var hResourceGlobal = Kernel32.LoadResource(hModule, hResource); var size = Kernel32.SizeofResource(hModule, hResource); try { resources.Add(CreateResource(hModule, hResourceGlobal, type, name, wIDLanguage, size)); } catch (Exception ex) { _innerException = new Exception(string.Format("Error loading resource '{0}' {1} ({2}).", name, type.TypeName, wIDLanguage), ex); throw ex; } return true; } /// <summary> /// Save resource to a file. /// </summary> /// <param name="filename">Target filename.</param> public void Save(string filename) { throw new NotImplementedException(); } } }
using System.Globalization; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; namespace Meziantou.Framework.Templating; public class Template { private const string DefaultClassName = "Template"; private const string DefaultRunMethodName = "Run"; private const string DefaultWriterParameterName = "__output__"; private static readonly object s_lock = new(); private MethodInfo? _runMethodInfo; private string? _className; private string? _runMethodName; private string? _writerParameterName; private readonly List<TemplateArgument> _arguments = new(); private readonly List<string> _usings = new(); private readonly List<string> _referencePaths = new(); [NotNull] private string? ClassName { get => string.IsNullOrEmpty(_className) ? DefaultClassName : _className; set => _className = value; } [NotNull] private string? RunMethodName { get => string.IsNullOrEmpty(_runMethodName) ? DefaultRunMethodName : _runMethodName; set => _runMethodName = value; } [NotNull] public string? OutputParameterName { get => string.IsNullOrEmpty(_writerParameterName) ? DefaultWriterParameterName : _writerParameterName; set => _writerParameterName = value; } public Type? OutputType { get; set; } public string? BaseClassFullTypeName { get; set; } public string StartCodeBlockDelimiter { get; set; } = "<%"; public string EndCodeBlockDelimiter { get; set; } = "%>"; public IList<ParsedBlock>? Blocks { get; private set; } public bool IsBuilt => _runMethodInfo != null; public string? SourceCode { get; private set; } public IReadOnlyList<TemplateArgument> Arguments => _arguments; public IReadOnlyList<string> Usings => _usings; public IReadOnlyList<string> ReferencePaths => _referencePaths; public bool Debug { get; set; } public void AddReference(Type type!!) { if (type.Assembly.Location == null) throw new ArgumentException("Assembly has no location.", nameof(type)); _referencePaths.Add(type.Assembly.Location); } public void AddUsing(string @namespace) { AddUsing(@namespace, alias: null); } public void AddUsing(string @namespace!!, string? alias) { if (!string.IsNullOrEmpty(alias)) { _usings.Add(alias + " = " + @namespace); } else { _usings.Add(@namespace); } } public void AddUsing(Type type) { AddUsing(type, alias: null); } public void AddUsing(Type type!!, string? alias) { if (!string.IsNullOrEmpty(alias)) { _usings.Add(alias + " = " + GetFriendlyTypeName(type)); } else { if (type.Namespace != null) { _usings.Add(type.Namespace); } } AddReference(type); } private static string GetFriendlyTypeName(Type type!!) { var friendlyName = type.Name; if (type.IsGenericType) { var iBacktick = friendlyName.IndexOf('`', StringComparison.Ordinal); if (iBacktick > 0) { friendlyName = friendlyName.Remove(iBacktick); } friendlyName += "<"; var typeParameters = type.GetGenericArguments(); for (var i = 0; i < typeParameters.Length; ++i) { var typeParamName = GetFriendlyTypeName(typeParameters[i]); friendlyName += i == 0 ? typeParamName : "," + typeParamName; } friendlyName += ">"; friendlyName = type.Namespace + "." + friendlyName; } else { if (type.FullName == null) throw new ArgumentException("type has no FullName", nameof(type)); friendlyName = type.FullName; } return friendlyName.Replace('+', '.'); } public void AddArgument(string name) { AddArgument(name, type: null); } public void AddArgument<T>(string name) { AddArgument(name, typeof(T)); } public void AddArgument(string name!!, Type? type) { _arguments.Add(new TemplateArgument(name, type)); if (type != null) { AddReference(type); } } public void AddArguments(IReadOnlyDictionary<string, object?> arguments!!) { foreach (var argument in arguments) { AddArgument(argument.Key, argument.Value?.GetType()); } } public void AddArguments(params string[] arguments) { foreach (var argument in arguments) { AddArgument(argument); } } public void Load(string text!!) { using var reader = new StringReader(text); Load(reader); } public void Load(TextReader reader!!) { using var r = new TextReaderWithPosition(reader); Load(r); } private void Load(TextReaderWithPosition reader!!) { if (IsBuilt) throw new InvalidOperationException("Template is already built."); var blocks = new List<ParsedBlock>(); var isInBlock = false; var currentBlock = new StringBuilder(); var nextDelimiter = StartCodeBlockDelimiter; var blockDelimiterIndex = 0; var blockIndex = 0; var startLine = reader.Line; var startColumn = reader.Column; int n; while ((n = reader.Read()) >= 0) { var c = (char)n; if (blockDelimiterIndex < nextDelimiter.Length && c == nextDelimiter[blockDelimiterIndex]) { blockDelimiterIndex++; if (blockDelimiterIndex >= nextDelimiter.Length) // end of delimiter { var text = currentBlock.ToString(0, currentBlock.Length - (blockDelimiterIndex - 1)); var block = CreateBlock(isInBlock, text, blockIndex++, startLine, startColumn, reader.Line, reader.Column); blocks.Add(block); currentBlock.Clear(); blockDelimiterIndex = 0; if (isInBlock) { nextDelimiter = StartCodeBlockDelimiter; isInBlock = false; } else { nextDelimiter = EndCodeBlockDelimiter; isInBlock = true; } continue; } } else { blockDelimiterIndex = 0; } if (currentBlock.Length == 0) { startLine = reader.Line; startColumn = reader.Column; } currentBlock.Append(c); } // Create final parsed block if needed if (currentBlock.Length > 0) { var block = CreateBlock(codeBlock: false, currentBlock.ToString(), blockIndex, startLine, startColumn, reader.Line, reader.Column); blocks.Add(block); } blocks.Sort(ParsedBlockComparer.IndexComparer); Blocks = blocks; } private ParsedBlock CreateBlock(bool codeBlock, string text, int index, int startLine, int startColumn, int endLine, int endColumn) { var block = codeBlock ? CreateCodeBlock(text, index) : CreateParsedBlock(text, index); block.StartLine = startLine; block.StartColumn = startColumn; block.EndLine = endLine; block.EndColumn = endColumn; return block; } public void Build(CancellationToken cancellationToken) { if (Blocks == null) throw new InvalidOperationException("Template is not loaded."); if (IsBuilt) return; lock (s_lock) { if (IsBuilt) return; using var sw = new StringWriter(); using (var tw = new IndentedTextWriter(sw)) { foreach (var @using in Usings) { if (string.IsNullOrEmpty(@using)) continue; tw.WriteLine("using " + @using + ";"); } tw.Write("public class " + ClassName); if (!string.IsNullOrEmpty(BaseClassFullTypeName)) { tw.Write(" : " + BaseClassFullTypeName); } tw.WriteLine(); tw.WriteLine("{"); tw.Indent++; tw.Write("public static void " + RunMethodName); tw.Write("("); tw.Write(OutputType?.FullName ?? "dynamic"); tw.Write(" " + OutputParameterName); foreach (var argument in Arguments) { if (argument == null) continue; tw.Write(", "); tw.Write(argument.Type?.FullName ?? "dynamic"); tw.Write(" "); tw.Write(argument.Name); } tw.Write(")"); tw.WriteLine(); tw.WriteLine("{"); tw.Indent++; foreach (var block in Blocks) { tw.WriteLine(block.BuildCode()); } tw.Indent--; tw.WriteLine("}"); tw.Indent--; tw.WriteLine("}"); } var source = sw.ToString(); SourceCode = source; Compile(source, cancellationToken); } } protected virtual ParsedBlock CreateParsedBlock(string text, int index) { return new ParsedBlock(this, text, index); } protected virtual CodeBlock CreateCodeBlock(string text, int index) { return new CodeBlock(this, text, index); } protected virtual SyntaxTree CreateSyntaxTree(string source!!, CancellationToken cancellationToken) { var options = CSharpParseOptions.Default .WithLanguageVersion(LanguageVersion.Latest) .WithPreprocessorSymbols(Debug ? "DEBUG" : "RELEASE"); return CSharpSyntaxTree.ParseText(source, options, cancellationToken: cancellationToken); } protected virtual MetadataReference[] CreateReferences() { var references = new List<string> { typeof(object).Assembly.Location, typeof(Template).Assembly.Location, // Require to use dynamic keyword typeof(System.Runtime.CompilerServices.DynamicAttribute).Assembly.Location, typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo).Assembly.Location, typeof(System.Dynamic.DynamicObject).Assembly.Location, typeof(System.Linq.Expressions.ExpressionType).Assembly.Location, Assembly.Load(new AssemblyName("mscorlib")).Location, Assembly.Load(new AssemblyName("System.Runtime")).Location, Assembly.Load(new AssemblyName("System.Dynamic.Runtime")).Location, Assembly.Load(new AssemblyName("netstandard")).Location, }; if (OutputType != null) { references.Add(OutputType.Assembly.Location); } foreach (var reference in ReferencePaths) { if (string.IsNullOrEmpty(reference)) continue; references.Add(reference); } var result = references.Where(_ => _ != null).Distinct(StringComparer.Ordinal); //var str = string.Join("\r\n", result); return result.Select(path => MetadataReference.CreateFromFile(path)).ToArray(); } protected virtual CSharpCompilation CreateCompilation(SyntaxTree syntaxTree!!) { var assemblyName = "Template_" + DateTime.UtcNow.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture) + Guid.NewGuid().ToString("N"); var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithDeterministic(deterministic: true) .WithOptimizationLevel(Debug ? OptimizationLevel.Debug : OptimizationLevel.Release) .WithPlatform(Platform.AnyCpu); var compilation = CSharpCompilation.Create(assemblyName, new[] { syntaxTree }, CreateReferences(), options); return compilation; } protected virtual EmitOptions CreateEmitOptions() { return new EmitOptions() .WithDebugInformationFormat(DebugInformationFormat.PortablePdb); } protected virtual void Compile(string source, CancellationToken cancellationToken) { var syntaxTree = CreateSyntaxTree(source, cancellationToken); var compilation = CreateCompilation(syntaxTree); using var dllStream = new MemoryStream(); using var pdbStream = new MemoryStream(); var emitResult = compilation.Emit(dllStream, pdbStream, options: CreateEmitOptions(), cancellationToken: cancellationToken); if (!emitResult.Success) { throw new TemplateException("Template file is not valid." + Environment.NewLine + string.Join(Environment.NewLine, emitResult.Diagnostics)); } dllStream.Seek(0, SeekOrigin.Begin); pdbStream.Seek(0, SeekOrigin.Begin); var assembly = LoadAssembly(dllStream, pdbStream); _runMethodInfo = FindMethod(assembly); if (_runMethodInfo == null) { throw new TemplateException("Run method not found in the generated assembly."); } } protected virtual Assembly LoadAssembly(MemoryStream peStream, MemoryStream pdbStream) { return Assembly.Load(peStream.ToArray(), pdbStream.ToArray()); } protected virtual MethodInfo FindMethod(Assembly assembly) { var type = assembly.GetType(ClassName); System.Diagnostics.Debug.Assert(type != null); var methodInfo = type.GetMethod(RunMethodName); System.Diagnostics.Debug.Assert(methodInfo != null); return methodInfo; } protected virtual StringWriter CreateStringWriter() { return new StringWriter(); } protected virtual object CreateOutput(TextWriter writer) { return new Output(this, writer); } public string Run(params object?[] parameters) { using var writer = CreateStringWriter(); Run(writer, parameters); return writer.ToString(); } public virtual void Run(TextWriter writer, params object?[] parameters) { if (!IsBuilt) { Build(CancellationToken.None); } var p = CreateMethodParameters(writer, parameters); InvokeRunMethod(p); } protected virtual object[] CreateMethodParameters(TextWriter writer, object?[]? parameters) { var p = new object[parameters?.Length + 1 ?? 1]; p[0] = CreateOutput(writer); parameters?.CopyTo(p, 1); return p; } public string Run(IReadOnlyDictionary<string, object?> parameters!!) { using var writer = new StringWriter(); Run(writer, parameters); return writer.ToString(); } public virtual void Run(TextWriter writer!!, IReadOnlyDictionary<string, object?> parameters!!) { var p = CreateMethodParameters(writer, parameters); InvokeRunMethod(p); } protected virtual object?[] CreateMethodParameters(TextWriter writer, IReadOnlyDictionary<string, object?> parameters) { if (!IsBuilt) { Build(CancellationToken.None); } var parameterInfos = _runMethodInfo!.GetParameters(); var p = new object?[parameterInfos.Length]; foreach (var pi in parameterInfos) { if (string.Equals(pi.Name, OutputParameterName, StringComparison.Ordinal)) { p[pi.Position] = CreateOutput(writer); } else { if (parameters.TryGetValue(pi.Name!, out var value)) { p[pi.Position] = value; } } } return p; } protected virtual void InvokeRunMethod(object?[] p) { if (!IsBuilt) { Build(CancellationToken.None); } _runMethodInfo!.Invoke(null, p); } }
// <copyright file="XmlPreprocessor.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System; using System.Xml; using BeanIO.Internal.Config; using BeanIO.Internal.Util; namespace BeanIO.Internal.Compiler.Xml { /// <summary> /// Configuration <see cref="Preprocessor"/> for an XML stream format. /// </summary> internal class XmlPreprocessor : Preprocessor { public XmlPreprocessor(StreamConfig stream) : base(stream) { } /// <summary> /// Initializes a group configuration before its children have been processed /// </summary> /// <param name="config">the group configuration to process</param> protected override void InitializeGroup(GroupConfig config) { base.InitializeGroup(config); if (config.XmlName == null) { config.XmlName = config.Name; } var type = config.XmlType; if (type == null) { config.XmlType = XmlNodeType.Element; } else { if (type != XmlNodeType.Element && type != XmlNodeType.None) throw new BeanIOConfigurationException($"Invalid xmlType '{type}'"); } if (config.XmlNamespace == null) { var parent = Parent; if (parent != null) { config.XmlPrefix = parent.XmlPrefix; config.XmlNamespace = parent.XmlNamespace; config.IsXmlNamespaceAware = parent.IsXmlNamespaceAware; } else { config.XmlPrefix = null; config.XmlNamespace = null; config.IsXmlNamespaceAware = false; } } else if (config.XmlNamespace == "*") { config.XmlPrefix = null; config.XmlNamespace = null; config.IsXmlNamespaceAware = false; } else if (config.XmlNamespace == string.Empty) { config.XmlPrefix = null; config.XmlNamespace = null; config.IsXmlNamespaceAware = true; } else { config.IsXmlNamespaceAware = true; } } /// <summary> /// Initializes a segment configuration before its children have been processed /// </summary> /// <param name="config">the segment configuration to process</param> protected override void InitializeSegment(SegmentConfig config) { base.InitializeSegment(config); if (config.XmlName == null) { config.XmlName = config.Name; } var type = config.XmlType; if (type == null) { config.XmlType = XmlNodeType.Element; } else { if (type != XmlNodeType.Element && type != XmlNodeType.None) throw new BeanIOConfigurationException($"Invalid xmlType '{type}'"); } if (config.XmlPrefix != null) { if (config.XmlNamespace == null) throw new BeanIOConfigurationException("Missing namespace for configured XML prefix"); } if (config.XmlNamespace == null) { var parent = Parent; config.XmlPrefix = parent.XmlPrefix; config.XmlNamespace = parent.XmlNamespace; config.IsXmlNamespaceAware = parent.IsXmlNamespaceAware; } else if (config.XmlNamespace == "*") { config.XmlPrefix = null; config.XmlNamespace = null; config.IsXmlNamespaceAware = false; } else if (config.XmlNamespace == string.Empty) { config.XmlPrefix = null; config.XmlNamespace = null; config.IsXmlNamespaceAware = true; } else { config.IsXmlNamespaceAware = true; } } /// <summary> /// Processes a field configuration /// </summary> /// <param name="config">the field configuration to process</param> protected override void HandleField(FieldConfig config) { if (config.XmlName == null) { config.XmlName = config.Name; } var type = config.XmlType; if (type == null) { var xmlType = Settings.Instance.GetProperty(Settings.DEFAULT_XML_TYPE); XmlNodeType newXmlNodeType; if (!Enum.TryParse(xmlType, true, out newXmlNodeType)) newXmlNodeType = XmlNodeType.Element; type = config.XmlType = newXmlNodeType; } else { switch (type) { case XmlNodeType.Element: case XmlNodeType.Attribute: case XmlNodeType.Text: break; default: throw new BeanIOConfigurationException($"Invalid xmlType '{type}'"); } } // repeating fields must be of type 'element' if (config.IsRepeating && type != XmlNodeType.Element) { throw new BeanIOConfigurationException("Repeating fields must have xmlType 'element'"); } if (config.XmlNamespace != null && type != XmlNodeType.Element && type != XmlNodeType.Attribute) { throw new BeanIOConfigurationException($"XML namespace is not applicable for xmlType '{type}'"); } // if the bean/field/record is nillable, it must be of type 'element' if (config.IsNillable && type != XmlNodeType.Element) { throw new BeanIOConfigurationException($"xmlType '{type}' is not nillable"); } // validate a namespace is set if a prefix is set if (config.XmlPrefix != null) { if (config.XmlNamespace == null) throw new BeanIOConfigurationException("Missing namespace for configured XML prefix"); } var isAttribute = type == XmlNodeType.Attribute; if (config.XmlNamespace == null) { if (isAttribute) { config.XmlPrefix = null; config.XmlNamespace = null; config.IsXmlNamespaceAware = false; } else { var parent = Parent; config.XmlPrefix = parent.XmlPrefix; config.XmlNamespace = parent.XmlNamespace; config.IsXmlNamespaceAware = parent.IsXmlNamespaceAware; } } else if (config.XmlNamespace == "*") { config.XmlPrefix = null; config.XmlNamespace = null; config.IsXmlNamespaceAware = false; } else if (config.XmlNamespace == string.Empty) { config.XmlPrefix = null; config.XmlNamespace = null; config.IsXmlNamespaceAware = true; } else { config.IsXmlNamespaceAware = true; } // default minOccurs for an attribute is 0 if (isAttribute) { if (config.MinOccurs == null) { config.MinOccurs = 0; } } base.HandleField(config); } /// <summary> /// This method validates a record identifying field has a literal or regular expression /// configured for identifying a record. /// </summary> /// <param name="field">the record identifying field configuration to validate</param> protected override void ValidateRecordIdentifyingCriteria(FieldConfig field) { if (field.XmlType == XmlNodeType.Text) base.ValidateRecordIdentifyingCriteria(field); } } }
using System; using System.Runtime.InteropServices; using Mono.Unix.Native; using size_t = System.UIntPtr; using off_t = System.Int64; using mode_t = Mono.Unix.Native.FilePermissions; using eio_tstamp = System.Double; using uid_t = System.Int32; using gid_t = System.Int32; namespace Manos.IO.Libev { static class Libeio { delegate void eio_cb (ref eio_req req); [StructLayout (LayoutKind.Sequential)] struct eio_req { public IntPtr next; public IntPtr result; public Int64 offs; // We are forcing 64bit off_t's by using -D_FILE_OFFSET_BITS=64 public UIntPtr size; public IntPtr ptr1; public IntPtr ptr2; public double nv1; public double nv2; public int type; public int int1; public IntPtr int2; public IntPtr int3; public int errorno; public byte flags; public byte pri; public IntPtr data; public IntPtr finish; public IntPtr destroy; public IntPtr feed; public IntPtr grp; public IntPtr grp_prev; public IntPtr grp_next; public IntPtr grp_first; }; // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_nop (int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_busy (eio_tstamp delay, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_sync (int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_fsync (int fd, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_fdatasync (int fd, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_msync (IntPtr addr, UIntPtr length, MsyncFlags flags, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_mtouch (IntPtr addr, size_t length, int flags, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_mlock (IntPtr addr, size_t length, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_mlockall (int flags, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_sync_file_range (int fd, IntPtr offset, UIntPtr nbytes, uint flags, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_close (int fd, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_readahead (int fd, off_t offset, size_t length, int pri, eio_cb cb, IntPtr data); static eio_cb readCB = ReadCallback; static void ReadCallback (ref eio_req req) { var handle = GCHandle.FromIntPtr (req.data); var tuple = (Tuple<byte [], Action<int, byte [], int>>) handle.Target; tuple.Item2 (req.result.ToInt32 (), tuple.Item1, req.errorno); handle.Free (); } public static void read (int fd, byte[] buffer, long offset, long length, Action<int, byte[], int> callback) { eio_read (fd, buffer, (UIntPtr) length, offset, 0, readCB, GCHandle.ToIntPtr (GCHandle.Alloc (Tuple.Create (buffer, callback)))); } [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr eio_read (int fd, byte [] buf, size_t length, off_t offset, int pri, eio_cb cb, IntPtr data); static eio_cb writeCB = WriteCallback; static void WriteCallback (ref eio_req req) { var handle = GCHandle.FromIntPtr (req.data); ((Action<int, int>) handle.Target) (req.result.ToInt32 (), req.errorno); handle.Free (); } public static void write (int fd, byte[] buffer, long offset, long length, Action<int, int> callback) { eio_write (fd, buffer, (UIntPtr) length, offset, 0, writeCB, GCHandle.ToIntPtr (GCHandle.Alloc (callback))); } [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr eio_write (int fd, byte[] buf, size_t length, off_t offset, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_fstat (int fd, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_fstatvfs (int fd, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_futime (int fd, eio_tstamp atime, eio_tstamp mtime, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_ftruncate (int fd, off_t offset, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_fchmod (int fd, mode_t mode, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_fchown (int fd, uid_t uid, gid_t gid, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_dup2 (int fd, int fd2, int pri, eio_cb cb, IntPtr data); static eio_cb sendfileCB = SendfileCallback; static void SendfileCallback (ref eio_req req) { var handle = GCHandle.FromIntPtr (req.data); ((Action<long, int>) handle.Target) (req.result.ToInt64 (), req.errorno); handle.Free (); } public static void sendfile (int out_fd, int in_fd, long offset, long length, Action<long, int> callback) { eio_sendfile (out_fd, in_fd, offset, (UIntPtr) length, 0, sendfileCB, GCHandle.ToIntPtr (GCHandle.Alloc (callback))); } [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr eio_sendfile (int out_fd, int in_fd, off_t in_offset, size_t length, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_open (string path, OpenFlags flags, mode_t mode, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_utime (string path, eio_tstamp atime, eio_tstamp mtime, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_truncate (string path, off_t offset, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_chown (string path, uid_t uid, gid_t gid, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_chmod (string path, mode_t mode, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_mkdir (string path, mode_t mode, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_readdir (string path, int flags, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_rmdir (string path, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_unlink (string path, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_readlink (string path, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_stat (string path, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_lstat (string path, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_statvfs (string path, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_mknod (string path, mode_t mode, dev_t dev, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_link (string path, string new_path, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_symlink (string path, string new_path, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_rename (string path, string new_path, int pri, eio_cb cb, IntPtr data); // // [DllImport ("libeio", CallingConvention = CallingConvention.Cdecl)] // static extern IntPtr eio_custom (eio_cb execute, int pri, eio_cb cb, IntPtr data); } }
// 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.Collections.Generic; using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ObjectCreationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new ObjectCreationExpressionSignatureHelpProvider(); } #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutParameters() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> C() { } void Foo() { C c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", "Summary for C", null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn1() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C($$2, 3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param a", currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for C /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> C(int a, int b) { } void Foo() { C c = [|new C(2, $$3|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param b", currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParen() { var markup = @" class C { void foo() { var c = [|new C($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParenWithParameters() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C($$2, 3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingParenWithParametersOn2() { var markup = @" class C { C(int a, int b) { } void Foo() { C c = [|new C(2, $$3 |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnLambda() { var markup = @" using System; class C { void foo() { var bar = [|new Action<int, int>($$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Action<int, int>(void (int, int) target)", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestCurrentParameterName() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(b: string.Empty, $$a: 2|]); } }"; VerifyCurrentParameterName(markup, "a"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerParens() { var markup = @" class C { void foo() { var c = [|new C($$|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerComma() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2,$$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, string b)", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestNoInvocationOnSpace() { var markup = @" class C { C(int a, string b) { } void foo() { var c = [|new C(2, $$string.Empty|]); } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Constructor_BrowsableAlways() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Constructor_BrowsableNever() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Constructor_BrowsableAdvanced() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Constructor_BrowsableMixed() { var markup = @" class Program { void M() { new Foo($$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Foo(int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Foo(long y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(long y)", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif void foo() { var x = new D($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D { } #endif #if BAR void foo() { var x = new D($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } [WorkItem(1067933)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InvokedWithNoToken() { var markup = @" // new foo($$"; Test(markup); } [WorkItem(1078993)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestSigHelpInIncorrectObjectCreationExpression() { var markup = @" class C { void foo(C c) { foo([|new C{$$|] } }"; Test(markup); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure { public class DefaultPageModelActivatorProviderTest { [Fact] public void CreateActivator_ThrowsIfModelTypeInfoOnActionDescriptorIsNull() { // Arrange var activatorProvider = new DefaultPageModelActivatorProvider(); var actionDescriptor = new CompiledPageActionDescriptor(); // Act & Assert ExceptionAssert.ThrowsArgument( () => activatorProvider.CreateActivator(actionDescriptor), "actionDescriptor", "The 'ModelTypeInfo' property of 'actionDescriptor' must not be null."); } [Fact] public void CreateActivator_CreatesModelInstance() { // Arrange var activatorProvider = new DefaultPageModelActivatorProvider(); var actionDescriptor = new CompiledPageActionDescriptor { ModelTypeInfo = typeof(SimpleModel).GetTypeInfo(), }; var serviceCollection = new ServiceCollection(); var generator = Mock.Of<IHtmlGenerator>(); serviceCollection.AddSingleton(generator); var httpContext = new DefaultHttpContext { RequestServices = serviceCollection.BuildServiceProvider(), }; var pageContext = new PageContext { HttpContext = httpContext }; // Act var activator = activatorProvider.CreateActivator(actionDescriptor); var model = activator(pageContext); // Assert var simpleModel = Assert.IsType<SimpleModel>(model); Assert.NotNull(simpleModel); } [Fact] public void CreateActivator_TypeActivatesModelType() { // Arrange var activatorProvider = new DefaultPageModelActivatorProvider(); var actionDescriptor = new CompiledPageActionDescriptor { ModelTypeInfo = typeof(ModelWithServices).GetTypeInfo(), }; var serviceCollection = new ServiceCollection(); var generator = Mock.Of<IHtmlGenerator>(); serviceCollection.AddSingleton(generator); var httpContext = new DefaultHttpContext { RequestServices = serviceCollection.BuildServiceProvider(), }; var pageContext = new PageContext { HttpContext = httpContext }; // Act var activator = activatorProvider.CreateActivator(actionDescriptor); var model = activator(pageContext); // Assert var modelWithServices = Assert.IsType<ModelWithServices>(model); Assert.Same(generator, modelWithServices.Generator); } [Theory] [InlineData(typeof(SimpleModel))] [InlineData(typeof(object))] public void CreateReleaser_ReturnsNullForModelsThatDoNotImplementDisposable(Type pageType) { // Arrange var context = new PageContext(); var activator = new DefaultPageModelActivatorProvider(); var actionDescriptor = new CompiledPageActionDescriptor { PageTypeInfo = pageType.GetTypeInfo(), }; // Act var releaser = activator.CreateReleaser(actionDescriptor); // Assert Assert.Null(releaser); } [Theory] [InlineData(typeof(SimpleModel))] [InlineData(typeof(object))] public void CreateAsyncReleaser_ReturnsNullForModelsThatDoNotImplementDisposable(Type pageType) { // Arrange var context = new PageContext(); var activator = new DefaultPageModelActivatorProvider(); var actionDescriptor = new CompiledPageActionDescriptor { PageTypeInfo = pageType.GetTypeInfo(), }; // Act var releaser = activator.CreateAsyncReleaser(actionDescriptor); // Assert Assert.Null(releaser); } [Fact] public void CreateReleaser_CreatesDelegateThatDisposesDisposableTypes() { // Arrange var context = new PageContext(); var activator = new DefaultPageModelActivatorProvider(); var actionDescriptor = new CompiledPageActionDescriptor { ModelTypeInfo = typeof(DisposableModel).GetTypeInfo(), }; var model = new DisposableModel(); // Act & Assert var releaser = activator.CreateReleaser(actionDescriptor); releaser(context, model); // Assert Assert.True(model.Disposed); } [Fact] public void CreateAsyncReleaser_CreatesDelegateThatDisposesDisposableTypes() { // Arrange var context = new PageContext(); var viewContext = new ViewContext(); var activator = new DefaultPageModelActivatorProvider(); var model = new DisposableModel(); // Act & Assert var disposer = activator.CreateAsyncReleaser(new CompiledPageActionDescriptor { ModelTypeInfo = model.GetType().GetTypeInfo() }); Assert.NotNull(disposer); disposer(context, model); // Assert Assert.True(model.Disposed); } [Fact] public async Task CreateAsyncReleaser_CreatesDelegateThatDisposesAsyncDisposableTypes() { // Arrange var context = new PageContext(); var viewContext = new ViewContext(); var activator = new DefaultPageModelActivatorProvider(); var model = new AsyncDisposableModel(); // Act & Assert var disposer = activator.CreateAsyncReleaser(new CompiledPageActionDescriptor { ModelTypeInfo = model.GetType().GetTypeInfo() }); Assert.NotNull(disposer); await disposer(context, model); // Assert Assert.True(model.Disposed); } [Fact] public async Task CreateAsyncReleaser_CreatesDelegateThatPrefersAsyncDisposeAsyncOverDispose() { // Arrange var context = new PageContext(); var viewContext = new ViewContext(); var activator = new DefaultPageModelActivatorProvider(); var model = new DisposableAndAsyncDisposableModel(); // Act & Assert var disposer = activator.CreateAsyncReleaser(new CompiledPageActionDescriptor { ModelTypeInfo = model.GetType().GetTypeInfo() }); Assert.NotNull(disposer); await disposer(context, model); // Assert Assert.True(model.AsyncDisposed); Assert.False(model.SyncDisposed); } private class SimpleModel { } private class ModelWithServices { public ModelWithServices(IHtmlGenerator generator) { Generator = generator; } public IHtmlGenerator Generator { get; } } private class DisposableModel : IDisposable { public bool Disposed { get; private set; } public void Dispose() { Disposed = true; } } private class AsyncDisposableModel : IAsyncDisposable { public bool Disposed { get; private set; } public ValueTask DisposeAsync() { Disposed = true; return default; } } private class DisposableAndAsyncDisposableModel : IDisposable, IAsyncDisposable { public bool AsyncDisposed { get; private set; } public bool SyncDisposed { get; private set; } public void Dispose() { SyncDisposed = true; } public ValueTask DisposeAsync() { AsyncDisposed = true; return default; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //============================================================ // // File: StreamHelper.cs // // Summary: Helper methods for streams. // //=========================================================== using System; using System.IO; using System.Runtime.Remoting; using System.Threading; namespace System.Runtime.Remoting.Channels { internal static class StreamHelper { private static AsyncCallback _asyncCopyStreamReadCallback = new AsyncCallback(AsyncCopyStreamReadCallback); private static AsyncCallback _asyncCopyStreamWriteCallback = new AsyncCallback(AsyncCopyStreamWriteCallback); internal static void CopyStream(Stream source, Stream target) { if (source == null) return; // see if this is a ChunkedMemoryStream (we can do a direct write) ChunkedMemoryStream chunkedMemStream = source as ChunkedMemoryStream; if (chunkedMemStream != null) { chunkedMemStream.WriteTo(target); } else { // see if this is a MemoryStream (we can do a direct write) MemoryStream memContentStream = source as MemoryStream; if (memContentStream != null) { memContentStream.WriteTo(target); } else { // otherwise, we need to copy the data through an intermediate buffer byte[] buffer = CoreChannel.BufferPool.GetBuffer(); int bufferSize = buffer.Length; int readCount = source.Read(buffer, 0, bufferSize); while (readCount > 0) { target.Write(buffer, 0, readCount); readCount = source.Read(buffer, 0, bufferSize); } CoreChannel.BufferPool.ReturnBuffer(buffer); } } } // CopyStream internal static void BufferCopy(byte[] source, int srcOffset, byte[] dest, int destOffset, int count) { if (count > 8) { Buffer.BlockCopy(source, srcOffset, dest, destOffset, count); } else { for (int co = 0; co < count; co++) dest[destOffset + co] = source[srcOffset + co]; } } // BufferCopy internal static IAsyncResult BeginAsyncCopyStream( Stream source, Stream target, bool asyncRead, bool asyncWrite, bool closeSource, bool closeTarget, AsyncCallback callback, Object state) { AsyncCopyStreamResult streamState = new AsyncCopyStreamResult(callback, state); byte[] buffer = CoreChannel.BufferPool.GetBuffer(); streamState.Source = source; streamState.Target = target; streamState.Buffer = buffer; streamState.AsyncRead = asyncRead; streamState.AsyncWrite = asyncWrite; streamState.CloseSource = closeSource; streamState.CloseTarget = closeTarget; try { AsyncCopyReadHelper(streamState); } catch (Exception e) { streamState.SetComplete(null, e); } return streamState; } // BeginAsyncCopyStream internal static void EndAsyncCopyStream(IAsyncResult iar) { AsyncCopyStreamResult asyncResult = (AsyncCopyStreamResult)iar; if (!iar.IsCompleted) { iar.AsyncWaitHandle.WaitOne(); } if (asyncResult.Exception != null) { throw asyncResult.Exception; } } // EndAsyncCopyStream private static void AsyncCopyReadHelper(AsyncCopyStreamResult streamState) { // There is no try-catch here because the calling method always has a try-catch. if (streamState.AsyncRead) { byte[] buffer = streamState.Buffer; streamState.Source.BeginRead(buffer, 0, buffer.Length, _asyncCopyStreamReadCallback, streamState); } else { byte[] buffer = streamState.Buffer; int bytesRead = streamState.Source.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { streamState.SetComplete(null, null); } else if (bytesRead < 0) { throw new RemotingException( CoreChannel.GetResourceString("Remoting_Stream_UnknownReadError")); } else { AsyncCopyWriteHelper(streamState, bytesRead); } } } // AsyncCopyReadHelper private static void AsyncCopyWriteHelper(AsyncCopyStreamResult streamState, int bytesRead) { // There is no try-catch here because the calling method always has a try-catch. if (streamState.AsyncWrite) { byte[] buffer = streamState.Buffer; streamState.Target.BeginWrite(buffer, 0, bytesRead, _asyncCopyStreamWriteCallback, streamState); } else { byte[] buffer = streamState.Buffer; streamState.Target.Write(buffer, 0, bytesRead); AsyncCopyReadHelper(streamState); } } // AsyncCopyWriteHelper private static void AsyncCopyStreamReadCallback(IAsyncResult iar) { AsyncCopyStreamResult state = (AsyncCopyStreamResult)iar.AsyncState; try { Stream source = state.Source; int bytesRead = source.EndRead(iar); if (bytesRead == 0) { state.SetComplete(null, null); } else if (bytesRead < 0) { throw new RemotingException( CoreChannel.GetResourceString("Remoting_Stream_UnknownReadError")); } else { AsyncCopyWriteHelper(state, bytesRead); } } catch (Exception e) { state.SetComplete(null, e); } } // AsyncCopyStreamReadCallback private static void AsyncCopyStreamWriteCallback(IAsyncResult iar) { AsyncCopyStreamResult state = (AsyncCopyStreamResult)iar.AsyncState; try { state.Target.EndWrite(iar); AsyncCopyReadHelper(state); } catch (Exception e) { state.SetComplete(null, e); } } // AsyncCopyStreamWriteCallback } // class StreamHelper internal class AsyncCopyStreamResult : BasicAsyncResult { internal Stream Source; internal Stream Target; internal byte[] Buffer; internal bool AsyncRead; internal bool AsyncWrite; internal bool CloseSource; internal bool CloseTarget; internal AsyncCopyStreamResult(AsyncCallback callback, Object state) : base(callback, state) { } internal override void CleanupOnComplete() { if (Buffer != null) CoreChannel.BufferPool.ReturnBuffer(Buffer); if (CloseSource) Source.Close(); if (CloseTarget) Target.Close(); } // CleanupOnComplete } // class AsyncCopyStreamResult } // namespace System.Runtime.Remoting.Channels
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using OpenLiveWriter.CoreServices; namespace OpenLiveWriter.PostEditor { public class BlogPostImageData : ICloneable { public BlogPostImageData() : this(null, null, null, null, new BlogPostImageServiceUploadInfo(), new BlogPostSettingsBag()) { } public BlogPostImageData(ImageFileData imageSource) : this(imageSource, null, null, null, new BlogPostImageServiceUploadInfo(), new BlogPostSettingsBag()) { } private BlogPostImageData(ImageFileData imageSource, ImageFileData imageShadowSource, ImageFileData inlineImageFile, ImageFileData linkedImageFile, BlogPostImageServiceUploadInfo uploadInfo, BlogPostSettingsBag decoratorSettings) { ImageSourceFile = imageSource; ImageSourceShadowFile = imageShadowSource; InlineImageFile = inlineImageFile; LinkedImageFile = linkedImageFile; UploadInfo = uploadInfo; ImageDecoratorSettings = decoratorSettings; } /// <summary> /// The source image file. /// </summary> public ImageFileData GetImageSourceFile() { if (File.Exists(ImageSourceFile.Uri.LocalPath)) return ImageSourceFile; else return ImageSourceShadowFile; } /// <summary> /// The source image file. /// </summary> public ImageFileData ImageSourceFile; /// <summary> /// The shadow copy of the source image file. /// </summary> public ImageFileData ImageSourceShadowFile { get { if (GlobalEditorOptions.SupportsFeature(ContentEditorFeature.ShadowImageForDrafts)) Debug.Assert(_imageSourceShadowFile != null, "shadow file is not available"); return _imageSourceShadowFile; } set { _imageSourceShadowFile = value; } } private ImageFileData _imageSourceShadowFile; internal void InitShadowFile(ISupportingFileService fileService) { if (_imageSourceShadowFile == null) { if (ImageSourceFile != null && File.Exists(ImageSourceFile.Uri.LocalPath)) { CreateShadowFile(ImageSourceFile, fileService); } else if (LinkedImageFile != null && File.Exists(LinkedImageFile.Uri.LocalPath)) { CreateShadowFile(LinkedImageFile, fileService); } else if (InlineImageFile != null && File.Exists(InlineImageFile.Uri.LocalPath)) { CreateShadowFile(InlineImageFile, fileService); } } } /// <summary> /// Creates an embedded shadow copy of a source image file. /// </summary> /// <param name="sourceFile"></param> /// <param name="fileService"></param> private void CreateShadowFile(ImageFileData sourceFile, ISupportingFileService fileService) { Size shadowSize = new Size(1280, 960); using (MemoryStream shadowStream = new MemoryStream()) { ImageFormat format; string fileExt; ImageHelper2.GetImageFormat(sourceFile.SupportingFile.FileName, out fileExt, out format); using (Bitmap sourceImage = new Bitmap(sourceFile.Uri.LocalPath)) { if (sourceImage.Width > shadowSize.Width || sourceImage.Height > shadowSize.Height) { shadowSize = ImageHelper2.SaveScaledThumbnailImage(Math.Min(shadowSize.Width, sourceImage.Width), Math.Min(shadowSize.Height, sourceImage.Height), sourceImage, format, shadowStream); } else { shadowSize = sourceImage.Size; using (FileStream fs = File.OpenRead(sourceFile.Uri.LocalPath)) { StreamHelper.Transfer(fs, shadowStream); } } } shadowStream.Seek(0, SeekOrigin.Begin); ISupportingFile supportingFile = fileService.CreateSupportingFile(sourceFile.SupportingFile.FileName, shadowStream); _imageSourceShadowFile = new ImageFileData(supportingFile, shadowSize.Width, shadowSize.Height, ImageFileRelationship.SourceShadow); } } /// <summary> /// The inline version of the image. /// </summary> public ImageFileData InlineImageFile; /// <summary> /// The linked version of the image. /// </summary> public ImageFileData LinkedImageFile; /// <summary> /// Returns the settings assigned to this image and its derivatives. /// </summary> public BlogPostSettingsBag ImageDecoratorSettings; public BlogPostImageServiceUploadInfo UploadInfo; #region ICloneable Members public object Clone() { return new BlogPostImageData( (ImageFileData)ImageSourceFile.Clone(), ImageSourceShadowFile != null ? (ImageFileData)ImageSourceShadowFile.Clone() : null, (ImageFileData)InlineImageFile.Clone(), LinkedImageFile != null ? (ImageFileData)LinkedImageFile.Clone() : null, (BlogPostImageServiceUploadInfo)UploadInfo.Clone(), (BlogPostSettingsBag)ImageDecoratorSettings.Clone()); } #endregion } public enum ImageFileRelationship { Undefined, Source, Inline, Linked, SourceShadow }; public class ImageFileData : ICloneable { private ISupportingFile _supportingFile; public ImageFileData(ISupportingFile supportingFile) { _supportingFile = supportingFile; } public ImageFileData(ISupportingFile supportingFile, int width, int height, ImageFileRelationship relationship) { _supportingFile = supportingFile; Width = width; Height = height; Relationship = relationship; } public ISupportingFile SupportingFile { get { return _supportingFile; } set { _supportingFile = value; } } public Uri Uri { get { return _supportingFile.FileUri; } } public Uri GetPublishedUri(string publishContext) { ISupportingFileUploadInfo uploadInfo = _supportingFile.GetUploadInfo(publishContext); if (uploadInfo != null) return uploadInfo.UploadUri; else return null; } public int Width { get { return _supportingFile.Settings.GetInt(WIDTH, 0); } set { _supportingFile.Settings.SetInt(WIDTH, value); } } private string WIDTH = "image.width"; public int Height { get { return _supportingFile.Settings.GetInt(HEIGHT, 0); } set { _supportingFile.Settings.SetInt(HEIGHT, value); } } private string HEIGHT = "image.height"; public ImageFileRelationship Relationship { get { string relationship = _supportingFile.Settings.GetString(RELATIONSHIP, ImageFileRelationship.Undefined.ToString()); try { return (ImageFileRelationship)ImageFileRelationship.Parse(typeof(ImageFileRelationship), relationship); } catch (Exception) { return ImageFileRelationship.Undefined; } } set { _supportingFile.Settings.SetString(RELATIONSHIP, value.ToString()); } } private string RELATIONSHIP = "image.relationship"; public object Clone() { return new ImageFileData(_supportingFile, Width, Height, Relationship); } } public class BlogPostImageServiceUploadInfo : ICloneable { internal BlogPostImageServiceUploadInfo() { Settings = new BlogPostSettingsBag(); } internal BlogPostImageServiceUploadInfo(string imageServiceId, BlogPostSettingsBag settings) { ImageServiceId = imageServiceId; Settings = settings; } public string ImageServiceId; public BlogPostSettingsBag Settings { get { return _settings; } set { _settings = value; } } private BlogPostSettingsBag _settings; public object Clone() { BlogPostImageServiceUploadInfo upload = new BlogPostImageServiceUploadInfo(ImageServiceId, (BlogPostSettingsBag)Settings.Clone()); return upload; } } public class BlogPostImageDataList : IEnumerable { ArrayList _list = new ArrayList(); public BlogPostImageDataList() { } public BlogPostImageDataList(BlogPostImageData[] images) { _list.AddRange(images); } public void AddImage(BlogPostImageData imageData) { _list.Add(imageData); } public void RemoveImage(BlogPostImageData imageData) { _list.Add(imageData); } public void Clear() { _list.Clear(); } public int Count { get { return _list.Count; } } public BlogPostImageData this[int i] { get { return (BlogPostImageData)_list[i]; } set { _list[i] = value; } } #region IEnumerable Members public IEnumerator GetEnumerator() { return _list.GetEnumerator(); } #endregion public static BlogPostImageData LookupImageDataByInlineUri(BlogPostImageDataList imageDataList, Uri inlineUri) { foreach (BlogPostImageData imageData in imageDataList) { ImageFileData fileData = imageData.InlineImageFile; //Check for condition that caused bug 483278, but we couldn't repro, investigate how we get into this state. Debug.Assert(fileData != null && fileData.Uri != null, "Illegal state for filedata detected!"); if (fileData != null && fileData.Uri != null && fileData.Uri.Equals(inlineUri)) return imageData; } return null; } public static BlogPostImageData LookupImageDataByLinkedUri(BlogPostImageDataList imageDataList, Uri inlineUri) { foreach (BlogPostImageData imageData in imageDataList) { if (imageData.LinkedImageFile != null && imageData.LinkedImageFile.Uri.Equals(inlineUri)) return imageData; } return null; } } }
// 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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A class that provides a simple, lightweight implementation of thread-local lazy-initialization, where a value is initialized once per accessing // thread; this provides an alternative to using a ThreadStatic static variable and having // to check the variable prior to every access to see if it's been initialized. // // // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading { /// <summary> /// Provides thread-local storage of data. /// </summary> /// <typeparam name="T">Specifies the type of data stored per-thread.</typeparam> /// <remarks> /// <para> /// With the exception of <see cref="Dispose()"/>, all public and protected members of /// <see cref="ThreadLocal{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </para> /// </remarks> [DebuggerTypeProxy(typeof(SystemThreading_ThreadLocalDebugView<>))] [DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")] public class ThreadLocal<T> : IDisposable { // a delegate that returns the created value, if null the created value will be default(T) private Func<T> m_valueFactory; // // ts_slotArray is a table of thread-local values for all ThreadLocal<T> instances // // So, when a thread reads ts_slotArray, it gets back an array of *all* ThreadLocal<T> values for this thread and this T. // The slot relevant to this particular ThreadLocal<T> instance is determined by the m_idComplement instance field stored in // the ThreadLocal<T> instance. // [ThreadStatic] private static LinkedSlotVolatile[] ts_slotArray; [ThreadStatic] private static FinalizationHelper ts_finalizationHelper; // Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish // between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or // possibly due to a memory model issue in user code. private int m_idComplement; // This field is set to true when the constructor completes. That is helpful for recognizing whether a constructor // threw an exception - either due to invalid argument or due to a thread abort. Finally, the field is set to false // when the instance is disposed. private volatile bool m_initialized; // IdManager assigns and reuses slot IDs. Additionally, the object is also used as a global lock. private static IdManager s_idManager = new IdManager(); // A linked list of all values associated with this ThreadLocal<T> instance. // We create a dummy head node. That allows us to remove any (non-dummy) node without having to locate the m_linkedSlot field. private LinkedSlot m_linkedSlot = new LinkedSlot(null); // Whether the Values property is supported private bool m_trackAllValues; /// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance. /// </summary> public ThreadLocal() { Initialize(null, false); } /// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance. /// </summary> /// <param name="trackAllValues">Whether to track all values set on the instance and expose them through the Values property.</param> public ThreadLocal(bool trackAllValues) { Initialize(null, trackAllValues); } /// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the /// specified <paramref name="valueFactory"/> function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when /// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic). /// </exception> public ThreadLocal(Func<T> valueFactory) { if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory)); Initialize(valueFactory, false); } /// <summary> /// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the /// specified <paramref name="valueFactory"/> function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when /// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized. /// </param> /// <param name="trackAllValues">Whether to track all values set on the instance and expose them via the Values property.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic). /// </exception> public ThreadLocal(Func<T> valueFactory, bool trackAllValues) { if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory)); Initialize(valueFactory, trackAllValues); } private void Initialize(Func<T> valueFactory, bool trackAllValues) { m_valueFactory = valueFactory; m_trackAllValues = trackAllValues; // Assign the ID and mark the instance as initialized. To avoid leaking IDs, we assign the ID and set m_initialized // in a finally block, to avoid a thread abort in between the two statements. try { } finally { m_idComplement = ~s_idManager.GetId(); // As the last step, mark the instance as fully initialized. (Otherwise, if m_initialized=false, we know that an exception // occurred in the constructor.) m_initialized = true; } } /// <summary> /// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance. /// </summary> ~ThreadLocal() { // finalizer to return the type combination index to the pool Dispose(false); } #region IDisposable Members /// <summary> /// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe. /// </remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance. /// </summary> /// <param name="disposing"> /// A Boolean value that indicates whether this method is being called due to a call to <see cref="Dispose()"/>. /// </param> /// <remarks> /// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe. /// </remarks> protected virtual void Dispose(bool disposing) { int id; lock (s_idManager) { id = ~m_idComplement; m_idComplement = 0; if (id < 0 || !m_initialized) { Debug.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized"); // Handle double Dispose calls or disposal of an instance whose constructor threw an exception. return; } m_initialized = false; for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next) { LinkedSlotVolatile[] slotArray = linkedSlot.SlotArray; if (slotArray == null) { // The thread that owns this slotArray has already finished. continue; } // Remove the reference from the LinkedSlot to the slot table. linkedSlot.SlotArray = null; // And clear the references from the slot table to the linked slot and the value so that // both can get garbage collected. slotArray[id].Value.Value = default(T); slotArray[id].Value = null; } } m_linkedSlot = null; s_idManager.ReturnId(id); } #endregion /// <summary>Creates and returns a string representation of this instance for the current thread.</summary> /// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see cref="Value"/>.</returns> /// <exception cref="T:System.NullReferenceException"> /// The <see cref="Value"/> for the current thread is a null reference (Nothing in Visual Basic). /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The initialization function referenced <see cref="Value"/> in an improper manner. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="ThreadLocal{T}"/> instance has been disposed. /// </exception> /// <remarks> /// Calling this method forces initialization for the current thread, as is the /// case with accessing <see cref="Value"/> directly. /// </remarks> public override string ToString() { return Value.ToString(); } /// <summary> /// Gets or sets the value of this instance for the current thread. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The initialization function referenced <see cref="Value"/> in an improper manner. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="ThreadLocal{T}"/> instance has been disposed. /// </exception> /// <remarks> /// If this instance was not previously initialized for the current thread, /// accessing <see cref="Value"/> will attempt to initialize it. If an initialization function was /// supplied during the construction, that initialization will happen by invoking the function /// to retrieve the initial value for <see cref="Value"/>. Otherwise, the default value of /// <typeparamref name="T"/> will be used. /// </remarks> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value { get { LinkedSlotVolatile[] slotArray = ts_slotArray; LinkedSlot slot; int id = ~m_idComplement; // // Attempt to get the value using the fast path // if (slotArray != null // Has the slot array been initialized? && id >= 0 // Is the ID non-negative (i.e., instance is not disposed)? && id < slotArray.Length // Is the table large enough? && (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID? && m_initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)? ) { // We verified that the instance has not been disposed *after* we got a reference to the slot. // This guarantees that we have a reference to the right slot. // // Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read // will not be reordered before the read of slotArray[id]. return slot.Value; } return GetValueSlow(); } set { LinkedSlotVolatile[] slotArray = ts_slotArray; LinkedSlot slot; int id = ~m_idComplement; // // Attempt to set the value using the fast path // if (slotArray != null // Has the slot array been initialized? && id >= 0 // Is the ID non-negative (i.e., instance is not disposed)? && id < slotArray.Length // Is the table large enough? && (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID? && m_initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)? ) { // We verified that the instance has not been disposed *after* we got a reference to the slot. // This guarantees that we have a reference to the right slot. // // Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read // will not be reordered before the read of slotArray[id]. slot.Value = value; } else { SetValueSlow(value, slotArray); } } } private T GetValueSlow() { // If the object has been disposed, the id will be -1. int id = ~m_idComplement; if (id < 0) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } Debugger.NotifyOfCrossThreadDependency(); // Determine the initial value T value; if (m_valueFactory == null) { value = default(T); } else { value = m_valueFactory(); if (IsValueCreated) { throw new InvalidOperationException(SR.ThreadLocal_Value_RecursiveCallsToValue); } } // Since the value has been previously uninitialized, we also need to set it (according to the ThreadLocal semantics). Value = value; return value; } private void SetValueSlow(T value, LinkedSlotVolatile[] slotArray) { int id = ~m_idComplement; // If the object has been disposed, id will be -1. if (id < 0) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } // If a slot array has not been created on this thread yet, create it. if (slotArray == null) { slotArray = new LinkedSlotVolatile[GetNewTableSize(id + 1)]; ts_finalizationHelper = new FinalizationHelper(slotArray, m_trackAllValues); ts_slotArray = slotArray; } // If the slot array is not big enough to hold this ID, increase the table size. if (id >= slotArray.Length) { GrowTable(ref slotArray, id + 1); ts_finalizationHelper.SlotArray = slotArray; ts_slotArray = slotArray; } // If we are using the slot in this table for the first time, create a new LinkedSlot and add it into // the linked list for this ThreadLocal instance. if (slotArray[id].Value == null) { CreateLinkedSlot(slotArray, id, value); } else { // Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read // that follows will not be reordered before the read of slotArray[id]. LinkedSlot slot = slotArray[id].Value; // It is important to verify that the ThreadLocal instance has not been disposed. The check must come // after capturing slotArray[id], but before assigning the value into the slot. This ensures that // if this ThreadLocal instance was disposed on another thread and another ThreadLocal instance was // created, we definitely won't assign the value into the wrong instance. if (!m_initialized) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } slot.Value = value; } } /// <summary> /// Creates a LinkedSlot and inserts it into the linked list for this ThreadLocal instance. /// </summary> private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value) { // Create a LinkedSlot var linkedSlot = new LinkedSlot(slotArray); // Insert the LinkedSlot into the linked list maintained by this ThreadLocal<> instance and into the slot array lock (s_idManager) { // Check that the instance has not been disposed. It is important to check this under a lock, since // Dispose also executes under a lock. if (!m_initialized) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } LinkedSlot firstRealNode = m_linkedSlot.Next; // // Insert linkedSlot between nodes m_linkedSlot and firstRealNode. // (m_linkedSlot is the dummy head node that should always be in the front.) // linkedSlot.Next = firstRealNode; linkedSlot.Previous = m_linkedSlot; linkedSlot.Value = value; if (firstRealNode != null) { firstRealNode.Previous = linkedSlot; } m_linkedSlot.Next = linkedSlot; // Assigning the slot under a lock prevents a race condition with Dispose (dispose also acquires the lock). // Otherwise, it would be possible that the ThreadLocal instance is disposed, another one gets created // with the same ID, and the write would go to the wrong instance. slotArray[id].Value = linkedSlot; } } /// <summary> /// Gets a list for all of the values currently stored by all of the threads that have accessed this instance. /// </summary> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="ThreadLocal{T}"/> instance has been disposed. /// </exception> public IList<T> Values { get { if (!m_trackAllValues) { throw new InvalidOperationException(SR.ThreadLocal_ValuesNotAvailable); } var list = GetValuesAsList(); // returns null if disposed if (list == null) throw new ObjectDisposedException(SR.ThreadLocal_Disposed); return list; } } /// <summary>Gets all of the threads' values in a list.</summary> private List<T> GetValuesAsList() { List<T> valueList = new List<T>(); int id = ~m_idComplement; if (id == -1) { return null; } // Walk over the linked list of slots and gather the values associated with this ThreadLocal instance. for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next) { // We can safely read linkedSlot.Value. Even if this ThreadLocal has been disposed in the meantime, the LinkedSlot // objects will never be assigned to another ThreadLocal instance. valueList.Add(linkedSlot.Value); } return valueList; } /// <summary>Gets the number of threads that have data in this instance.</summary> private int ValuesCountForDebugDisplay { get { int count = 0; for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next) { count++; } return count; } } /// <summary> /// Gets whether <see cref="Value"/> is initialized on the current thread. /// </summary> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="ThreadLocal{T}"/> instance has been disposed. /// </exception> public bool IsValueCreated { get { int id = ~m_idComplement; if (id < 0) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } LinkedSlotVolatile[] slotArray = ts_slotArray; return slotArray != null && id < slotArray.Length && slotArray[id].Value != null; } } /// <summary>Gets the value of the ThreadLocal&lt;T&gt; for debugging display purposes. It takes care of getting /// the value for the current thread in the ThreadLocal mode.</summary> internal T ValueForDebugDisplay { get { LinkedSlotVolatile[] slotArray = ts_slotArray; int id = ~m_idComplement; LinkedSlot slot; if (slotArray == null || id >= slotArray.Length || (slot = slotArray[id].Value) == null || !m_initialized) return default(T); return slot.Value; } } /// <summary>Gets the values of all threads that accessed the ThreadLocal&lt;T&gt;.</summary> internal List<T> ValuesForDebugDisplay // same as Values property, but doesn't throw if disposed { get { return GetValuesAsList(); } } /// <summary> /// Resizes a table to a certain length (or larger). /// </summary> private void GrowTable(ref LinkedSlotVolatile[] table, int minLength) { Debug.Assert(table.Length < minLength); // Determine the size of the new table and allocate it. int newLen = GetNewTableSize(minLength); LinkedSlotVolatile[] newTable = new LinkedSlotVolatile[newLen]; // // The lock is necessary to avoid a race with ThreadLocal.Dispose. GrowTable has to point all // LinkedSlot instances referenced in the old table to reference the new table. Without locking, // Dispose could use a stale SlotArray reference and clear out a slot in the old array only, while // the value continues to be referenced from the new (larger) array. // lock (s_idManager) { for (int i = 0; i < table.Length; i++) { LinkedSlot linkedSlot = table[i].Value; if (linkedSlot != null && linkedSlot.SlotArray != null) { linkedSlot.SlotArray = newTable; newTable[i] = table[i]; } } } table = newTable; } /// <summary> /// Chooses the next larger table size /// </summary> private static int GetNewTableSize(int minSize) { if ((uint)minSize > Array.MaxArrayLength) { // Intentionally return a value that will result in an OutOfMemoryException return int.MaxValue; } Debug.Assert(minSize > 0); // // Round up the size to the next power of 2 // // The algorithm takes three steps: // input -> subtract one -> propagate 1-bits to the right -> add one // // Let's take a look at the 3 steps in both interesting cases: where the input // is (Example 1) and isn't (Example 2) a power of 2. // // Example 1: 100000 -> 011111 -> 011111 -> 100000 // Example 2: 011010 -> 011001 -> 011111 -> 100000 // int newSize = minSize; // Step 1: Decrement newSize--; // Step 2: Propagate 1-bits to the right. newSize |= newSize >> 1; newSize |= newSize >> 2; newSize |= newSize >> 4; newSize |= newSize >> 8; newSize |= newSize >> 16; // Step 3: Increment newSize++; // Don't set newSize to more than Array.MaxArrayLength if ((uint)newSize > Array.MaxArrayLength) { newSize = Array.MaxArrayLength; } return newSize; } /// <summary> /// A wrapper struct used as LinkedSlotVolatile[] - an array of LinkedSlot instances, but with volatile semantics /// on array accesses. /// </summary> private struct LinkedSlotVolatile { internal volatile LinkedSlot Value; } /// <summary> /// A node in the doubly-linked list stored in the ThreadLocal instance. /// /// The value is stored in one of two places: /// /// 1. If SlotArray is not null, the value is in SlotArray.Table[id] /// 2. If SlotArray is null, the value is in FinalValue. /// </summary> private sealed class LinkedSlot { internal LinkedSlot(LinkedSlotVolatile[] slotArray) { SlotArray = slotArray; } // The next LinkedSlot for this ThreadLocal<> instance internal volatile LinkedSlot Next; // The previous LinkedSlot for this ThreadLocal<> instance internal volatile LinkedSlot Previous; // The SlotArray that stores this LinkedSlot at SlotArray.Table[id]. internal volatile LinkedSlotVolatile[] SlotArray; // The value for this slot. internal T Value; } /// <summary> /// A manager class that assigns IDs to ThreadLocal instances /// </summary> private class IdManager { // The next ID to try private int m_nextIdToTry = 0; // Stores whether each ID is free or not. Additionally, the object is also used as a lock for the IdManager. private List<bool> m_freeIds = new List<bool>(); internal int GetId() { lock (m_freeIds) { int availableId = m_nextIdToTry; while (availableId < m_freeIds.Count) { if (m_freeIds[availableId]) { break; } availableId++; } if (availableId == m_freeIds.Count) { m_freeIds.Add(false); } else { m_freeIds[availableId] = false; } m_nextIdToTry = availableId + 1; return availableId; } } // Return an ID to the pool internal void ReturnId(int id) { lock (m_freeIds) { m_freeIds[id] = true; if (id < m_nextIdToTry) m_nextIdToTry = id; } } } /// <summary> /// A class that facilitates ThreadLocal cleanup after a thread exits. /// /// After a thread with an associated thread-local table has exited, the FinalizationHelper /// is reponsible for removing back-references to the table. Since an instance of FinalizationHelper /// is only referenced from a single thread-local slot, the FinalizationHelper will be GC'd once /// the thread has exited. /// /// The FinalizationHelper then locates all LinkedSlot instances with back-references to the table /// (all those LinkedSlot instances can be found by following references from the table slots) and /// releases the table so that it can get GC'd. /// </summary> private class FinalizationHelper { internal LinkedSlotVolatile[] SlotArray; private bool m_trackAllValues; internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues) { SlotArray = slotArray; m_trackAllValues = trackAllValues; } ~FinalizationHelper() { LinkedSlotVolatile[] slotArray = SlotArray; Debug.Assert(slotArray != null); for (int i = 0; i < slotArray.Length; i++) { LinkedSlot linkedSlot = slotArray[i].Value; if (linkedSlot == null) { // This slot in the table is empty continue; } if (m_trackAllValues) { // Set the SlotArray field to null to release the slot array. linkedSlot.SlotArray = null; } else { // Remove the LinkedSlot from the linked list. Once the FinalizationHelper is done, all back-references to // the table will be have been removed, and so the table can get GC'd. lock (s_idManager) { if (linkedSlot.Next != null) { linkedSlot.Next.Previous = linkedSlot.Previous; } // Since the list uses a dummy head node, the Previous reference should never be null. Debug.Assert(linkedSlot.Previous != null); linkedSlot.Previous.Next = linkedSlot.Next; } } } } } } /// <summary>A debugger view of the ThreadLocal&lt;T&gt; to surface additional debugging properties and /// to ensure that the ThreadLocal&lt;T&gt; does not become initialized if it was not already.</summary> internal sealed class SystemThreading_ThreadLocalDebugView<T> { //The ThreadLocal object being viewed. private readonly ThreadLocal<T> m_tlocal; /// <summary>Constructs a new debugger view object for the provided ThreadLocal object.</summary> /// <param name="tlocal">A ThreadLocal object to browse in the debugger.</param> public SystemThreading_ThreadLocalDebugView(ThreadLocal<T> tlocal) { m_tlocal = tlocal; } /// <summary>Returns whether the ThreadLocal object is initialized or not.</summary> public bool IsValueCreated { get { return m_tlocal.IsValueCreated; } } /// <summary>Returns the value of the ThreadLocal object.</summary> public T Value { get { return m_tlocal.ValueForDebugDisplay; } } /// <summary>Return all values for all threads that have accessed this instance.</summary> public List<T> Values { get { return m_tlocal.ValuesForDebugDisplay; } } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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 using System; using System.Collections.Generic; using Quartz.Impl.Matchers; using Quartz.Spi; namespace Quartz { /// <summary> /// This is the main interface of a Quartz Scheduler. /// </summary> /// <remarks> /// <para> /// A <see cref="IScheduler"/> maintains a registry of /// <see cref="IJobDetail"/>s and <see cref="ITrigger"/>s. Once /// registered, the <see cref="IScheduler"/> is responsible for executing /// <see cref="IJob"/> s when their associated <see cref="ITrigger"/> s /// fire (when their scheduled time arrives). /// </para> /// <para> /// <see cref="IScheduler"/> instances are produced by a /// <see cref="ISchedulerFactory"/>. A scheduler that has already been /// created/initialized can be found and used through the same factory that /// produced it. After a <see cref="IScheduler"/> has been created, it is in /// "stand-by" mode, and must have its <see cref="IScheduler.Start"/> method /// called before it will fire any <see cref="IJob"/>s. /// </para> /// <para> /// <see cref="IJob"/> s are to be created by the 'client program', by /// defining a class that implements the <see cref="IJob"/> interface. /// <see cref="IJobDetail"/> objects are then created (also by the client) to /// define a individual instances of the <see cref="IJob"/>. /// <see cref="IJobDetail"/> instances can then be registered with the /// <see cref="IScheduler"/> via the %IScheduler.ScheduleJob(JobDetail, /// Trigger)% or %IScheduler.AddJob(JobDetail, bool)% method. /// </para> /// <para> /// <see cref="ITrigger"/> s can then be defined to fire individual /// <see cref="IJob"/> instances based on given schedules. /// <see cref="ISimpleTrigger"/> s are most useful for one-time firings, or /// firing at an exact moment in time, with N repeats with a given delay between /// them. <see cref="ICronTrigger"/> s allow scheduling based on time of day, /// day of week, day of month, and month of year. /// </para> /// <para> /// <see cref="IJob"/> s and <see cref="ITrigger"/> s have a name and /// group associated with them, which should uniquely identify them within a single /// <see cref="IScheduler"/>. The 'group' feature may be useful for creating /// logical groupings or categorizations of <see cref="IJob"/>s and /// <see cref="ITrigger"/>s. If you don't have need for assigning a group to a /// given <see cref="IJob"/>s of <see cref="ITrigger"/>s, then you can use /// the <see cref="SchedulerConstants.DefaultGroup"/> constant defined on /// this interface. /// </para> /// <para> /// Stored <see cref="IJob"/> s can also be 'manually' triggered through the /// use of the %IScheduler.TriggerJob(string, string)% function. /// </para> /// <para> /// Client programs may also be interested in the 'listener' interfaces that are /// available from Quartz. The <see cref="IJobListener"/> interface provides /// notifications of <see cref="IJob"/> executions. The /// <see cref="ITriggerListener"/> interface provides notifications of /// <see cref="ITrigger"/> firings. The <see cref="ISchedulerListener"/> /// interface provides notifications of <see cref="IScheduler"/> events and /// errors. Listeners can be associated with local schedulers through the /// <see cref="IListenerManager" /> interface. /// </para> /// <para> /// The setup/configuration of a <see cref="IScheduler"/> instance is very /// customizable. Please consult the documentation distributed with Quartz. /// </para> /// </remarks> /// <seealso cref="IJob"/> /// <seealso cref="IJobDetail"/> /// <seealso cref="ITrigger"/> /// <seealso cref="IJobListener"/> /// <seealso cref="ITriggerListener"/> /// <seealso cref="ISchedulerListener"/> /// <author>Marko Lahma (.NET)</author> public interface IScheduler { /// <summary> /// returns true if the given JobGroup /// is paused /// </summary> /// <param name="groupName"></param> /// <returns></returns> bool IsJobGroupPaused(string groupName); /// <summary> /// returns true if the given TriggerGroup /// is paused /// </summary> /// <param name="groupName"></param> /// <returns></returns> bool IsTriggerGroupPaused(string groupName); /// <summary> /// Returns the name of the <see cref="IScheduler" />. /// </summary> string SchedulerName { get; } /// <summary> /// Returns the instance Id of the <see cref="IScheduler" />. /// </summary> string SchedulerInstanceId { get; } /// <summary> /// Returns the <see cref="SchedulerContext" /> of the <see cref="IScheduler" />. /// </summary> SchedulerContext Context { get; } /// <summary> /// Reports whether the <see cref="IScheduler" /> is in stand-by mode. /// </summary> /// <seealso cref="Standby()" /> /// <seealso cref="Start()" /> bool InStandbyMode { get; } /// <summary> /// Reports whether the <see cref="IScheduler" /> has been Shutdown. /// </summary> bool IsShutdown { get; } /// <summary> /// Get a <see cref="SchedulerMetaData" /> object describing the settings /// and capabilities of the scheduler instance. /// </summary> /// <remarks> /// Note that the data returned is an 'instantaneous' snap-shot, and that as /// soon as it's returned, the meta data values may be different. /// </remarks> SchedulerMetaData GetMetaData(); /// <summary> /// Return a list of <see cref="IJobExecutionContext" /> objects that /// represent all currently executing Jobs in this Scheduler instance. /// </summary> /// <remarks> /// <para> /// This method is not cluster aware. That is, it will only return Jobs /// currently executing in this Scheduler instance, not across the entire /// cluster. /// </para> /// <para> /// Note that the list returned is an 'instantaneous' snap-shot, and that as /// soon as it's returned, the true list of executing jobs may be different. /// Also please read the doc associated with <see cref="IJobExecutionContext" />- /// especially if you're using remoting. /// </para> /// </remarks> /// <seealso cref="IJobExecutionContext" /> IList<IJobExecutionContext> GetCurrentlyExecutingJobs(); /// <summary> /// Set the <see cref="JobFactory" /> that will be responsible for producing /// instances of <see cref="IJob" /> classes. /// </summary> /// <remarks> /// JobFactories may be of use to those wishing to have their application /// produce <see cref="IJob" /> instances via some special mechanism, such as to /// give the opportunity for dependency injection. /// </remarks> /// <seealso cref="IJobFactory" /> IJobFactory JobFactory { set; } /// <summary> /// Get a reference to the scheduler's <see cref="IListenerManager" />, /// through which listeners may be registered. /// </summary> /// <returns>the scheduler's <see cref="IListenerManager" /></returns> /// <seealso cref="ListenerManager" /> /// <seealso cref="IJobListener" /> /// <seealso cref="ITriggerListener" /> /// <seealso cref="ISchedulerListener" /> IListenerManager ListenerManager { get; } /// <summary> /// Get the names of all known <see cref="IJobDetail" /> groups. /// </summary> IList<string> GetJobGroupNames(); /// <summary> /// Get the names of all known <see cref="ITrigger" /> groups. /// </summary> IList<string> GetTriggerGroupNames(); /// <summary> /// Get the names of all <see cref="ITrigger" /> groups that are paused. /// </summary> Collection.ISet<string> GetPausedTriggerGroups(); /// <summary> /// Starts the <see cref="IScheduler" />'s threads that fire <see cref="ITrigger" />s. /// When a scheduler is first created it is in "stand-by" mode, and will not /// fire triggers. The scheduler can also be put into stand-by mode by /// calling the <see cref="Standby" /> method. /// </summary> /// <remarks> /// The misfire/recovery process will be started, if it is the initial call /// to this method on this scheduler instance. /// </remarks> /// <seealso cref="StartDelayed(TimeSpan)"/> /// <seealso cref="Standby"/> /// <seealso cref="Shutdown(bool)"/> void Start(); /// <summary> /// Calls <see cref="Start" /> after the indicated delay. /// (This call does not block). This can be useful within applications that /// have initializers that create the scheduler immediately, before the /// resources needed by the executing jobs have been fully initialized. /// </summary> /// <seealso cref="Start"/> /// <seealso cref="Standby"/> /// <seealso cref="Shutdown(bool)"/> void StartDelayed(TimeSpan delay); /// <summary> /// Whether the scheduler has been started. /// </summary> /// <remarks> /// Note: This only reflects whether <see cref="Start" /> has ever /// been called on this Scheduler, so it will return <see langword="true" /> even /// if the <see cref="IScheduler" /> is currently in standby mode or has been /// since shutdown. /// </remarks> /// <seealso cref="Start" /> /// <seealso cref="IsShutdown" /> /// <seealso cref="InStandbyMode" /> bool IsStarted { get; } /// <summary> /// Temporarily halts the <see cref="IScheduler" />'s firing of <see cref="ITrigger" />s. /// </summary> /// <remarks> /// <para> /// When <see cref="Start" /> is called (to bring the scheduler out of /// stand-by mode), trigger misfire instructions will NOT be applied /// during the execution of the <see cref="Start" /> method - any misfires /// will be detected immediately afterward (by the <see cref="IJobStore" />'s /// normal process). /// </para> /// <para> /// The scheduler is not destroyed, and can be re-started at any time. /// </para> /// </remarks> /// <seealso cref="Start()"/> /// <seealso cref="PauseAll()"/> void Standby(); /// <summary> /// Halts the <see cref="IScheduler" />'s firing of <see cref="ITrigger" />s, /// and cleans up all resources associated with the Scheduler. Equivalent to Shutdown(false). /// </summary> /// <remarks> /// The scheduler cannot be re-started. /// </remarks> /// <seealso cref="Shutdown(bool)" /> void Shutdown(); /// <summary> /// Halts the <see cref="IScheduler" />'s firing of <see cref="ITrigger" />s, /// and cleans up all resources associated with the Scheduler. /// </summary> /// <remarks> /// The scheduler cannot be re-started. /// </remarks> /// <param name="waitForJobsToComplete"> /// if <see langword="true" /> the scheduler will not allow this method /// to return until all currently executing jobs have completed. /// </param> /// <seealso cref="Shutdown()" /> void Shutdown(bool waitForJobsToComplete); /// <summary> /// Add the given <see cref="IJobDetail" /> to the /// Scheduler, and associate the given <see cref="ITrigger" /> with /// it. /// </summary> /// <remarks> /// If the given Trigger does not reference any <see cref="IJob" />, then it /// will be set to reference the Job passed with it into this method. /// </remarks> DateTimeOffset ScheduleJob(IJobDetail jobDetail, ITrigger trigger); /// <summary> /// Schedule the given <see cref="ITrigger" /> with the /// <see cref="IJob" /> identified by the <see cref="ITrigger" />'s settings. /// </summary> DateTimeOffset ScheduleJob(ITrigger trigger); /// <summary> /// Schedule all of the given jobs with the related set of triggers. /// </summary> /// <remarks> /// <para>If any of the given jobs or triggers already exist (or more /// specifically, if the keys are not unique) and the replace /// parameter is not set to true then an exception will be thrown.</para> /// </remarks> void ScheduleJobs(IDictionary<IJobDetail, Collection.ISet<ITrigger>> triggersAndJobs, bool replace); /// <summary> /// Schedule the given job with the related set of triggers. /// </summary> /// <remarks> /// If any of the given job or triggers already exist (or more /// specifically, if the keys are not unique) and the replace /// parameter is not set to true then an exception will be thrown. /// </remarks> /// <param name="jobDetail"></param> /// <param name="triggersForJob"></param> /// <param name="replace"></param> void ScheduleJob(IJobDetail jobDetail, Collection.ISet<ITrigger> triggersForJob, bool replace); /// <summary> /// Remove the indicated <see cref="ITrigger" /> from the scheduler. /// <para>If the related job does not have any other triggers, and the job is /// not durable, then the job will also be deleted.</para> /// </summary> bool UnscheduleJob(TriggerKey triggerKey); /// <summary> /// Remove all of the indicated <see cref="ITrigger" />s from the scheduler. /// </summary> /// <remarks> /// <para>If the related job does not have any other triggers, and the job is /// not durable, then the job will also be deleted.</para> /// Note that while this bulk operation is likely more efficient than /// invoking <see cref="UnscheduleJob(TriggerKey)" /> several /// times, it may have the adverse affect of holding data locks for a /// single long duration of time (rather than lots of small durations /// of time). /// </remarks> bool UnscheduleJobs(IList<TriggerKey> triggerKeys); /// <summary> /// Remove (delete) the <see cref="ITrigger" /> with the /// given key, and store the new given one - which must be associated /// with the same job (the new trigger must have the job name &amp; group specified) /// - however, the new trigger need not have the same name as the old trigger. /// </summary> /// <param name="triggerKey">The <see cref="ITrigger" /> to be replaced.</param> /// <param name="newTrigger"> /// The new <see cref="ITrigger" /> to be stored. /// </param> /// <returns> /// <see langword="null" /> if a <see cref="ITrigger" /> with the given /// name and group was not found and removed from the store (and the /// new trigger is therefore not stored), otherwise /// the first fire time of the newly scheduled trigger. /// </returns> DateTimeOffset? RescheduleJob(TriggerKey triggerKey, ITrigger newTrigger); /// <summary> /// Add the given <see cref="IJob" /> to the Scheduler - with no associated /// <see cref="ITrigger" />. The <see cref="IJob" /> will be 'dormant' until /// it is scheduled with a <see cref="ITrigger" />, or <see cref="TriggerJob(Quartz.JobKey)" /> /// is called for it. /// </summary> /// <remarks> /// The <see cref="IJob" /> must by definition be 'durable', if it is not, /// SchedulerException will be thrown. /// </remarks> void AddJob(IJobDetail jobDetail, bool replace); /// <summary> /// Add the given <see cref="IJob" /> to the Scheduler - with no associated /// <see cref="ITrigger" />. The <see cref="IJob" /> will be 'dormant' until /// it is scheduled with a <see cref="ITrigger" />, or <see cref="TriggerJob(Quartz.JobKey)" /> /// is called for it. /// </summary> /// <remarks> /// With the <paramref name="storeNonDurableWhileAwaitingScheduling"/> parameter /// set to <code>true</code>, a non-durable job can be stored. Once it is /// scheduled, it will resume normal non-durable behavior (i.e. be deleted /// once there are no remaining associated triggers). /// </remarks> void AddJob(IJobDetail jobDetail, bool replace, bool storeNonDurableWhileAwaitingScheduling); /// <summary> /// Delete the identified <see cref="IJob" /> from the Scheduler - and any /// associated <see cref="ITrigger" />s. /// </summary> /// <returns> true if the Job was found and deleted.</returns> bool DeleteJob(JobKey jobKey); /// <summary> /// Delete the identified jobs from the Scheduler - and any /// associated <see cref="ITrigger" />s. /// </summary> /// <remarks> /// <para>Note that while this bulk operation is likely more efficient than /// invoking <see cref="DeleteJob(JobKey)" /> several /// times, it may have the adverse affect of holding data locks for a /// single long duration of time (rather than lots of small durations /// of time).</para> /// </remarks> /// <returns> /// true if all of the Jobs were found and deleted, false if /// one or more were not deleted. /// </returns> bool DeleteJobs(IList<JobKey> jobKeys); /// <summary> /// Trigger the identified <see cref="IJobDetail" /> /// (Execute it now). /// </summary> void TriggerJob(JobKey jobKey); /// <summary> /// Trigger the identified <see cref="IJobDetail" /> (Execute it now). /// </summary> /// <param name="data"> /// the (possibly <see langword="null" />) JobDataMap to be /// associated with the trigger that fires the job immediately. /// </param> /// <param name="jobKey"> /// The <see cref="JobKey"/> of the <see cref="IJob" /> to be executed. /// </param> void TriggerJob(JobKey jobKey, JobDataMap data); /// <summary> /// Pause the <see cref="IJobDetail" /> with the given /// key - by pausing all of its current <see cref="ITrigger" />s. /// </summary> void PauseJob(JobKey jobKey); /// <summary> /// Pause all of the <see cref="IJobDetail" />s in the /// matching groups - by pausing all of their <see cref="ITrigger" />s. /// </summary> /// <remarks> /// <para> /// The Scheduler will "remember" that the groups are paused, and impose the /// pause on any new jobs that are added to any of those groups until it is resumed. /// </para> /// <para>NOTE: There is a limitation that only exactly matched groups /// can be remembered as paused. For example, if there are pre-existing /// job in groups "aaa" and "bbb" and a matcher is given to pause /// groups that start with "a" then the group "aaa" will be remembered /// as paused and any subsequently added jobs in group "aaa" will be paused, /// however if a job is added to group "axx" it will not be paused, /// as "axx" wasn't known at the time the "group starts with a" matcher /// was applied. HOWEVER, if there are pre-existing groups "aaa" and /// "bbb" and a matcher is given to pause the group "axx" (with a /// group equals matcher) then no jobs will be paused, but it will be /// remembered that group "axx" is paused and later when a job is added /// in that group, it will become paused.</para> /// </remarks> /// <seealso cref="ResumeJobs" /> void PauseJobs(GroupMatcher<JobKey> matcher); /// <summary> /// Pause the <see cref="ITrigger" /> with the given key. /// </summary> void PauseTrigger(TriggerKey triggerKey); /// <summary> /// Pause all of the <see cref="ITrigger" />s in the groups matching. /// </summary> /// <remarks> /// <para> /// The Scheduler will "remember" all the groups paused, and impose the /// pause on any new triggers that are added to any of those groups until it is resumed. /// </para> /// <para>NOTE: There is a limitation that only exactly matched groups /// can be remembered as paused. For example, if there are pre-existing /// triggers in groups "aaa" and "bbb" and a matcher is given to pause /// groups that start with "a" then the group "aaa" will be remembered as /// paused and any subsequently added triggers in that group be paused, /// however if a trigger is added to group "axx" it will not be paused, /// as "axx" wasn't known at the time the "group starts with a" matcher /// was applied. HOWEVER, if there are pre-existing groups "aaa" and /// "bbb" and a matcher is given to pause the group "axx" (with a /// group equals matcher) then no triggers will be paused, but it will be /// remembered that group "axx" is paused and later when a trigger is added /// in that group, it will become paused.</para> /// </remarks> /// <seealso cref="ResumeTriggers" /> void PauseTriggers(GroupMatcher<TriggerKey> matcher); /// <summary> /// Resume (un-pause) the <see cref="IJobDetail" /> with /// the given key. /// </summary> /// <remarks> /// If any of the <see cref="IJob" />'s<see cref="ITrigger" /> s missed one /// or more fire-times, then the <see cref="ITrigger" />'s misfire /// instruction will be applied. /// </remarks> void ResumeJob(JobKey jobKey); /// <summary> /// Resume (un-pause) all of the <see cref="IJobDetail" />s /// in matching groups. /// </summary> /// <remarks> /// If any of the <see cref="IJob" /> s had <see cref="ITrigger" /> s that /// missed one or more fire-times, then the <see cref="ITrigger" />'s /// misfire instruction will be applied. /// </remarks> /// <seealso cref="PauseJobs" /> void ResumeJobs(GroupMatcher<JobKey> matcher); /// <summary> /// Resume (un-pause) the <see cref="ITrigger" /> with the given /// key. /// </summary> /// <remarks> /// If the <see cref="ITrigger" /> missed one or more fire-times, then the /// <see cref="ITrigger" />'s misfire instruction will be applied. /// </remarks> void ResumeTrigger(TriggerKey triggerKey); /// <summary> /// Resume (un-pause) all of the <see cref="ITrigger" />s in matching groups. /// </summary> /// <remarks> /// If any <see cref="ITrigger" /> missed one or more fire-times, then the /// <see cref="ITrigger" />'s misfire instruction will be applied. /// </remarks> /// <seealso cref="PauseTriggers" /> void ResumeTriggers(GroupMatcher<TriggerKey> matcher); /// <summary> /// Pause all triggers - similar to calling <see cref="PauseTriggers" /> /// on every group, however, after using this method <see cref="ResumeAll()" /> /// must be called to clear the scheduler's state of 'remembering' that all /// new triggers will be paused as they are added. /// </summary> /// <remarks> /// When <see cref="ResumeAll()" /> is called (to un-pause), trigger misfire /// instructions WILL be applied. /// </remarks> /// <seealso cref="ResumeAll()" /> /// <seealso cref="PauseTriggers" /> /// <seealso cref="Standby()" /> void PauseAll(); /// <summary> /// Resume (un-pause) all triggers - similar to calling /// <see cref="ResumeTriggers" /> on every group. /// </summary> /// <remarks> /// If any <see cref="ITrigger" /> missed one or more fire-times, then the /// <see cref="ITrigger" />'s misfire instruction will be applied. /// </remarks> /// <seealso cref="PauseAll()" /> void ResumeAll(); /// <summary> /// Get the keys of all the <see cref="IJobDetail" />s in the matching groups. /// </summary> Collection.ISet<JobKey> GetJobKeys(GroupMatcher<JobKey> matcher); /// <summary> /// Get all <see cref="ITrigger" /> s that are associated with the /// identified <see cref="IJobDetail" />. /// </summary> /// <remarks> /// The returned Trigger objects will be snap-shots of the actual stored /// triggers. If you wish to modify a trigger, you must re-store the /// trigger afterward (e.g. see <see cref="RescheduleJob(TriggerKey, ITrigger)" />). /// </remarks> IList<ITrigger> GetTriggersOfJob(JobKey jobKey); /// <summary> /// Get the names of all the <see cref="ITrigger" />s in the given /// groups. /// </summary> Collection.ISet<TriggerKey> GetTriggerKeys(GroupMatcher<TriggerKey> matcher); /// <summary> /// Get the <see cref="IJobDetail" /> for the <see cref="IJob" /> /// instance with the given key . /// </summary> /// <remarks> /// The returned JobDetail object will be a snap-shot of the actual stored /// JobDetail. If you wish to modify the JobDetail, you must re-store the /// JobDetail afterward (e.g. see <see cref="AddJob(IJobDetail, bool)" />). /// </remarks> IJobDetail GetJobDetail(JobKey jobKey); /// <summary> /// Get the <see cref="ITrigger" /> instance with the given key. /// </summary> /// <remarks> /// The returned Trigger object will be a snap-shot of the actual stored /// trigger. If you wish to modify the trigger, you must re-store the /// trigger afterward (e.g. see <see cref="RescheduleJob(TriggerKey, ITrigger)" />). /// </remarks> ITrigger GetTrigger(TriggerKey triggerKey); /// <summary> /// Get the current state of the identified <see cref="ITrigger" />. /// </summary> /// <seealso cref="TriggerState.Normal" /> /// <seealso cref="TriggerState.Paused" /> /// <seealso cref="TriggerState.Complete" /> /// <seealso cref="TriggerState.Blocked" /> /// <seealso cref="TriggerState.Error" /> /// <seealso cref="TriggerState.None" /> TriggerState GetTriggerState(TriggerKey triggerKey); /// <summary> /// Add (register) the given <see cref="ICalendar" /> to the Scheduler. /// </summary> /// <param name="calName">Name of the calendar.</param> /// <param name="calendar">The calendar.</param> /// <param name="replace">if set to <c>true</c> [replace].</param> /// <param name="updateTriggers">whether or not to update existing triggers that /// referenced the already existing calendar so that they are 'correct' /// based on the new trigger.</param> void AddCalendar(string calName, ICalendar calendar, bool replace, bool updateTriggers); /// <summary> /// Delete the identified <see cref="ICalendar" /> from the Scheduler. /// </summary> /// <remarks> /// If removal of the <code>Calendar</code> would result in /// <see cref="ITrigger" />s pointing to non-existent calendars, then a /// <see cref="SchedulerException" /> will be thrown. /// </remarks> /// <param name="calName">Name of the calendar.</param> /// <returns>true if the Calendar was found and deleted.</returns> bool DeleteCalendar(string calName); /// <summary> /// Get the <see cref="ICalendar" /> instance with the given name. /// </summary> ICalendar GetCalendar(string calName); /// <summary> /// Get the names of all registered <see cref="ICalendar" />. /// </summary> IList<string> GetCalendarNames(); /// <summary> /// Request the interruption, within this Scheduler instance, of all /// currently executing instances of the identified <see cref="IJob" />, which /// must be an implementor of the <see cref="IInterruptableJob" /> interface. /// </summary> /// <remarks> /// <para> /// If more than one instance of the identified job is currently executing, /// the <see cref="IInterruptableJob.Interrupt" /> method will be called on /// each instance. However, there is a limitation that in the case that /// <see cref="Interrupt(JobKey)" /> on one instances throws an exception, all /// remaining instances (that have not yet been interrupted) will not have /// their <see cref="Interrupt(JobKey)" /> method called. /// </para> /// /// <para> /// If you wish to interrupt a specific instance of a job (when more than /// one is executing) you can do so by calling /// <see cref="GetCurrentlyExecutingJobs" /> to obtain a handle /// to the job instance, and then invoke <see cref="Interrupt(JobKey)" /> on it /// yourself. /// </para> /// <para> /// This method is not cluster aware. That is, it will only interrupt /// instances of the identified InterruptableJob currently executing in this /// Scheduler instance, not across the entire cluster. /// </para> /// </remarks> /// <returns> /// true is at least one instance of the identified job was found and interrupted. /// </returns> /// <seealso cref="IInterruptableJob" /> /// <seealso cref="GetCurrentlyExecutingJobs" /> bool Interrupt(JobKey jobKey); /// <summary> /// Request the interruption, within this Scheduler instance, of the /// identified executing job instance, which /// must be an implementor of the <see cref="IInterruptableJob" /> interface. /// </summary> /// <remarks> /// This method is not cluster aware. That is, it will only interrupt /// instances of the identified InterruptableJob currently executing in this /// Scheduler instance, not across the entire cluster. /// </remarks> /// <seealso cref="IInterruptableJob.Interrupt()" /> /// <seealso cref="GetCurrentlyExecutingJobs()" /> /// <seealso cref="IJobExecutionContext.FireInstanceId" /> /// <seealso cref="Interrupt(JobKey)" /> /// <param name="fireInstanceId"> /// the unique identifier of the job instance to be interrupted (see <see cref="IJobExecutionContext.FireInstanceId" />) /// </param> /// <returns>true if the identified job instance was found and interrupted.</returns> bool Interrupt(string fireInstanceId); /// <summary> /// Determine whether a <see cref="IJob" /> with the given identifier already /// exists within the scheduler. /// </summary> /// <param name="jobKey">the identifier to check for</param> /// <returns>true if a Job exists with the given identifier</returns> bool CheckExists(JobKey jobKey); /// <summary> /// Determine whether a <see cref="ITrigger" /> with the given identifier already /// exists within the scheduler. /// </summary> /// <param name="triggerKey">the identifier to check for</param> /// <returns>true if a Trigger exists with the given identifier</returns> bool CheckExists(TriggerKey triggerKey); /// <summary> /// Clears (deletes!) all scheduling data - all <see cref="IJob"/>s, <see cref="ITrigger" />s /// <see cref="ICalendar"/>s. /// </summary> void Clear(); } }
using System; using System.Linq; using System.Threading.Tasks; using Baseline; using Marten.Services; using Marten.Testing.Documents; using Marten.Testing.Harness; using Shouldly; using Xunit; namespace Marten.Testing.Linq { public class invoking_query_with_select_Tests: IntegrationContext { // SAMPLE: one_field_projection [Fact] public void use_select_in_query_for_one_field() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => x.FirstName) .ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom"); } // ENDSAMPLE [Fact] public void use_select_in_query_for_one_field_and_first() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => x.FirstName) .First().ShouldBe("Bill"); } [Fact] public async Task use_select_in_query_for_one_field_async() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); var names = await theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => x.FirstName).ToListAsync().ConfigureAwait(false); names.ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom"); } [Fact] public void use_select_to_another_type() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => new UserName { Name = x.FirstName }) .ToArray() .Select(x => x.Name) .ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom"); } [Fact] public void use_select_to_another_type_as_json() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); // Postgres sticks some extra spaces into the JSON string // SAMPLE: AsJson-plus-Select-1 theSession .Query<User>() .OrderBy(x => x.FirstName) // Transform the User class to a different type .Select(x => new UserName { Name = x.FirstName }) .AsJson() .First() .ShouldBe("{\"Name\": \"Bill\"}"); // ENDSAMPLE } // SAMPLE: get_first_projection [Fact] public void use_select_to_another_type_with_first() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => new UserName { Name = x.FirstName }) .FirstOrDefault() ?.Name.ShouldBe("Bill"); } // ENDSAMPLE [Fact] public void use_select_to_anonymous_type_with_first_as_json() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); // SAMPLE:AsJson-plus-Select-2 theSession .Query<User>() .OrderBy(x => x.FirstName) // Transform to an anonymous type .Select(x => new { Name = x.FirstName }) // Select only the raw JSON .AsJson() .FirstOrDefault() .ShouldBe("{\"Name\": \"Bill\"}"); // ENDSAMPLE } [Fact] public void use_select_to_anonymous_type_with_to_json_array() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => new { Name = x.FirstName }) .ToJsonArray() .ShouldBe("[{\"Name\": \"Bill\"},{\"Name\": \"Hank\"},{\"Name\": \"Sam\"},{\"Name\": \"Tom\"}]"); } [Fact] public async Task use_select_to_another_type_async() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); var users = await theSession .Query<User>() .OrderBy(x => x.FirstName) .Select(x => new UserName { Name = x.FirstName }) .ToListAsync().ConfigureAwait(false); users.Select(x => x.Name) .ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom"); } [Fact] public void use_select_to_another_type_as_to_json_array() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); var users = theSession .Query<User>() .OrderBy(x => x.FirstName) .Select(x => new UserName { Name = x.FirstName }) .ToJsonArray(); users.ShouldBe("[{\"Name\": \"Bill\"},{\"Name\": \"Hank\"},{\"Name\": \"Sam\"},{\"Name\": \"Tom\"}]"); } // SAMPLE: anonymous_type_projection [Fact] public void use_select_to_transform_to_an_anonymous_type() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); theSession.Query<User>().OrderBy(x => x.FirstName).Select(x => new { Name = x.FirstName }) .ToArray() .Select(x => x.Name) .ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom"); } // ENDSAMPLE [Fact] public void use_select_with_multiple_fields_in_anonymous() { theSession.Store(new User { FirstName = "Hank", LastName = "Aaron" }); theSession.Store(new User { FirstName = "Bill", LastName = "Laimbeer" }); theSession.Store(new User { FirstName = "Sam", LastName = "Mitchell" }); theSession.Store(new User { FirstName = "Tom", LastName = "Chambers" }); theSession.SaveChanges(); var users = theSession.Query<User>().Select(x => new { First = x.FirstName, Last = x.LastName }).ToList(); users.Count.ShouldBe(4); users.Each(x => { SpecificationExtensions.ShouldNotBeNull(x.First); SpecificationExtensions.ShouldNotBeNull(x.Last); }); } // SAMPLE: other_type_projection [Fact] public void use_select_with_multiple_fields_to_other_type() { theSession.Store(new User { FirstName = "Hank", LastName = "Aaron" }); theSession.Store(new User { FirstName = "Bill", LastName = "Laimbeer" }); theSession.Store(new User { FirstName = "Sam", LastName = "Mitchell" }); theSession.Store(new User { FirstName = "Tom", LastName = "Chambers" }); theSession.SaveChanges(); var users = theSession.Query<User>().Select(x => new User2 { First = x.FirstName, Last = x.LastName }).ToList(); users.Count.ShouldBe(4); users.Each(x => { SpecificationExtensions.ShouldNotBeNull(x.First); SpecificationExtensions.ShouldNotBeNull(x.Last); }); } // ENDSAMPLE public class User2 { public string First; public string Last; } [Fact] public void use_select_with_multiple_fields_to_other_type_using_constructor() { theSession.Store(new User { FirstName = "Hank", LastName = "Aaron" }); theSession.Store(new User { FirstName = "Bill", LastName = "Laimbeer" }); theSession.Store(new User { FirstName = "Sam", LastName = "Mitchell" }); theSession.Store(new User { FirstName = "Tom", LastName = "Chambers" }); theSession.SaveChanges(); var users = theSession.Query<User>() .Select(x => new UserDto(x.FirstName, x.LastName)) .ToList(); users.Count.ShouldBe(4); users.Each(x => { SpecificationExtensions.ShouldNotBeNull(x.FirstName); SpecificationExtensions.ShouldNotBeNull(x.LastName); }); } [Fact] public void use_select_with_multiple_fields_to_other_type_using_constructor_and_properties() { theSession.Store(new User { FirstName = "Hank", LastName = "Aaron", Age = 20 }); theSession.Store(new User { FirstName = "Bill", LastName = "Laimbeer", Age = 40 }); theSession.Store(new User { FirstName = "Sam", LastName = "Mitchell", Age = 60 }); theSession.Store(new User { FirstName = "Tom", LastName = "Chambers", Age = 80 }); theSession.SaveChanges(); var users = theSession.Query<User>() .Select(x => new UserDto(x.FirstName, x.LastName) { YearsOld = x.Age }) .ToList(); users.Count.ShouldBe(4); users.Each(x => { SpecificationExtensions.ShouldNotBeNull(x.FirstName); SpecificationExtensions.ShouldNotBeNull(x.LastName); SpecificationExtensions.ShouldBeGreaterThan(x.YearsOld, 0); }); } public class UserDto { public UserDto(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } public string FirstName { get; } public string LastName { get; } public int YearsOld { get; set; } } [Fact] public async Task use_select_to_transform_to_an_anonymous_type_async() { theSession.Store(new User { FirstName = "Hank" }); theSession.Store(new User { FirstName = "Bill" }); theSession.Store(new User { FirstName = "Sam" }); theSession.Store(new User { FirstName = "Tom" }); theSession.SaveChanges(); var users = await theSession .Query<User>() .OrderBy(x => x.FirstName) .Select(x => new { Name = x.FirstName }) .ToListAsync().ConfigureAwait(false); users .Select(x => x.Name) .ShouldHaveTheSameElementsAs("Bill", "Hank", "Sam", "Tom"); } // SAMPLE: deep_properties_projection [Fact] public void transform_with_deep_properties() { var targets = Target.GenerateRandomData(100).ToArray(); theStore.BulkInsert(targets); var actual = theSession.Query<Target>().Where(x => x.Number == targets[0].Number).Select(x => x.Inner.Number).ToList().Distinct(); var expected = targets.Where(x => x.Number == targets[0].Number).Select(x => x.Inner.Number).Distinct(); actual.ShouldHaveTheSameElementsAs(expected); } // ENDSAMPLE [Fact] public void transform_with_deep_properties_to_anonymous_type() { var target = Target.Random(true); theSession.Store(target); theSession.SaveChanges(); var actual = theSession.Query<Target>() .Where(x => x.Id == target.Id) .Select(x => new { x.Id, x.Number, InnerNumber = x.Inner.Number }) .First(); actual.Id.ShouldBe(target.Id); actual.Number.ShouldBe(target.Number); actual.InnerNumber.ShouldBe(target.Inner.Number); } [Fact] public void transform_with_deep_properties_to_type_using_constructor() { var target = Target.Random(true); theSession.Store(target); theSession.SaveChanges(); var actual = theSession.Query<Target>() .Where(x => x.Id == target.Id) .Select(x => new FlatTarget(x.Id, x.Number, x.Inner.Number)) .First(); actual.Id.ShouldBe(target.Id); actual.Number.ShouldBe(target.Number); actual.InnerNumber.ShouldBe(target.Inner.Number); } public class FlatTarget { public FlatTarget(Guid id, int number, int innerNumber) { Id = id; Number = number; InnerNumber = innerNumber; } public Guid Id { get; } public int Number { get; } public int InnerNumber { get; } } public invoking_query_with_select_Tests(DefaultStoreFixture fixture) : base(fixture) { } } public class UserName { public string Name { 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.IO; namespace System.Security.Cryptography { public abstract class HashAlgorithm : IDisposable, ICryptoTransform { private bool _disposed; protected int HashSizeValue; protected internal byte[] HashValue; protected int State = 0; protected HashAlgorithm() { } public static HashAlgorithm Create() { return Create("System.Security.Cryptography.HashAlgorithm"); } public static HashAlgorithm Create(string hashName) { throw new PlatformNotSupportedException(); } public virtual int HashSize => HashSizeValue; public virtual byte[] Hash { get { if (_disposed) throw new ObjectDisposedException(null); if (State != 0) throw new CryptographicUnexpectedOperationException(SR.Cryptography_HashNotYetFinalized); return (byte[])HashValue.Clone(); } } public byte[] ComputeHash(byte[] buffer) { if (_disposed) throw new ObjectDisposedException(null); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); HashCore(buffer, 0, buffer.Length); return CaptureHashCodeAndReinitialize(); } public byte[] ComputeHash(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0 || (count > buffer.Length)) throw new ArgumentException(SR.Argument_InvalidValue); if ((buffer.Length - count) < offset) throw new ArgumentException(SR.Argument_InvalidOffLen); if (_disposed) throw new ObjectDisposedException(null); HashCore(buffer, offset, count); return CaptureHashCodeAndReinitialize(); } public byte[] ComputeHash(Stream inputStream) { if (_disposed) throw new ObjectDisposedException(null); // Default the buffer size to 4K. byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) { HashCore(buffer, 0, bytesRead); } return CaptureHashCodeAndReinitialize(); } private byte[] CaptureHashCodeAndReinitialize() { HashValue = HashFinal(); // Clone the hash value prior to invoking Initialize in case the user-defined Initialize // manipulates the array. byte[] tmp = (byte[])HashValue.Clone(); Initialize(); return tmp; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Clear() { (this as IDisposable).Dispose(); } protected virtual void Dispose(bool disposing) { if (disposing) { // Although we don't have any resources to dispose at this level, // we need to continue to throw ObjectDisposedExceptions from CalculateHash // for compatibility with the desktop framework. _disposed = true; } return; } // ICryptoTransform methods // We assume any HashAlgorithm can take input a byte at a time public virtual int InputBlockSize { get { return (1); } } public virtual int OutputBlockSize { get { return (1); } } public virtual bool CanTransformMultipleBlocks { get { return true; } } public virtual bool CanReuseTransform { get { return true; } } public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { ValidateTransformBlock(inputBuffer, inputOffset, inputCount); // Change the State value State = 1; HashCore(inputBuffer, inputOffset, inputCount); if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset))) { // We let BlockCopy do the destination array validation Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount); } return inputCount; } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { ValidateTransformBlock(inputBuffer, inputOffset, inputCount); HashCore(inputBuffer, inputOffset, inputCount); HashValue = CaptureHashCodeAndReinitialize(); byte[] outputBytes; if (inputCount != 0) { outputBytes = new byte[inputCount]; Buffer.BlockCopy(inputBuffer, inputOffset, outputBytes, 0, inputCount); } else { outputBytes = Array.Empty<byte>(); } // Reset the State value State = 0; return outputBytes; } private void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (inputBuffer == null) throw new ArgumentNullException(nameof(inputBuffer)); if (inputOffset < 0) throw new ArgumentOutOfRangeException(nameof(inputOffset), SR.ArgumentOutOfRange_NeedNonNegNum); if (inputCount < 0 || inputCount > inputBuffer.Length) throw new ArgumentException(SR.Argument_InvalidValue); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(SR.Argument_InvalidOffLen); if (_disposed) throw new ObjectDisposedException(null); } protected abstract void HashCore(byte[] array, int ibStart, int cbSize); protected abstract byte[] HashFinal(); public abstract void Initialize(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Runtime; using System.Security.Authentication.ExtendedProtection; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security.Tokens; using System.Globalization; namespace System.ServiceModel.Security { /* * See * http://xws/gxa/main/specs/security/security_profiles/SecurityProfiles.doc * for details on security protocols * Concrete implementations are required to me thread safe after * Open() is called; * instances of concrete protocol factories are scoped to a * channel/listener factory; * Each channel/listener factory must have a * SecurityProtocolFactory set on it before open/first use; the * factory instance cannot be changed once the factory is opened * or listening; * security protocol instances are scoped to a channel and will be * created by the Create calls on protocol factories; * security protocol instances are required to be thread-safe. * for typical subclasses, factory wide state and immutable * settings are expected to be on the ProtocolFactory itself while * channel-wide state is maintained internally in each security * protocol instance; * the security protocol instance set on a channel cannot be * changed; however, the protocol instance may change internal * state; this covers RM's SCT renego case; by keeping state * change internal to protocol instances, we get better * coordination with concurrent message security on channels; * the primary pivot in creating a security protocol instance is * initiator (client) vs. responder (server), NOT sender vs * receiver * Create calls for input and reply channels will contain the * listener-wide state (if any) created by the corresponding call * on the factory; */ // Whether we need to add support for targetting different SOAP roles is tracked by 19144 internal abstract class SecurityProtocolFactory : ISecurityCommunicationObject { internal const bool defaultAddTimestamp = true; internal const bool defaultDeriveKeys = true; internal const bool defaultDetectReplays = true; internal const string defaultMaxClockSkewString = "00:05:00"; internal const string defaultReplayWindowString = "00:05:00"; internal static readonly TimeSpan defaultMaxClockSkew = TimeSpan.Parse(defaultMaxClockSkewString, CultureInfo.InvariantCulture); internal static readonly TimeSpan defaultReplayWindow = TimeSpan.Parse(defaultReplayWindowString, CultureInfo.InvariantCulture); internal const int defaultMaxCachedNonces = 900000; internal const string defaultTimestampValidityDurationString = "00:05:00"; internal static readonly TimeSpan defaultTimestampValidityDuration = TimeSpan.Parse(defaultTimestampValidityDurationString, CultureInfo.InvariantCulture); internal const SecurityHeaderLayout defaultSecurityHeaderLayout = SecurityHeaderLayout.Strict; private static ReadOnlyCollection<SupportingTokenAuthenticatorSpecification> s_emptyTokenAuthenticators; private bool _actAsInitiator; private bool _isDuplexReply; private bool _addTimestamp = defaultAddTimestamp; private bool _detectReplays = defaultDetectReplays; private bool _expectIncomingMessages; private bool _expectOutgoingMessages; private SecurityAlgorithmSuite _incomingAlgorithmSuite = SecurityAlgorithmSuite.Default; // per receiver protocol factory lists private ICollection<SupportingTokenAuthenticatorSpecification> _channelSupportingTokenAuthenticatorSpecification; private Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>> _scopedSupportingTokenAuthenticatorSpecification; private Dictionary<string, MergedSupportingTokenAuthenticatorSpecification> _mergedSupportingTokenAuthenticatorsMap; private int _maxCachedNonces = defaultMaxCachedNonces; private TimeSpan _maxClockSkew = defaultMaxClockSkew; private NonceCache _nonceCache = null; private SecurityAlgorithmSuite _outgoingAlgorithmSuite = SecurityAlgorithmSuite.Default; private TimeSpan _replayWindow = defaultReplayWindow; private SecurityStandardsManager _standardsManager = SecurityStandardsManager.DefaultInstance; private SecurityTokenManager _securityTokenManager; private SecurityBindingElement _securityBindingElement; private string _requestReplyErrorPropertyName; private NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken> _derivedKeyTokenAuthenticator; private TimeSpan _timestampValidityDuration = defaultTimestampValidityDuration; private AuditLogLocation _auditLogLocation; private bool _suppressAuditFailure; private SecurityHeaderLayout _securityHeaderLayout; private AuditLevel _serviceAuthorizationAuditLevel; private AuditLevel _messageAuthenticationAuditLevel; private bool _expectKeyDerivation; private bool _expectChannelBasicTokens; private bool _expectChannelSignedTokens; private bool _expectChannelEndorsingTokens; private bool _expectSupportingTokens; private Uri _listenUri; private MessageSecurityVersion _messageSecurityVersion; private WrapperSecurityCommunicationObject _communicationObject; private Uri _privacyNoticeUri; private int _privacyNoticeVersion; private ExtendedProtectionPolicy _extendedProtectionPolicy; private BufferManager _streamBufferManager = null; protected SecurityProtocolFactory() { _channelSupportingTokenAuthenticatorSpecification = new Collection<SupportingTokenAuthenticatorSpecification>(); _scopedSupportingTokenAuthenticatorSpecification = new Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>>(); _communicationObject = new WrapperSecurityCommunicationObject(this); } internal SecurityProtocolFactory(SecurityProtocolFactory factory) : this() { if (factory == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("factory"); } _actAsInitiator = factory._actAsInitiator; _addTimestamp = factory._addTimestamp; _detectReplays = factory._detectReplays; _incomingAlgorithmSuite = factory._incomingAlgorithmSuite; _maxCachedNonces = factory._maxCachedNonces; _maxClockSkew = factory._maxClockSkew; _outgoingAlgorithmSuite = factory._outgoingAlgorithmSuite; _replayWindow = factory._replayWindow; _channelSupportingTokenAuthenticatorSpecification = new Collection<SupportingTokenAuthenticatorSpecification>(new List<SupportingTokenAuthenticatorSpecification>(factory._channelSupportingTokenAuthenticatorSpecification)); _scopedSupportingTokenAuthenticatorSpecification = new Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>>(factory._scopedSupportingTokenAuthenticatorSpecification); _standardsManager = factory._standardsManager; _timestampValidityDuration = factory._timestampValidityDuration; _auditLogLocation = factory._auditLogLocation; _suppressAuditFailure = factory._suppressAuditFailure; _serviceAuthorizationAuditLevel = factory._serviceAuthorizationAuditLevel; _messageAuthenticationAuditLevel = factory._messageAuthenticationAuditLevel; if (factory._securityBindingElement != null) { _securityBindingElement = (SecurityBindingElement)factory._securityBindingElement.Clone(); } _securityTokenManager = factory._securityTokenManager; _privacyNoticeUri = factory._privacyNoticeUri; _privacyNoticeVersion = factory._privacyNoticeVersion; _extendedProtectionPolicy = factory._extendedProtectionPolicy; _nonceCache = factory._nonceCache; } protected WrapperSecurityCommunicationObject CommunicationObject { get { return _communicationObject; } } // The ActAsInitiator value is set automatically on Open and // remains unchanged thereafter. ActAsInitiator is true for // the initiator of the message exchange, such as the sender // of a datagram, sender of a request and sender of either leg // of a duplex exchange. public bool ActAsInitiator { get { return _actAsInitiator; } } public BufferManager StreamBufferManager { get { if (_streamBufferManager == null) { _streamBufferManager = BufferManager.CreateBufferManager(0, int.MaxValue); } return _streamBufferManager; } set { _streamBufferManager = value; } } public ExtendedProtectionPolicy ExtendedProtectionPolicy { get { return _extendedProtectionPolicy; } set { _extendedProtectionPolicy = value; } } internal bool IsDuplexReply { get { return _isDuplexReply; } set { _isDuplexReply = value; } } public bool AddTimestamp { get { return _addTimestamp; } set { ThrowIfImmutable(); _addTimestamp = value; } } public AuditLogLocation AuditLogLocation { get { return _auditLogLocation; } set { ThrowIfImmutable(); AuditLogLocationHelper.Validate(value); _auditLogLocation = value; } } public bool SuppressAuditFailure { get { return _suppressAuditFailure; } set { ThrowIfImmutable(); _suppressAuditFailure = value; } } public AuditLevel ServiceAuthorizationAuditLevel { get { return _serviceAuthorizationAuditLevel; } set { ThrowIfImmutable(); AuditLevelHelper.Validate(value); _serviceAuthorizationAuditLevel = value; } } public AuditLevel MessageAuthenticationAuditLevel { get { return _messageAuthenticationAuditLevel; } set { ThrowIfImmutable(); AuditLevelHelper.Validate(value); _messageAuthenticationAuditLevel = value; } } public bool DetectReplays { get { return _detectReplays; } set { ThrowIfImmutable(); _detectReplays = value; } } public Uri PrivacyNoticeUri { get { return _privacyNoticeUri; } set { ThrowIfImmutable(); _privacyNoticeUri = value; } } public int PrivacyNoticeVersion { get { return _privacyNoticeVersion; } set { ThrowIfImmutable(); _privacyNoticeVersion = value; } } private static ReadOnlyCollection<SupportingTokenAuthenticatorSpecification> EmptyTokenAuthenticators { get { if (s_emptyTokenAuthenticators == null) { s_emptyTokenAuthenticators = new ReadOnlyCollection<SupportingTokenAuthenticatorSpecification>(new SupportingTokenAuthenticatorSpecification[0]); } return s_emptyTokenAuthenticators; } } internal NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken> DerivedKeyTokenAuthenticator { get { return _derivedKeyTokenAuthenticator; } } internal bool ExpectIncomingMessages { get { return _expectIncomingMessages; } } internal bool ExpectOutgoingMessages { get { return _expectOutgoingMessages; } } internal bool ExpectKeyDerivation { get { return _expectKeyDerivation; } set { _expectKeyDerivation = value; } } internal bool ExpectSupportingTokens { get { return _expectSupportingTokens; } set { _expectSupportingTokens = value; } } public SecurityAlgorithmSuite IncomingAlgorithmSuite { get { return _incomingAlgorithmSuite; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _incomingAlgorithmSuite = value; } } protected bool IsReadOnly { get { return this.CommunicationObject.State != CommunicationState.Created; } } public int MaxCachedNonces { get { return _maxCachedNonces; } set { ThrowIfImmutable(); if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _maxCachedNonces = value; } } public TimeSpan MaxClockSkew { get { return _maxClockSkew; } set { ThrowIfImmutable(); if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _maxClockSkew = value; } } public NonceCache NonceCache { get { return _nonceCache; } set { ThrowIfImmutable(); _nonceCache = value; } } public SecurityAlgorithmSuite OutgoingAlgorithmSuite { get { return _outgoingAlgorithmSuite; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _outgoingAlgorithmSuite = value; } } public TimeSpan ReplayWindow { get { return _replayWindow; } set { ThrowIfImmutable(); if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.TimeSpanMustbeGreaterThanTimeSpanZero)); } _replayWindow = value; } } public ICollection<SupportingTokenAuthenticatorSpecification> ChannelSupportingTokenAuthenticatorSpecification { get { return _channelSupportingTokenAuthenticatorSpecification; } } public Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>> ScopedSupportingTokenAuthenticatorSpecification { get { return _scopedSupportingTokenAuthenticatorSpecification; } } public SecurityBindingElement SecurityBindingElement { get { return _securityBindingElement; } set { ThrowIfImmutable(); if (value != null) { value = (SecurityBindingElement)value.Clone(); } _securityBindingElement = value; } } public SecurityTokenManager SecurityTokenManager { get { return _securityTokenManager; } set { ThrowIfImmutable(); _securityTokenManager = value; } } public virtual bool SupportsDuplex { get { return false; } } public SecurityHeaderLayout SecurityHeaderLayout { get { return _securityHeaderLayout; } set { ThrowIfImmutable(); _securityHeaderLayout = value; } } public virtual bool SupportsReplayDetection { get { return true; } } public virtual bool SupportsRequestReply { get { return true; } } public SecurityStandardsManager StandardsManager { get { return _standardsManager; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _standardsManager = value; } } public TimeSpan TimestampValidityDuration { get { return _timestampValidityDuration; } set { ThrowIfImmutable(); if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.TimeSpanMustbeGreaterThanTimeSpanZero)); } _timestampValidityDuration = value; } } public Uri ListenUri { get { return _listenUri; } set { ThrowIfImmutable(); _listenUri = value; } } internal MessageSecurityVersion MessageSecurityVersion { get { return _messageSecurityVersion; } } // ISecurityCommunicationObject members public TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnClose, timeout, callback, state); } public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnOpen, timeout, callback, state); } public void OnClosed() { } public void OnClosing() { } public void OnEndClose(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnEndOpen(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnFaulted() { } public void OnOpened() { } public void OnOpening() { } public virtual void OnAbort() { if (!_actAsInitiator) { foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.AbortTokenAuthenticatorIfRequired(spec.TokenAuthenticator); } foreach (string action in _scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = _scopedSupportingTokenAuthenticatorSpecification[action]; foreach (SupportingTokenAuthenticatorSpecification spec in supportingAuthenticators) { SecurityUtils.AbortTokenAuthenticatorIfRequired(spec.TokenAuthenticator); } } } } public virtual void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (!_actAsInitiator) { foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.CloseTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); } foreach (string action in _scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = _scopedSupportingTokenAuthenticatorSpecification[action]; foreach (SupportingTokenAuthenticatorSpecification spec in supportingAuthenticators) { SecurityUtils.CloseTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); } } } } public virtual object CreateListenerSecurityState() { return null; } public SecurityProtocol CreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, bool isReturnLegSecurityRequired, TimeSpan timeout) { ThrowIfNotOpen(); SecurityProtocol securityProtocol = OnCreateSecurityProtocol(target, via, listenerSecurityState, timeout); if (securityProtocol == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.ProtocolFactoryCouldNotCreateProtocol)); } return securityProtocol; } public virtual EndpointIdentity GetIdentityOfSelf() { return null; } public virtual T GetProperty<T>() { if (typeof(T) == typeof(Collection<ISecurityContextSecurityTokenCache>)) { ThrowIfNotOpen(); Collection<ISecurityContextSecurityTokenCache> result = new Collection<ISecurityContextSecurityTokenCache>(); if (_channelSupportingTokenAuthenticatorSpecification != null) { foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { if (spec.TokenAuthenticator is ISecurityContextSecurityTokenCacheProvider) { result.Add(((ISecurityContextSecurityTokenCacheProvider)spec.TokenAuthenticator).TokenCache); } } } return (T)(object)(result); } else { return default(T); } } protected abstract SecurityProtocol OnCreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, TimeSpan timeout); private void VerifyTypeUniqueness(ICollection<SupportingTokenAuthenticatorSpecification> supportingTokenAuthenticators) { // its ok to go brute force here since we are dealing with a small number of authenticators foreach (SupportingTokenAuthenticatorSpecification spec in supportingTokenAuthenticators) { Type authenticatorType = spec.TokenAuthenticator.GetType(); int numSkipped = 0; foreach (SupportingTokenAuthenticatorSpecification spec2 in supportingTokenAuthenticators) { Type spec2AuthenticatorType = spec2.TokenAuthenticator.GetType(); if (object.ReferenceEquals(spec, spec2)) { if (numSkipped > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MultipleSupportingAuthenticatorsOfSameType, spec.TokenParameters.GetType()))); } ++numSkipped; continue; } else if (authenticatorType.IsAssignableFrom(spec2AuthenticatorType) || spec2AuthenticatorType.IsAssignableFrom(authenticatorType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MultipleSupportingAuthenticatorsOfSameType, spec.TokenParameters.GetType()))); } } } } internal IList<SupportingTokenAuthenticatorSpecification> GetSupportingTokenAuthenticators(string action, out bool expectSignedTokens, out bool expectBasicTokens, out bool expectEndorsingTokens) { if (_mergedSupportingTokenAuthenticatorsMap != null && _mergedSupportingTokenAuthenticatorsMap.Count > 0) { if (action != null && _mergedSupportingTokenAuthenticatorsMap.ContainsKey(action)) { MergedSupportingTokenAuthenticatorSpecification mergedSpec = _mergedSupportingTokenAuthenticatorsMap[action]; expectSignedTokens = mergedSpec.ExpectSignedTokens; expectBasicTokens = mergedSpec.ExpectBasicTokens; expectEndorsingTokens = mergedSpec.ExpectEndorsingTokens; return mergedSpec.SupportingTokenAuthenticators; } else if (_mergedSupportingTokenAuthenticatorsMap.ContainsKey(MessageHeaders.WildcardAction)) { MergedSupportingTokenAuthenticatorSpecification mergedSpec = _mergedSupportingTokenAuthenticatorsMap[MessageHeaders.WildcardAction]; expectSignedTokens = mergedSpec.ExpectSignedTokens; expectBasicTokens = mergedSpec.ExpectBasicTokens; expectEndorsingTokens = mergedSpec.ExpectEndorsingTokens; return mergedSpec.SupportingTokenAuthenticators; } } expectSignedTokens = _expectChannelSignedTokens; expectBasicTokens = _expectChannelBasicTokens; expectEndorsingTokens = _expectChannelEndorsingTokens; // in case the channelSupportingTokenAuthenticators is empty return null so that its Count does not get accessed. return (Object.ReferenceEquals(_channelSupportingTokenAuthenticatorSpecification, EmptyTokenAuthenticators)) ? null : (IList<SupportingTokenAuthenticatorSpecification>)_channelSupportingTokenAuthenticatorSpecification; } private void MergeSupportingTokenAuthenticators(TimeSpan timeout) { if (_scopedSupportingTokenAuthenticatorSpecification.Count == 0) { _mergedSupportingTokenAuthenticatorsMap = null; } else { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); _expectSupportingTokens = true; _mergedSupportingTokenAuthenticatorsMap = new Dictionary<string, MergedSupportingTokenAuthenticatorSpecification>(); foreach (string action in _scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> scopedAuthenticators = _scopedSupportingTokenAuthenticatorSpecification[action]; if (scopedAuthenticators == null || scopedAuthenticators.Count == 0) { continue; } Collection<SupportingTokenAuthenticatorSpecification> mergedAuthenticators = new Collection<SupportingTokenAuthenticatorSpecification>(); bool expectSignedTokens = _expectChannelSignedTokens; bool expectBasicTokens = _expectChannelBasicTokens; bool expectEndorsingTokens = _expectChannelEndorsingTokens; foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { mergedAuthenticators.Add(spec); } foreach (SupportingTokenAuthenticatorSpecification spec in scopedAuthenticators) { SecurityUtils.OpenTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); mergedAuthenticators.Add(spec); if (spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing) { if (spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey) { _expectKeyDerivation = true; } } SecurityTokenAttachmentMode mode = spec.SecurityTokenAttachmentMode; if (mode == SecurityTokenAttachmentMode.SignedEncrypted || mode == SecurityTokenAttachmentMode.Signed || mode == SecurityTokenAttachmentMode.SignedEndorsing) { expectSignedTokens = true; if (mode == SecurityTokenAttachmentMode.SignedEncrypted) { expectBasicTokens = true; } } if (mode == SecurityTokenAttachmentMode.Endorsing || mode == SecurityTokenAttachmentMode.SignedEndorsing) { expectEndorsingTokens = true; } } VerifyTypeUniqueness(mergedAuthenticators); MergedSupportingTokenAuthenticatorSpecification mergedSpec = new MergedSupportingTokenAuthenticatorSpecification(); mergedSpec.SupportingTokenAuthenticators = mergedAuthenticators; mergedSpec.ExpectBasicTokens = expectBasicTokens; mergedSpec.ExpectEndorsingTokens = expectEndorsingTokens; mergedSpec.ExpectSignedTokens = expectSignedTokens; _mergedSupportingTokenAuthenticatorsMap.Add(action, mergedSpec); } } } protected RecipientServiceModelSecurityTokenRequirement CreateRecipientSecurityTokenRequirement() { RecipientServiceModelSecurityTokenRequirement requirement = new RecipientServiceModelSecurityTokenRequirement(); requirement.SecurityBindingElement = _securityBindingElement; requirement.SecurityAlgorithmSuite = this.IncomingAlgorithmSuite; requirement.ListenUri = _listenUri; requirement.MessageSecurityVersion = this.MessageSecurityVersion.SecurityTokenVersion; requirement.Properties[ServiceModelSecurityTokenRequirement.ExtendedProtectionPolicy] = _extendedProtectionPolicy; return requirement; } private RecipientServiceModelSecurityTokenRequirement CreateRecipientSecurityTokenRequirement(SecurityTokenParameters parameters, SecurityTokenAttachmentMode attachmentMode) { RecipientServiceModelSecurityTokenRequirement requirement = CreateRecipientSecurityTokenRequirement(); requirement.KeyUsage = SecurityKeyUsage.Signature; requirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = MessageDirection.Input; requirement.Properties[ServiceModelSecurityTokenRequirement.SupportingTokenAttachmentModeProperty] = attachmentMode; requirement.Properties[ServiceModelSecurityTokenRequirement.ExtendedProtectionPolicy] = _extendedProtectionPolicy; return requirement; } private void AddSupportingTokenAuthenticators(SupportingTokenParameters supportingTokenParameters, bool isOptional, IList<SupportingTokenAuthenticatorSpecification> authenticatorSpecList) { for (int i = 0; i < supportingTokenParameters.Endorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Endorsing[i], SecurityTokenAttachmentMode.Endorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Endorsing, supportingTokenParameters.Endorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEndorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEndorsing[i], SecurityTokenAttachmentMode.SignedEndorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEndorsing, supportingTokenParameters.SignedEndorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEncrypted.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEncrypted[i], SecurityTokenAttachmentMode.SignedEncrypted); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEncrypted, supportingTokenParameters.SignedEncrypted[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.Signed.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Signed[i], SecurityTokenAttachmentMode.Signed); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Signed, supportingTokenParameters.Signed[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } } public virtual void OnOpen(TimeSpan timeout) { if (this.SecurityBindingElement == null) { this.OnPropertySettingsError("SecurityBindingElement", true); } if (this.SecurityTokenManager == null) { this.OnPropertySettingsError("SecurityTokenManager", true); } _messageSecurityVersion = _standardsManager.MessageSecurityVersion; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); _expectOutgoingMessages = this.ActAsInitiator || this.SupportsRequestReply; _expectIncomingMessages = !this.ActAsInitiator || this.SupportsRequestReply; if (!_actAsInitiator) { AddSupportingTokenAuthenticators(_securityBindingElement.EndpointSupportingTokenParameters, false, (IList<SupportingTokenAuthenticatorSpecification>)_channelSupportingTokenAuthenticatorSpecification); // validate the token authenticator types and create a merged map if needed. if (!_channelSupportingTokenAuthenticatorSpecification.IsReadOnly) { if (_channelSupportingTokenAuthenticatorSpecification.Count == 0) { _channelSupportingTokenAuthenticatorSpecification = EmptyTokenAuthenticators; } else { _expectSupportingTokens = true; foreach (SupportingTokenAuthenticatorSpecification tokenAuthenticatorSpec in _channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.OpenTokenAuthenticatorIfRequired(tokenAuthenticatorSpec.TokenAuthenticator, timeoutHelper.RemainingTime()); if (tokenAuthenticatorSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || tokenAuthenticatorSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing) { if (tokenAuthenticatorSpec.TokenParameters.RequireDerivedKeys && !tokenAuthenticatorSpec.TokenParameters.HasAsymmetricKey) { _expectKeyDerivation = true; } } SecurityTokenAttachmentMode mode = tokenAuthenticatorSpec.SecurityTokenAttachmentMode; if (mode == SecurityTokenAttachmentMode.SignedEncrypted || mode == SecurityTokenAttachmentMode.Signed || mode == SecurityTokenAttachmentMode.SignedEndorsing) { _expectChannelSignedTokens = true; if (mode == SecurityTokenAttachmentMode.SignedEncrypted) { _expectChannelBasicTokens = true; } } if (mode == SecurityTokenAttachmentMode.Endorsing || mode == SecurityTokenAttachmentMode.SignedEndorsing) { _expectChannelEndorsingTokens = true; } } _channelSupportingTokenAuthenticatorSpecification = new ReadOnlyCollection<SupportingTokenAuthenticatorSpecification>((Collection<SupportingTokenAuthenticatorSpecification>)_channelSupportingTokenAuthenticatorSpecification); } } VerifyTypeUniqueness(_channelSupportingTokenAuthenticatorSpecification); MergeSupportingTokenAuthenticators(timeoutHelper.RemainingTime()); } if (this.DetectReplays) { if (!this.SupportsReplayDetection) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("DetectReplays", SR.Format(SR.SecurityProtocolCannotDoReplayDetection, this)); } if (this.MaxClockSkew == TimeSpan.MaxValue || this.ReplayWindow == TimeSpan.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.NoncesCachedInfinitely)); } // If DetectReplays is true and nonceCache is null then use the default InMemoryNonceCache. if (_nonceCache == null) { // The nonce needs to be cached for replayWindow + 2*clockSkew to eliminate replays _nonceCache = new InMemoryNonceCache(this.ReplayWindow + this.MaxClockSkew + this.MaxClockSkew, this.MaxCachedNonces); } } _derivedKeyTokenAuthenticator = new NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken>(); } public void Open(bool actAsInitiator, TimeSpan timeout) { _actAsInitiator = actAsInitiator; _communicationObject.Open(timeout); } public IAsyncResult BeginOpen(bool actAsInitiator, TimeSpan timeout, AsyncCallback callback, object state) { _actAsInitiator = actAsInitiator; return this.CommunicationObject.BeginOpen(timeout, callback, state); } public void EndOpen(IAsyncResult result) { this.CommunicationObject.EndOpen(result); } public void Close(bool aborted, TimeSpan timeout) { if (aborted) { this.CommunicationObject.Abort(); } else { this.CommunicationObject.Close(timeout); } } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return this.CommunicationObject.BeginClose(timeout, callback, state); } public void EndClose(IAsyncResult result) { this.CommunicationObject.EndClose(result); } internal void Open(string propertyName, bool requiredForForwardDirection, SecurityTokenAuthenticator authenticator, TimeSpan timeout) { if (authenticator != null) { SecurityUtils.OpenTokenAuthenticatorIfRequired(authenticator, timeout); } else { OnPropertySettingsError(propertyName, requiredForForwardDirection); } } internal void Open(string propertyName, bool requiredForForwardDirection, SecurityTokenProvider provider, TimeSpan timeout) { if (provider != null) { SecurityUtils.OpenTokenProviderIfRequired(provider, timeout); } else { OnPropertySettingsError(propertyName, requiredForForwardDirection); } } internal void OnPropertySettingsError(string propertyName, bool requiredForForwardDirection) { if (requiredForForwardDirection) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.Format(SR.PropertySettingErrorOnProtocolFactory, propertyName, this), propertyName)); } else if (_requestReplyErrorPropertyName == null) { _requestReplyErrorPropertyName = propertyName; } } private void ThrowIfReturnDirectionSecurityNotSupported() { if (_requestReplyErrorPropertyName != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.Format(SR.PropertySettingErrorOnProtocolFactory, _requestReplyErrorPropertyName, this), _requestReplyErrorPropertyName)); } } internal void ThrowIfImmutable() { _communicationObject.ThrowIfDisposedOrImmutable(); } private void ThrowIfNotOpen() { _communicationObject.ThrowIfNotOpened(); } } internal struct MergedSupportingTokenAuthenticatorSpecification { public Collection<SupportingTokenAuthenticatorSpecification> SupportingTokenAuthenticators; public bool ExpectSignedTokens; public bool ExpectEndorsingTokens; public bool ExpectBasicTokens; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Text; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.IE { /// <summary> /// Provides a way to access Internet Explorer to run your tests by creating a InternetExplorerDriver instance /// </summary> /// <remarks> /// When the WebDriver object has been instantiated the browser will load. The test can then navigate to the URL under test and /// start your test. /// </remarks> /// <example> /// <code> /// [TestFixture] /// public class Testing /// { /// private IWebDriver driver; /// <para></para> /// [SetUp] /// public void SetUp() /// { /// driver = new InternetExplorerDriver(); /// } /// <para></para> /// [Test] /// public void TestGoogle() /// { /// driver.Navigate().GoToUrl("http://www.google.co.uk"); /// /* /// * Rest of the test /// */ /// } /// <para></para> /// [TearDown] /// public void TearDown() /// { /// driver.Quit(); /// driver.Dispose(); /// } /// } /// </code> /// </example> public sealed class InternetExplorerDriver : IWebDriver, ISearchContext, IJavaScriptExecutor, ITakesScreenshot { #region Private members private bool disposed; private SafeInternetExplorerDriverHandle handle; private InternetExplorerNavigation navigation; private InternetExplorerOptions options; private InternetExplorerTargetLocator targetLocator; #endregion #region Constructor /// <summary> /// Initializes a new instance of the InternetExplorerDriver class. /// </summary> public InternetExplorerDriver() { handle = new SafeInternetExplorerDriverHandle(); WebDriverResult result = NativeDriverLibrary.Instance.NewDriverInstance(ref handle); if (result != WebDriverResult.Success) { throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, "Cannot create new browser instance: {0}", result.ToString())); } } #endregion #region IWebDriver Members /// <summary> /// Gets or sets the URL the browser is currently displaying. /// </summary> /// <seealso cref="IWebDriver.Url"/> /// <seealso cref="INavigation.GoToUrl(System.String)"/> /// <seealso cref="INavigation.GoToUrl(System.Uri)"/> public string Url { get { SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetCurrentUrl(handle, ref stringHandle); if (result != WebDriverResult.Success) { stringHandle.Dispose(); throw new InvalidOperationException("Unable to get current URL:" + result.ToString()); } string returnValue = string.Empty; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { returnValue = wrapper.Value; } return returnValue; } set { if (disposed) { throw new ObjectDisposedException("handle"); } if (value == null) { throw new ArgumentNullException("value", "Argument 'url' cannot be null."); } WebDriverResult result = NativeDriverLibrary.Instance.ChangeCurrentUrl(handle, value); if (result != WebDriverResult.Success) { ResultHandler.VerifyResultCode(result, string.Format(CultureInfo.InvariantCulture, "Cannot go to '{0}': {1}", value, result.ToString())); } } } /// <summary> /// Gets the title of the current browser window. /// </summary> public string Title { get { SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetTitle(handle, ref stringHandle); if (result != WebDriverResult.Success) { stringHandle.Dispose(); throw new InvalidOperationException("Unable to get current title:" + result.ToString()); } string returnValue = string.Empty; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { returnValue = wrapper.Value; } return returnValue; } } /// <summary> /// Gets or sets a value indicating whether the browser is visible. /// </summary> public bool Visible { get { int visible = 0; WebDriverResult result = NativeDriverLibrary.Instance.GetVisible(handle, ref visible); ResultHandler.VerifyResultCode(result, "Unable to determine if browser is visible"); return visible == 1; } set { WebDriverResult result = NativeDriverLibrary.Instance.SetVisible(handle, value ? 1 : 0); ResultHandler.VerifyResultCode(result, "Unable to change the visibility of the browser"); } } /// <summary> /// Gets the source of the page last loaded by the browser. /// </summary> public string PageSource { get { SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetPageSource(handle, ref stringHandle); ResultHandler.VerifyResultCode(result, "Unable to get page source"); string returnValue = string.Empty; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { returnValue = wrapper.Value; } return returnValue; } } /// <summary> /// Gets a value indicating whether JavaScript is enabled for this browser. /// </summary> public bool IsJavaScriptEnabled { get { return true; } } /// <summary> /// Closes the Browser. /// </summary> public void Close() { WebDriverResult result = NativeDriverLibrary.Instance.Close(handle); if (result != WebDriverResult.Success) { throw new InvalidOperationException("Unable to close driver: " + result.ToString()); } } /// <summary> /// Close the Browser and Dispose of WebDriver. /// </summary> public void Quit() { // This code mimics the Java implementation. try { ReadOnlyCollection<string> handleList = GetWindowHandles(); foreach (string windowHandle in handleList) { try { SwitchTo().Window(windowHandle); Close(); } catch (NoSuchWindowException) { // doesn't matter one jot. } } } catch (NotSupportedException) { // Stuff happens. Bail out Dispose(); } Dispose(); } /// <summary> /// Executes JavaScript in the context of the currently selected frame or window. /// </summary> /// <param name="script">The JavaScript code to execute.</param> /// <param name="args">The arguments to the script.</param> /// <returns>The value returned by the script.</returns> /// <remarks> /// <para> /// The <see cref="ExecuteScript"/>method executes JavaScript in the context of /// the currently selected frame or window. This means that "document" will refer /// to the current document. If the script has a return value, then the following /// steps will be taken: /// </para> /// <para> /// <list type="bullet"> /// <item><description>For an HTML element, this method returns a <see cref="IWebElement"/></description></item> /// <item><description>For a number, a <see cref="System.Int64"/> is returned</description></item> /// <item><description>For a boolean, a <see cref="System.Boolean"/> is returned</description></item> /// <item><description>For all other cases a <see cref="System.String"/> is returned.</description></item> /// <item><description>For an array,we check the first element, and attempt to return a /// <see cref="List{T}"/> of that type, following the rules above. Nested lists are not /// supported.</description></item> /// <item><description>If the value is null or there is no return value, /// <see langword="null"/> is returned.</description></item> /// </list> /// </para> /// <para> /// Arguments must be a number (which will be converted to a <see cref="System.Int64"/>), /// a <see cref="System.Boolean"/>, a <see cref="System.String"/> or a <see cref="IWebElement"/>. /// An exception will be thrown if the arguments do not meet these criteria. /// The arguments will be made available to the JavaScript via the "arguments" magic /// variable, as if the function were called via "Function.apply" /// </para> /// </remarks> public object ExecuteScript(string script, params object[] args) { object toReturn = null; SafeScriptArgsHandle scriptArgsHandle = new SafeScriptArgsHandle(); WebDriverResult result = NativeDriverLibrary.Instance.NewScriptArgs(ref scriptArgsHandle, args.Length); ResultHandler.VerifyResultCode(result, "Unable to create new script arguments array"); try { PopulateArguments(scriptArgsHandle, args); script = "(function() { return function(){" + script + "};})();"; SafeScriptResultHandle scriptResultHandle = new SafeScriptResultHandle(); result = NativeDriverLibrary.Instance.ExecuteScript(handle, script, scriptArgsHandle, ref scriptResultHandle); ResultHandler.VerifyResultCode(result, "Cannot execute script"); // Note that ExtractReturnValue frees the memory for the script result. toReturn = ExtractReturnValue(scriptResultHandle); } finally { scriptArgsHandle.Dispose(); } return toReturn; } /// <summary> /// Method for returning a collection of WindowHandles that the driver has access to. /// </summary> /// <returns>Returns a ReadOnlyCollection of Window Handles.</returns> /// <example> /// IWebDriver driver = new InternetExplorerDriver(); /// ReadOnlyCollection<![CDATA[<string>]]> windowNames = driver.GetWindowHandles(); /// </example> public ReadOnlyCollection<string> GetWindowHandles() { SafeStringCollectionHandle handlesPtr = new SafeStringCollectionHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetAllWindowHandles(handle, ref handlesPtr); ResultHandler.VerifyResultCode(result, "Unable to obtain all window handles"); List<string> windowHandleList = new List<string>(); using (StringCollection windowHandleStringCollection = new StringCollection(handlesPtr)) { windowHandleList = windowHandleStringCollection.ToList(); } return new ReadOnlyCollection<string>(windowHandleList); } /// <summary> /// Returns the Name of Window that the driver is working in. /// </summary> /// <returns>Returns the name of the Window.</returns> /// <example> /// IWebDriver driver = new InternetExplorerDriver(); /// string windowName = driver.GetWindowHandles(); /// </example> public string GetWindowHandle() { SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetCurrentWindowHandle(handle, ref stringHandle); ResultHandler.VerifyResultCode(result, "Unable to obtain current window handle"); string handleValue = string.Empty; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { handleValue = wrapper.Value; } return handleValue; } /// <summary> /// Method to give you access to switch frames and windows. /// </summary> /// <returns>Returns an Object that allows you to Switch Frames and Windows.</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// driver.SwitchTo().Frame("FrameName"); /// </code> /// </example> public ITargetLocator SwitchTo() { if (targetLocator == null) { targetLocator = new InternetExplorerTargetLocator(this); } return targetLocator; } /// <summary> /// Method For getting an object to set the Speed. /// </summary> /// <returns>Returns an IOptions object that allows the driver to set the speed and cookies and getting cookies.</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// driver.Manage().GetCookies(); /// </code> /// </example> public IOptions Manage() { if (options == null) { options = new InternetExplorerOptions(this); } return options; } /// <summary> /// Method to allow you to Navigate with WebDriver. /// </summary> /// <returns>Returns an INavigation Object that allows the driver to navigate in the browser.</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// driver.Navigate().GoToUrl("http://www.google.co.uk"); /// </code> /// </example> public INavigation Navigate() { if (navigation == null) { navigation = new InternetExplorerNavigation(this); } return navigation; } #endregion #region ISearchContext Members /// <summary> /// Finds the elements on the page by using the <see cref="By"/> object and returns a ReadOnlyCollection of the Elements on the page. /// </summary> /// <param name="by">By mechanism for finding the element.</param> /// <returns>ReadOnlyCollection of IWebElement.</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> classList = driver.FindElements(By.ClassName("class")); /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElements(By by) { return by.FindElements(new Finder(this, new SafeInternetExplorerWebElementHandle())); } /// <summary> /// Finds the first element in the page that matches the <see cref="By"/> object. /// </summary> /// <param name="by">By mechanism for finding the element.</param> /// <returns>IWebElement object so that you can interction that object.</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// IWebElement elem = driver.FindElement(By.Name("q")); /// </code> /// </example> public IWebElement FindElement(By by) { return by.FindElement(new Finder(this, new SafeInternetExplorerWebElementHandle())); } #endregion #region ITakesScreenshot Members /// <summary> /// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen. /// </summary> /// <returns>A <see cref="Screenshot"/> object containing the image.</returns> public Screenshot GetScreenshot() { Screenshot currentScreenshot = null; SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); WebDriverResult result = NativeDriverLibrary.Instance.CaptureScreenshotAsBase64(handle, ref stringHandle); ResultHandler.VerifyResultCode(result, "Unable to get screenshot"); string screenshotValue = string.Empty; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { screenshotValue = wrapper.Value; } if (!string.IsNullOrEmpty(screenshotValue)) { currentScreenshot = new Screenshot(screenshotValue); } return currentScreenshot; } #endregion #region IDisposable Members /// <summary> /// Disposes of all unmanaged instances of InternetExplorerDriver. /// </summary> public void Dispose() { if (!disposed) { handle.Dispose(); disposed = true; } } #endregion #region Internal and private support members /// <summary> /// Get the driver handle. /// </summary> /// <returns>The underlying handle.</returns> internal SafeInternetExplorerDriverHandle GetUnderlayingHandle() { return handle; } /// <summary> /// Wait for the load to complete. /// </summary> public void WaitForLoadToComplete() { NativeDriverLibrary.Instance.WaitForLoadToComplete(handle); } private static WebDriverResult PopulateArguments(SafeScriptArgsHandle scriptArgs, object[] args) { WebDriverResult result = WebDriverResult.Success; foreach (object arg in args) { string stringArg = arg as string; InternetExplorerWebElement webElementArg = arg as InternetExplorerWebElement; if (stringArg != null) { result = NativeDriverLibrary.Instance.AddStringScriptArg(scriptArgs, stringArg); } else if (arg is bool) { bool param = (bool)arg; result = NativeDriverLibrary.Instance.AddBooleanScriptArg(scriptArgs, !param ? 0 : 1); } else if (webElementArg != null) { result = webElementArg.AddToScriptArgs(scriptArgs); } else if (arg is int || arg is short || arg is long) { int param; bool parseSucceeded = int.TryParse(arg.ToString(), out param); if (!parseSucceeded) { throw new ArgumentException("Parameter is not recognized as an int: " + arg); } result = NativeDriverLibrary.Instance.AddNumberScriptArg(scriptArgs, param); } else if (arg is float || arg is double) { double param; bool parseSucceeded = double.TryParse(arg.ToString(), out param); if (!parseSucceeded) { throw new ArgumentException("Parameter is not of recognized as a double: " + arg); } result = NativeDriverLibrary.Instance.AddDoubleScriptArg(scriptArgs, param); } else { throw new ArgumentException("Parameter is not of recognized type: " + arg); } ResultHandler.VerifyResultCode(result, "Unable to add argument: " + arg); } return result; } private object ExtractReturnValue(SafeScriptResultHandle scriptResult) { WebDriverResult result; int type; result = NativeDriverLibrary.Instance.GetScriptResultType(handle, scriptResult, out type); ResultHandler.VerifyResultCode(result, "Cannot determine result type"); object toReturn = null; try { switch (type) { case 1: SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); result = NativeDriverLibrary.Instance.GetStringScriptResult(scriptResult, ref stringHandle); ResultHandler.VerifyResultCode(result, "Cannot extract string result"); using (StringWrapper wrapper = new StringWrapper(stringHandle)) { toReturn = wrapper.Value; } break; case 2: long longVal; result = NativeDriverLibrary.Instance.GetNumberScriptResult(scriptResult, out longVal); ResultHandler.VerifyResultCode(result, "Cannot extract number result"); toReturn = longVal; break; case 3: int boolVal; result = NativeDriverLibrary.Instance.GetBooleanScriptResult(scriptResult, out boolVal); ResultHandler.VerifyResultCode(result, "Cannot extract boolean result"); toReturn = boolVal == 1 ? true : false; break; case 4: SafeInternetExplorerWebElementHandle element; result = NativeDriverLibrary.Instance.GetElementScriptResult(scriptResult, handle, out element); ResultHandler.VerifyResultCode(result, "Cannot extract element result"); toReturn = new InternetExplorerWebElement(this, element); break; case 5: toReturn = null; break; case 6: SafeStringWrapperHandle messageHandle = new SafeStringWrapperHandle(); result = NativeDriverLibrary.Instance.GetStringScriptResult(scriptResult, ref messageHandle); ResultHandler.VerifyResultCode(result, "Cannot extract string result"); string message = string.Empty; using (StringWrapper wrapper = new StringWrapper(messageHandle)) { message = wrapper.Value; } throw new WebDriverException(message); case 7: double doubleVal; result = NativeDriverLibrary.Instance.GetDoubleScriptResult(scriptResult, out doubleVal); ResultHandler.VerifyResultCode(result, "Cannot extract number result"); toReturn = doubleVal; break; case 8: bool allArrayItemsAreElements = true; int arrayLength = 0; result = NativeDriverLibrary.Instance.GetArrayLengthScriptResult(handle, scriptResult, out arrayLength); ResultHandler.VerifyResultCode(result, "Cannot extract array length."); List<object> list = new List<object>(); for (int i = 0; i < arrayLength; i++) { // Get reference to object SafeScriptResultHandle currItemHandle = new SafeScriptResultHandle(); WebDriverResult getItemResult = NativeDriverLibrary.Instance.GetArrayItemFromScriptResult(handle, scriptResult, i, out currItemHandle); if (getItemResult != WebDriverResult.Success) { // Note about memory management: Usually memory for this item // will be released during the recursive call to // ExtractReturnValue. It is freed explicitly here since a // recursive call will not happen. currItemHandle.Dispose(); throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, "Cannot extract element from collection at index: {0} ({1})", i, result)); } object arrayItem = ExtractReturnValue(currItemHandle); if (allArrayItemsAreElements && !(arrayItem is IWebElement)) { allArrayItemsAreElements = false; } // Call ExtractReturnValue with the fetched item (recursive) list.Add(arrayItem); } if (allArrayItemsAreElements) { List<IWebElement> elementList = new List<IWebElement>(); foreach (object item in list) { elementList.Add((IWebElement)item); } toReturn = elementList.AsReadOnly(); } else { toReturn = list.AsReadOnly(); } break; default: throw new WebDriverException("Cannot determine result type"); } } finally { scriptResult.Dispose(); } return toReturn; } #endregion #region IOptions class /// <summary> /// Provides a mechanism for setting options needed for the driver during the test. /// </summary> private class InternetExplorerOptions : IOptions { private Speed internalSpeed = Speed.Fast; private InternetExplorerDriver driver; /// <summary> /// Initializes a new instance of the InternetExplorerOptions class. /// </summary> /// <param name="driver">Instance of the driver currently in use.</param> public InternetExplorerOptions(InternetExplorerDriver driver) { this.driver = driver; } /// <summary> /// Gets or sets the speed with which actions are executed in the browser. /// </summary> public Speed Speed { get { return internalSpeed; } set { internalSpeed = value; } } /// <summary> /// Method for creating a cookie in the browser. /// </summary> /// <param name="cookie"><see cref="Cookie"/> that represents a cookie in the browser.</param> public void AddCookie(Cookie cookie) { ////wdAddCookie does not properly add cookies with expiration dates, ////thus cookies are not properly deleted. Use JavaScript execution, ////just like the Java implementation does. ////string cookieString = cookie.ToString(); ////WebDriverResult result = NativeDriverLibrary.Instance.AddCookie(driver.handle, cookieString); ////ResultHandler.VerifyResultCode(result, "Add Cookie"); StringBuilder sb = new StringBuilder(cookie.Name); sb.Append("="); sb.Append(cookie.Value); sb.Append("; "); if (!string.IsNullOrEmpty(cookie.Path)) { sb.Append("path="); sb.Append(cookie.Path); sb.Append("; "); } if (!string.IsNullOrEmpty(cookie.Domain)) { string domain = cookie.Domain; int colon = domain.IndexOf(":", StringComparison.OrdinalIgnoreCase); if (colon != -1) { domain = domain.Substring(0, colon); } sb.Append("domain="); sb.Append(domain); sb.Append("; "); } if (cookie.Expiry != null) { sb.Append("expires="); sb.Append(cookie.Expiry.Value.ToUniversalTime().ToString("ddd MM/dd/yyyy HH:mm:ss UTC", CultureInfo.InvariantCulture)); } driver.ExecuteScript("document.cookie = arguments[0]", sb.ToString()); } /// <summary> /// Method for getting a Collection of Cookies that are present in the browser. /// </summary> /// <returns>ReadOnlyCollection of Cookies in the browser.</returns> public ReadOnlyCollection<Cookie> GetCookies() { Uri currentUri = GetCurrentUri(); SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetCookies(driver.handle, ref stringHandle); ResultHandler.VerifyResultCode(result, "Getting Cookies"); string allDomainCookies = string.Empty; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { allDomainCookies = wrapper.Value; } List<Cookie> toReturn = new List<Cookie>(); string[] cookies = allDomainCookies.Split(new string[] { "; " }, StringSplitOptions.RemoveEmptyEntries); foreach (string cookie in cookies) { string[] parts = cookie.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { continue; } toReturn.Add(new ReturnedCookie(parts[0], parts[1], currentUri.Host, string.Empty, null, false, currentUri)); } return new ReadOnlyCollection<Cookie>(toReturn); } /// <summary> /// Method for returning a getting a cookie by name. /// </summary> /// <param name="name">name of the cookie that needs to be returned.</param> /// <returns>The <see cref="Cookie"/> with the name that was passed in.</returns> public Cookie GetCookieNamed(string name) { Cookie cookieToReturn = null; ReadOnlyCollection<Cookie> allCookies = GetCookies(); foreach (Cookie currentCookie in allCookies) { if (name.Equals(currentCookie.Name)) { cookieToReturn = currentCookie; break; } } return cookieToReturn; } /// <summary> /// Delete All Cookies that are present in the browser. /// </summary> public void DeleteAllCookies() { ReadOnlyCollection<Cookie> allCookies = GetCookies(); foreach (Cookie cookieToDelete in allCookies) { DeleteCookie(cookieToDelete); } } /// <summary> /// Delete a cookie in the browser that is the. /// </summary> /// <param name="cookie">An object that represents a copy of the cookie that needs to be deleted.</param> public void DeleteCookie(Cookie cookie) { ////Uri currentUri = new Uri(driver.Url); ////DateTime dateInPast = DateTime.MinValue; ////AddCookie(new Cookie(cookie.Name, cookie.Value, currentUri.Host, currentUri.PathAndQuery, dateInPast)); if (cookie == null) { throw new WebDriverException("Cookie to delete cannot be null"); } string currentUrl = driver.Url; try { Uri uri = new Uri(currentUrl); Cookie toDelete = new NullPathCookie(cookie.Name, cookie.Value, uri.Host, uri.AbsolutePath, DateTime.MinValue); DeleteCookieByPath(toDelete); } catch (UriFormatException e) { throw new WebDriverException("Cannot delete cookie: " + e.Message); } } /// <summary> /// Delete the cookie by passing in the name of the cookie. /// </summary> /// <param name="name">The name of the cookie that is in the browser.</param> public void DeleteCookieNamed(string name) { DeleteCookie(GetCookieNamed(name)); } /// <summary> /// Provides access to the timeouts defined for this driver. /// </summary> /// <returns>An object implementing the <see cref="ITimeouts"/> interface.</returns> public ITimeouts Timeouts() { return new InternetExplorerTimeouts(driver); } private Uri GetCurrentUri() { Uri currentUri = null; try { currentUri = new Uri(driver.Url); } catch (UriFormatException) { } return currentUri; } private void DeleteCookieByPath(Cookie cookie) { Cookie toDelete = null; string path = cookie.Path; if (path != null) { string[] segments = cookie.Path.Split(new char[] { '/' }); StringBuilder currentPath = new StringBuilder(); foreach (string segment in segments) { if (string.IsNullOrEmpty(segment)) { continue; } currentPath.Append("/"); currentPath.Append(segment); toDelete = new NullPathCookie(cookie.Name, cookie.Value, cookie.Domain, currentPath.ToString(), DateTime.MinValue); RecursivelyDeleteCookieByDomain(toDelete); } } toDelete = new NullPathCookie(cookie.Name, cookie.Value, cookie.Domain, "/", DateTime.MinValue); RecursivelyDeleteCookieByDomain(toDelete); toDelete = new NullPathCookie(cookie.Name, cookie.Value, cookie.Domain, null, DateTime.MinValue); RecursivelyDeleteCookieByDomain(toDelete); } private void RecursivelyDeleteCookieByDomain(Cookie cookie) { AddCookie(cookie); int dotIndex = cookie.Domain.IndexOf('.'); if (dotIndex == 0) { string domain = cookie.Domain.Substring(1); Cookie toDelete = new NullPathCookie(cookie.Name, cookie.Value, domain, cookie.Path, DateTime.MinValue); RecursivelyDeleteCookieByDomain(toDelete); } else if (dotIndex != -1) { string domain = cookie.Domain.Substring(dotIndex); Cookie toDelete = new NullPathCookie(cookie.Name, cookie.Value, domain, cookie.Path, DateTime.MinValue); RecursivelyDeleteCookieByDomain(toDelete); } else { Cookie toDelete = new NullPathCookie(cookie.Name, cookie.Value, string.Empty, cookie.Path, DateTime.MinValue); AddCookie(toDelete); } } #region ITimeouts class /// <summary> /// Defines the interface through which the user can define timeouts. /// </summary> private class InternetExplorerTimeouts : ITimeouts { private InternetExplorerDriver driver; /// <summary> /// Initializes a new instance of the InternetExplorerTimeouts class /// </summary> /// <param name="driver">The driver that is currently in use</param> public InternetExplorerTimeouts(InternetExplorerDriver driver) { this.driver = driver; } #region ITimeouts Members /// <summary> /// Specifies the amount of time the driver should wait when searching for an /// element if it is not immediately present. /// </summary> /// <param name="timeToWait">A <see cref="TimeSpan"/> structure defining the amount of time to wait.</param> /// <returns>A self reference</returns> /// <remarks> /// When searching for a single element, the driver should poll the page /// until the element has been found, or this timeout expires before throwing /// a <see cref="NoSuchElementException"/>. When searching for multiple elements, /// the driver should poll the page until at least one element has been found /// or this timeout has expired. /// <para> /// Increasing the implicit wait timeout should be used judiciously as it /// will have an adverse effect on test run time, especially when used with /// slower location strategies like XPath. /// </para> /// </remarks> public ITimeouts ImplicitlyWait(TimeSpan timeToWait) { int timeInMilliseconds = Convert.ToInt32(timeToWait.TotalMilliseconds); WebDriverResult result = NativeDriverLibrary.Instance.SetImplicitWaitTimeout(driver.handle, timeInMilliseconds); return this; } #endregion } #endregion } #endregion #region ITargetLocator class /// <summary> /// Provides a mechanism for finding elements on the page with locators. /// </summary> private class InternetExplorerTargetLocator : ITargetLocator { private InternetExplorerDriver driver; /// <summary> /// Initializes a new instance of the InternetExplorerTargetLocator class. /// </summary> /// <param name="driver">The driver that is currently in use.</param> public InternetExplorerTargetLocator(InternetExplorerDriver driver) { this.driver = driver; } /// <summary> /// Move to a different frame using its index. Indexes are Zero based and their may be issues if a /// frame is named as an integer. /// </summary> /// <param name="frameIndex">The index of the frame.</param> /// <returns>A WebDriver instance that is currently in use.</returns> public IWebDriver Frame(int frameIndex) { return Frame(frameIndex.ToString(CultureInfo.InvariantCulture)); } /// <summary> /// Move to different frame using its name. /// </summary> /// <param name="frameName">name of the frame.</param> /// <returns>A WebDriver instance that is currently in use.</returns> public IWebDriver Frame(string frameName) { if (frameName == null) { /* TODO(andre.nogueira): At least the IE driver crashes when * a null is received. I'd much rather move this to the driver itself. * In Java this is not a problem because of "new WString" which does this check for us. */ throw new ArgumentNullException("frameName", "Frame name cannot be null"); } WebDriverResult res = NativeDriverLibrary.Instance.SwitchToFrame(driver.handle, frameName); ResultHandler.VerifyResultCode(res, "switch to frame " + frameName); ////TODO(andre.nogueira): If this fails, driver cannot be used and has to be ////set to a valid frame... What's the best way of doing this? return driver; } /// <summary> /// Move to a frame element. /// </summary> /// <param name="frameElement">a previously found FRAME or IFRAME element.</param> /// <returns>A WebDriver instance that is currently in use.</returns> public IWebDriver Frame(IWebElement frameElement) { throw new InvalidOperationException("Not yet implemented for the IE driver"); } /// <summary> /// Change to the Window by passing in the name. /// </summary> /// <param name="windowName">name of the window that you wish to move to.</param> /// <returns>A WebDriver instance that is currently in use.</returns> public IWebDriver Window(string windowName) { WebDriverResult result = NativeDriverLibrary.Instance.SwitchToWindow(driver.handle, windowName); ResultHandler.VerifyResultCode(result, "Could not switch to window " + windowName); return driver; } /// <summary> /// Move the driver back to the default. /// </summary> /// <returns>Empty frame to the driver.</returns> public IWebDriver DefaultContent() { return Frame(string.Empty); } /// <summary> /// Finds the currently active element. /// </summary> /// <returns>WebElement of the active element.</returns> public IWebElement ActiveElement() { SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle(); WebDriverResult result = NativeDriverLibrary.Instance.SwitchToActiveElement(driver.handle, ref rawElement); ResultHandler.VerifyResultCode(result, "Unable to find active element"); return new InternetExplorerWebElement(driver, rawElement); } } #endregion #region INavigation class /// <summary> /// Provides a mechanism for Navigating with the driver. /// </summary> private class InternetExplorerNavigation : INavigation { private InternetExplorerDriver driver; /// <summary> /// Initializes a new instance of the InternetExplorerNavigation class. /// </summary> /// <param name="driver">Driver in use</param> public InternetExplorerNavigation(InternetExplorerDriver driver) { this.driver = driver; } /// <summary> /// Move the browser back. /// </summary> public void Back() { WebDriverResult result = NativeDriverLibrary.Instance.GoBack(driver.handle); ResultHandler.VerifyResultCode(result, "Going back in history"); } /// <summary> /// Move the browser forward. /// </summary> public void Forward() { WebDriverResult result = NativeDriverLibrary.Instance.GoForward(driver.handle); ResultHandler.VerifyResultCode(result, "Going forward in history"); } /// <summary> /// Navigate to a url for your test. /// </summary> /// <param name="url">Uri object of where you want the browser to go to.</param> public void GoToUrl(Uri url) { if (url == null) { throw new ArgumentNullException("url", "URL cannot be null."); } string address = url.AbsoluteUri; driver.Url = address; } /// <summary> /// Navigate to a url for your test. /// </summary> /// <param name="url">string of the URL you want the browser to go to.</param> public void GoToUrl(string url) { driver.Url = url; } /// <summary> /// Refresh the browser. /// </summary> public void Refresh() { WebDriverResult result = NativeDriverLibrary.Instance.Refresh(driver.handle); ResultHandler.VerifyResultCode(result, "Refreshing page"); } } #endregion #region Private support classes /// <summary> /// Provides a Null Path Cookie. /// </summary> private class NullPathCookie : Cookie { private string cookiePath; /// <summary> /// Initializes a new instance of the NullPathCookie class. /// </summary> /// <param name="name">name of the cookie.</param> /// <param name="value">value of the cookie.</param> /// <param name="domain">domain of the cookie.</param> /// <param name="path">path of the cookie.</param> /// <param name="expiry">date when the cookie expires, can be null.</param> public NullPathCookie(string name, string value, string domain, string path, DateTime? expiry) : base(name, value, domain, path, expiry) { this.cookiePath = path; } /// <summary> /// Gets the value of the path from the cookie. /// </summary> public override string Path { get { return cookiePath; } } } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Utilities; using System; using TMPro; using UnityEngine; using UnityEngine.UI; namespace Microsoft.MixedReality.Toolkit.Experimental.UI { /// <summary> /// A simple general use keyboard that is ideal for AR/VR applications that do not provide a native keyboard. /// </summary> /// /// NOTE: This keyboard will not automatically appear when you select an InputField in your /// Canvas. In order for the keyboard to appear you must call Keyboard.Instance.PresentKeyboard(string). /// To retrieve the input from the Keyboard, subscribe to the textEntered event. Note that /// tapping 'Close' on the Keyboard will not fire the textEntered event. You must tap 'Enter' to /// get the textEntered event. public class NonNativeKeyboard : InputSystemGlobalHandlerListener, IMixedRealityDictationHandler { public static NonNativeKeyboard Instance { get; private set; } /// <summary> /// Layout type enum for the type of keyboard layout to use. /// This is used when spawning to enable the correct keys based on layout type. /// </summary> public enum LayoutType { Alpha, Symbol, URL, Email, } #region Callbacks /// <summary> /// Sent when the 'Enter' button is pressed. To retrieve the text from the event, /// cast the sender to 'Keyboard' and get the text from the TextInput field. /// (Cleared when keyboard is closed.) /// </summary> public event EventHandler OnTextSubmitted = delegate { }; /// <summary> /// Fired every time the text in the InputField changes. /// (Cleared when keyboard is closed.) /// </summary> public event Action<string> OnTextUpdated = delegate { }; /// <summary> /// Fired every time the close button is pressed. /// (Cleared when keyboard is closed.) /// </summary> public event EventHandler OnClosed = delegate { }; /// <summary> /// Sent when the 'Previous' button is pressed. Ideally you would use this event /// to set your targeted text input to the previous text field in your document. /// (Cleared when keyboard is closed.) /// </summary> public event EventHandler OnPrevious = delegate { }; /// <summary> /// Sent when the 'Next' button is pressed. Ideally you would use this event /// to set your targeted text input to the next text field in your document. /// (Cleared when keyboard is closed.) /// </summary> public event EventHandler OnNext = delegate { }; /// <summary> /// Sent when the keyboard is placed. This allows listener to know when someone else is co-opting the keyboard. /// </summary> public event EventHandler OnPlacement = delegate { }; #endregion Callbacks /// <summary> /// The InputField that the keyboard uses to show the currently edited text. /// If you are using the Keyboard prefab you can ignore this field as it will /// be already assigned. /// </summary> [Experimental] public TMP_InputField InputField = null; /// <summary> /// Move the axis slider based on the camera forward and the keyboard plane projection. /// </summary> public AxisSlider InputFieldSlide = null; /// <summary> /// Bool for toggling the slider being enabled. /// </summary> public bool SliderEnabled = true; /// <summary> /// Bool to flag submitting on enter /// </summary> public bool SubmitOnEnter = true; /// <summary> /// The panel that contains the alpha keys. /// </summary> public Image AlphaKeyboard = null; /// <summary> /// The panel that contains the number and symbol keys. /// </summary> public Image SymbolKeyboard = null; /// <summary> /// References abc bottom panel. /// </summary> public Image AlphaSubKeys = null; /// <summary> /// References .com bottom panel. /// </summary> public Image AlphaWebKeys = null; /// <summary> /// References @ bottom panel. /// </summary> public Image AlphaMailKeys = null; private LayoutType m_LastKeyboardLayout = LayoutType.Alpha; /// <summary> /// The scale the keyboard should be at its maximum distance. /// </summary> [Header("Positioning")] [SerializeField] private float m_MaxScale = 1.0f; /// <summary> /// The scale the keyboard should be at its minimum distance. /// </summary> [SerializeField] private float m_MinScale = 1.0f; /// <summary> /// The maximum distance the keyboard should be from the user. /// </summary> [SerializeField] private float m_MaxDistance = 3.5f; /// <summary> /// The minimum distance the keyboard needs to be away from the user. /// </summary> [SerializeField] private float m_MinDistance = 0.25f; /// <summary> /// Make the keyboard disappear automatically after a timeout /// </summary> public bool CloseOnInactivity = true; /// <summary> /// Inactivity time that makes the keyboard disappear automatically. /// </summary> public float CloseOnInactivityTime = 15; /// <summary> /// Time on which the keyboard should close on inactivity /// </summary> private float _closingTime; /// <summary> /// Event fired when shift key on keyboard is pressed. /// </summary> public event Action<bool> OnKeyboardShifted = delegate { }; /// <summary> /// Event fired when char key on keyboard is pressed. /// </summary> public event Action<KeyboardValueKey> OnKeyboardValueKeyPressed = delegate { }; /// <summary> /// Event fired when function key on keyboard is pressed. /// Fires before internal keyboard state is updated. /// </summary> public event Action<KeyboardKeyFunc> OnKeyboardFunctionKeyPressed = delegate { }; /// <summary> /// Current shift state of keyboard. /// </summary> private bool m_IsShifted = false; /// <summary> /// Current caps lock state of keyboard. /// </summary> private bool m_IsCapslocked = false; /// <summary> /// Accessor reporting shift state of keyboard. /// </summary> public bool IsShifted { get { return m_IsShifted; } } /// <summary> /// Accessor reporting caps lock state of keyboard. /// </summary> public bool IsCapsLocked { get { return m_IsCapslocked; } } /// <summary> /// The position of the caret in the text field. /// </summary> private int m_CaretPosition = 0; /// <summary> /// The starting scale of the keyboard. /// </summary> private Vector3 m_StartingScale = Vector3.one; /// <summary> /// The default bounds of the keyboard. /// </summary> private Vector3 m_ObjectBounds; /// <summary> /// The default color of the mike key. /// </summary> private Color _defaultColor; /// <summary> /// The image on the mike key. /// </summary> private Image _recordImage; /// <summary> /// User can add an audio source to the keyboard to have a click be heard on tapping a key /// </summary> private AudioSource _audioSource; /// <summary> /// Dictation System /// </summary> private IMixedRealityDictationSystem dictationSystem; /// <summary> /// Deactivate on Awake. /// </summary> void Awake() { Instance = this; m_StartingScale = transform.localScale; Bounds canvasBounds = RectTransformUtility.CalculateRelativeRectTransformBounds(transform); RectTransform rect = GetComponent<RectTransform>(); m_ObjectBounds = new Vector3(canvasBounds.size.x * rect.localScale.x, canvasBounds.size.y * rect.localScale.y, canvasBounds.size.z * rect.localScale.z); // Actually find microphone key in the keyboard var dictationButton = TransformExtensions.GetChildRecursive(gameObject.transform, "Dictation"); if (dictationButton != null) { var dictationIcon = dictationButton.Find("keyboard_closeIcon"); if (dictationIcon != null) { _recordImage = dictationIcon.GetComponentInChildren<Image>(); var material = new Material(_recordImage.material); _defaultColor = material.color; _recordImage.material = material; } } // Setting the keyboardType to an undefined TouchScreenKeyboardType, // which prevents the MRTK keyboard from triggering the system keyboard itself. InputField.keyboardType = (TouchScreenKeyboardType)(int.MaxValue); // Keep keyboard deactivated until needed gameObject.SetActive(false); } /// <summary> /// Set up Dictation, CanvasEX, and automatically select the TextInput object. /// </summary> protected override void Start() { base.Start(); dictationSystem = CoreServices.GetInputSystemDataProvider<IMixedRealityDictationSystem>(); // Delegate Subscription InputField.onValueChanged.AddListener(DoTextUpdated); } protected override void RegisterHandlers() { CoreServices.InputSystem?.RegisterHandler<IMixedRealityDictationHandler>(this); } protected override void UnregisterHandlers() { CoreServices.InputSystem?.UnregisterHandler<IMixedRealityDictationHandler>(this); } /// <summary> /// Intermediary function for text update events. /// Workaround for strange leftover reference when unsubscribing. /// </summary> /// <param name="value">String value.</param> private void DoTextUpdated(string value) => OnTextUpdated?.Invoke(value); /// <summary> /// Makes sure the input field is always selected while the keyboard is up. /// </summary> private void LateUpdate() { // Axis Slider if (SliderEnabled) { Vector3 nearPoint = Vector3.ProjectOnPlane(CameraCache.Main.transform.forward, transform.forward); Vector3 relPos = transform.InverseTransformPoint(nearPoint); InputFieldSlide.TargetPoint = relPos; } CheckForCloseOnInactivityTimeExpired(); } private void UpdateCaretPosition(int newPos) => InputField.caretPosition = newPos; /// <summary> /// Called whenever the keyboard is disabled or deactivated. /// </summary> protected override void OnDisable() { base.OnDisable(); m_LastKeyboardLayout = LayoutType.Alpha; Clear(); } /// <summary> /// Called when dictation hypothesis is found. Not used here /// </summary> /// <param name="eventData">Dictation event data</param> public void OnDictationHypothesis(DictationEventData eventData) { } /// <summary> /// Called when dictation result is obtained /// </summary> /// <param name="eventData">Dictation event data</param> public void OnDictationResult(DictationEventData eventData) { if (eventData.used) { return; } var text = eventData.DictationResult; ResetClosingTime(); if (text != null) { m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition, text); m_CaretPosition += text.Length; UpdateCaretPosition(m_CaretPosition); eventData.Use(); } } /// <summary> /// Called when dictation is completed /// </summary> /// <param name="eventData">Dictation event data</param> public void OnDictationComplete(DictationEventData eventData) { ResetClosingTime(); SetMicrophoneDefault(); } /// <summary> /// Called on dictation error. Not used here. /// </summary> /// <param name="eventData">Dictation event data</param> public void OnDictationError(DictationEventData eventData) { } /// <summary> /// Destroy unmanaged memory links. /// </summary> void OnDestroy() { if (dictationSystem != null && IsMicrophoneActive()) { dictationSystem.StopRecording(); } Instance = null; } #region Present Functions /// <summary> /// Present the default keyboard to the camera. /// </summary> public void PresentKeyboard() { ResetClosingTime(); gameObject.SetActive(true); ActivateSpecificKeyboard(LayoutType.Alpha); OnPlacement(this, EventArgs.Empty); // todo: if the app is built for xaml, our prefab and the system keyboard may be displayed. InputField.ActivateInputField(); SetMicrophoneDefault(); } /// <summary> /// Presents the default keyboard to the camera, with start text. /// </summary> /// <param name="startText">The initial text to show in the keyboard's input field.</param> public void PresentKeyboard(string startText) { PresentKeyboard(); Clear(); InputField.text = startText; } /// <summary> /// Presents a specific keyboard to the camera. /// </summary> /// <param name="keyboardType">Specify the keyboard type.</param> public void PresentKeyboard(LayoutType keyboardType) { PresentKeyboard(); ActivateSpecificKeyboard(keyboardType); } /// <summary> /// Presents a specific keyboard to the camera, with start text. /// </summary> /// <param name="startText">The initial text to show in the keyboard's input field.</param> /// <param name="keyboardType">Specify the keyboard type.</param> public void PresentKeyboard(string startText, LayoutType keyboardType) { PresentKeyboard(startText); ActivateSpecificKeyboard(keyboardType); } #endregion Present Functions /// <summary> /// Function to reposition the Keyboard based on target position and vertical offset /// </summary> /// <param name="kbPos">World position for keyboard</param> /// <param name="verticalOffset">Optional vertical offset of keyboard</param> public void RepositionKeyboard(Vector3 kbPos, float verticalOffset = 0.0f) { transform.position = kbPos; ScaleToSize(); LookAtTargetOrigin(); } /// <summary> /// Function to reposition the keyboard based on target transform and collider information /// </summary> /// <param name="objectTransform">Transform of target object to remain relative to</param> /// <param name="aCollider">Optional collider information for offset placement</param> /// <param name="verticalOffset">Optional vertical offset from the target</param> public void RepositionKeyboard(Transform objectTransform, BoxCollider aCollider = null, float verticalOffset = 0.0f) { transform.position = objectTransform.position; if (aCollider != null) { float yTranslation = -((aCollider.bounds.size.y * 0.5f) + verticalOffset); transform.Translate(0.0f, yTranslation, -0.6f, objectTransform); } else { float yTranslation = -((m_ObjectBounds.y * 0.5f) + verticalOffset); transform.Translate(0.0f, yTranslation, -0.6f, objectTransform); } ScaleToSize(); LookAtTargetOrigin(); } /// <summary> /// Function to scale keyboard to the appropriate size based on distance /// </summary> private void ScaleToSize() { float distance = (transform.position - CameraCache.Main.transform.position).magnitude; float distancePercent = (distance - m_MinDistance) / (m_MaxDistance - m_MinDistance); float scale = m_MinScale + (m_MaxScale - m_MinScale) * distancePercent; scale = Mathf.Clamp(scale, m_MinScale, m_MaxScale); transform.localScale = m_StartingScale * scale; Debug.LogFormat("Setting scale: {0} for distance: {1}", scale, distance); } /// <summary> /// Look at function to have the keyboard face the user /// </summary> private void LookAtTargetOrigin() { transform.LookAt(CameraCache.Main.transform.position); transform.Rotate(Vector3.up, 180.0f); } /// <summary> /// Activates a specific keyboard layout, and any sub keys. /// </summary> /// <param name="keyboardType">The keyboard layout type that should be activated</param> private void ActivateSpecificKeyboard(LayoutType keyboardType) { DisableAllKeyboards(); ResetKeyboardState(); switch (keyboardType) { case LayoutType.URL: { ShowAlphaKeyboard(); TryToShowURLSubkeys(); break; } case LayoutType.Email: { ShowAlphaKeyboard(); TryToShowEmailSubkeys(); break; } case LayoutType.Symbol: { ShowSymbolKeyboard(); break; } case LayoutType.Alpha: default: { ShowAlphaKeyboard(); TryToShowAlphaSubkeys(); break; } } } #region Keyboard Functions #region Dictation /// <summary> /// Initialize dictation mode. /// </summary> private void BeginDictation() { ResetClosingTime(); dictationSystem.StartRecording(gameObject); SetMicrophoneRecording(); } private bool IsMicrophoneActive() { var result = _recordImage.color != _defaultColor; return result; } /// <summary> /// Set mike default look /// </summary> private void SetMicrophoneDefault() { _recordImage.color = _defaultColor; } /// <summary> /// Set mike recording look (red) /// </summary> private void SetMicrophoneRecording() { _recordImage.color = Color.red; } /// <summary> /// Terminate dictation mode. /// </summary> public void EndDictation() { dictationSystem.StopRecording(); SetMicrophoneDefault(); } #endregion Dictation /// <summary> /// Primary method for typing individual characters to a text field. /// </summary> /// <param name="valueKey">The valueKey of the pressed key.</param> public void AppendValue(KeyboardValueKey valueKey) { IndicateActivity(); string value = ""; OnKeyboardValueKeyPressed(valueKey); // Shift value should only be applied if a shift value is present. if (m_IsShifted && !string.IsNullOrEmpty(valueKey.ShiftValue)) { value = valueKey.ShiftValue; } else { value = valueKey.Value; } if (!m_IsCapslocked) { Shift(false); } m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition, value); m_CaretPosition += value.Length; UpdateCaretPosition(m_CaretPosition); } /// <summary> /// Trigger specific keyboard functionality. /// </summary> /// <param name="functionKey">The functionKey of the pressed key.</param> public void FunctionKey(KeyboardKeyFunc functionKey) { IndicateActivity(); OnKeyboardFunctionKeyPressed(functionKey); switch (functionKey.ButtonFunction) { case KeyboardKeyFunc.Function.Enter: { Enter(); break; } case KeyboardKeyFunc.Function.Tab: { Tab(); break; } case KeyboardKeyFunc.Function.ABC: { ActivateSpecificKeyboard(m_LastKeyboardLayout); break; } case KeyboardKeyFunc.Function.Symbol: { ActivateSpecificKeyboard(LayoutType.Symbol); break; } case KeyboardKeyFunc.Function.Previous: { MoveCaretLeft(); break; } case KeyboardKeyFunc.Function.Next: { MoveCaretRight(); break; } case KeyboardKeyFunc.Function.Close: { Close(); break; } case KeyboardKeyFunc.Function.Dictate: { if (dictationSystem == null) { break; } if (IsMicrophoneActive()) { EndDictation(); } else { BeginDictation(); } break; } case KeyboardKeyFunc.Function.Shift: { Shift(!m_IsShifted); break; } case KeyboardKeyFunc.Function.CapsLock: { CapsLock(!m_IsCapslocked); break; } case KeyboardKeyFunc.Function.Space: { Space(); break; } case KeyboardKeyFunc.Function.Backspace: { Backspace(); break; } case KeyboardKeyFunc.Function.UNDEFINED: { Debug.LogErrorFormat("The {0} key on this keyboard hasn't been assigned a function.", functionKey.name); break; } default: throw new ArgumentOutOfRangeException(); } } /// <summary> /// Delete the character before the caret. /// </summary> public void Backspace() { // check if text is selected if (InputField.selectionFocusPosition != InputField.caretPosition || InputField.selectionAnchorPosition != InputField.caretPosition) { if (InputField.selectionAnchorPosition > InputField.selectionFocusPosition) // right to left { InputField.text = InputField.text.Substring(0, InputField.selectionFocusPosition) + InputField.text.Substring(InputField.selectionAnchorPosition); InputField.caretPosition = InputField.selectionFocusPosition; } else // left to right { InputField.text = InputField.text.Substring(0, InputField.selectionAnchorPosition) + InputField.text.Substring(InputField.selectionFocusPosition); InputField.caretPosition = InputField.selectionAnchorPosition; } m_CaretPosition = InputField.caretPosition; InputField.selectionAnchorPosition = m_CaretPosition; InputField.selectionFocusPosition = m_CaretPosition; } else { m_CaretPosition = InputField.caretPosition; if (m_CaretPosition > 0) { --m_CaretPosition; InputField.text = InputField.text.Remove(m_CaretPosition, 1); UpdateCaretPosition(m_CaretPosition); } } } /// <summary> /// Send the "previous" event. /// </summary> public void Previous() { OnPrevious(this, EventArgs.Empty); } /// <summary> /// Send the "next" event. /// </summary> public void Next() { OnNext(this, EventArgs.Empty); } /// <summary> /// Fire the text entered event for objects listening to keyboard. /// Immediately closes keyboard. /// </summary> public void Enter() { if (SubmitOnEnter) { // Send text entered event and close the keyboard OnTextSubmitted?.Invoke(this, EventArgs.Empty); Close(); } else { string enterString = "\n"; m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition, enterString); m_CaretPosition += enterString.Length; UpdateCaretPosition(m_CaretPosition); } } /// <summary> /// Set the keyboard to a single action shift state. /// </summary> /// <param name="newShiftState">value the shift key should have after calling the method</param> public void Shift(bool newShiftState) { m_IsShifted = newShiftState; OnKeyboardShifted(m_IsShifted); if (m_IsCapslocked && !newShiftState) { m_IsCapslocked = false; } } /// <summary> /// Set the keyboard to a permanent shift state. /// </summary> /// <param name="newCapsLockState">Caps lock state the method is switching to</param> public void CapsLock(bool newCapsLockState) { m_IsCapslocked = newCapsLockState; Shift(newCapsLockState); } /// <summary> /// Insert a space character. /// </summary> public void Space() { m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition++, " "); UpdateCaretPosition(m_CaretPosition); } /// <summary> /// Insert a tab character. /// </summary> public void Tab() { string tabString = "\t"; m_CaretPosition = InputField.caretPosition; InputField.text = InputField.text.Insert(m_CaretPosition, tabString); m_CaretPosition += tabString.Length; UpdateCaretPosition(m_CaretPosition); } /// <summary> /// Move caret to the left. /// </summary> public void MoveCaretLeft() { m_CaretPosition = InputField.caretPosition; if (m_CaretPosition > 0) { --m_CaretPosition; UpdateCaretPosition(m_CaretPosition); } } /// <summary> /// Move caret to the right. /// </summary> public void MoveCaretRight() { m_CaretPosition = InputField.caretPosition; if (m_CaretPosition < InputField.text.Length) { ++m_CaretPosition; UpdateCaretPosition(m_CaretPosition); } } /// <summary> /// Close the keyboard. /// (Clears all event subscriptions.) /// </summary> public void Close() { if (IsMicrophoneActive()) { dictationSystem.StopRecording(); } SetMicrophoneDefault(); OnClosed(this, EventArgs.Empty); gameObject.SetActive(false); } /// <summary> /// Clear the text input field. /// </summary> public void Clear() { ResetKeyboardState(); if (InputField.caretPosition != 0) { InputField.MoveTextStart(false); } InputField.text = ""; m_CaretPosition = InputField.caretPosition; } #endregion /// <summary> /// Method to set the sizes by code, as the properties are private. /// Useful for scaling 'from the outside', for instance taking care of differences between /// immersive headsets and HoloLens /// </summary> /// <param name="minScale">Min scale factor</param> /// <param name="maxScale">Max scale factor</param> /// <param name="minDistance">Min distance from camera</param> /// <param name="maxDistance">Max distance from camera</param> public void SetScaleSizeValues(float minScale, float maxScale, float minDistance, float maxDistance) { m_MinScale = minScale; m_MaxScale = maxScale; m_MinDistance = minDistance; m_MaxDistance = maxDistance; } #region Keyboard Layout Modes /// <summary> /// Enable the alpha keyboard. /// </summary> public void ShowAlphaKeyboard() { AlphaKeyboard.gameObject.SetActive(true); m_LastKeyboardLayout = LayoutType.Alpha; } /// <summary> /// Show the default subkeys only on the Alphanumeric keyboard. /// </summary> /// <returns>Returns true if default subkeys were activated, false if alphanumeric keyboard isn't active</returns> private bool TryToShowAlphaSubkeys() { if (AlphaKeyboard.IsActive()) { AlphaSubKeys.gameObject.SetActive(true); return true; } else { return false; } } /// <summary> /// Show the email subkeys only on the Alphanumeric keyboard. /// </summary> /// <returns>Returns true if the email subkey was activated, false if alphanumeric keyboard is not active and key can't be activated</returns> private bool TryToShowEmailSubkeys() { if (AlphaKeyboard.IsActive()) { AlphaMailKeys.gameObject.SetActive(true); m_LastKeyboardLayout = LayoutType.Email; return true; } else { return false; } } /// <summary> /// Show the URL subkeys only on the Alphanumeric keyboard. /// </summary> /// <returns>Returns true if the URL subkey was activated, false if alphanumeric keyboard is not active and key can't be activated</returns> private bool TryToShowURLSubkeys() { if (AlphaKeyboard.IsActive()) { AlphaWebKeys.gameObject.SetActive(true); m_LastKeyboardLayout = LayoutType.URL; return true; } else { return false; } } /// <summary> /// Enable the symbol keyboard. /// </summary> public void ShowSymbolKeyboard() { SymbolKeyboard.gameObject.SetActive(true); } /// <summary> /// Disable GameObjects for all keyboard elements. /// </summary> private void DisableAllKeyboards() { AlphaKeyboard.gameObject.SetActive(false); SymbolKeyboard.gameObject.SetActive(false); AlphaWebKeys.gameObject.SetActive(false); AlphaMailKeys.gameObject.SetActive(false); AlphaSubKeys.gameObject.SetActive(false); } /// <summary> /// Reset temporary states of keyboard. /// </summary> private void ResetKeyboardState() { CapsLock(false); } #endregion Keyboard Layout Modes /// <summary> /// Respond to keyboard activity: reset timeout timer, play sound /// </summary> private void IndicateActivity() { ResetClosingTime(); if (_audioSource == null) { _audioSource = GetComponent<AudioSource>(); } if (_audioSource != null) { _audioSource.Play(); } } /// <summary> /// Reset inactivity closing timer /// </summary> private void ResetClosingTime() { if (CloseOnInactivity) { _closingTime = Time.time + CloseOnInactivityTime; } } /// <summary> /// Check if the keyboard has been left alone for too long and close /// </summary> private void CheckForCloseOnInactivityTimeExpired() { if (Time.time > _closingTime && CloseOnInactivity) { Close(); } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type PlannerProgressTaskBoardTaskFormatRequest. /// </summary> public partial class PlannerProgressTaskBoardTaskFormatRequest : BaseRequest, IPlannerProgressTaskBoardTaskFormatRequest { /// <summary> /// Constructs a new PlannerProgressTaskBoardTaskFormatRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public PlannerProgressTaskBoardTaskFormatRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified PlannerProgressTaskBoardTaskFormat using POST. /// </summary> /// <param name="plannerProgressTaskBoardTaskFormatToCreate">The PlannerProgressTaskBoardTaskFormat to create.</param> /// <returns>The created PlannerProgressTaskBoardTaskFormat.</returns> public System.Threading.Tasks.Task<PlannerProgressTaskBoardTaskFormat> CreateAsync(PlannerProgressTaskBoardTaskFormat plannerProgressTaskBoardTaskFormatToCreate) { return this.CreateAsync(plannerProgressTaskBoardTaskFormatToCreate, CancellationToken.None); } /// <summary> /// Creates the specified PlannerProgressTaskBoardTaskFormat using POST. /// </summary> /// <param name="plannerProgressTaskBoardTaskFormatToCreate">The PlannerProgressTaskBoardTaskFormat to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created PlannerProgressTaskBoardTaskFormat.</returns> public async System.Threading.Tasks.Task<PlannerProgressTaskBoardTaskFormat> CreateAsync(PlannerProgressTaskBoardTaskFormat plannerProgressTaskBoardTaskFormatToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<PlannerProgressTaskBoardTaskFormat>(plannerProgressTaskBoardTaskFormatToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified PlannerProgressTaskBoardTaskFormat. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified PlannerProgressTaskBoardTaskFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<PlannerProgressTaskBoardTaskFormat>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified PlannerProgressTaskBoardTaskFormat. /// </summary> /// <returns>The PlannerProgressTaskBoardTaskFormat.</returns> public System.Threading.Tasks.Task<PlannerProgressTaskBoardTaskFormat> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified PlannerProgressTaskBoardTaskFormat. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The PlannerProgressTaskBoardTaskFormat.</returns> public async System.Threading.Tasks.Task<PlannerProgressTaskBoardTaskFormat> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<PlannerProgressTaskBoardTaskFormat>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified PlannerProgressTaskBoardTaskFormat using PATCH. /// </summary> /// <param name="plannerProgressTaskBoardTaskFormatToUpdate">The PlannerProgressTaskBoardTaskFormat to update.</param> /// <returns>The updated PlannerProgressTaskBoardTaskFormat.</returns> public System.Threading.Tasks.Task<PlannerProgressTaskBoardTaskFormat> UpdateAsync(PlannerProgressTaskBoardTaskFormat plannerProgressTaskBoardTaskFormatToUpdate) { return this.UpdateAsync(plannerProgressTaskBoardTaskFormatToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified PlannerProgressTaskBoardTaskFormat using PATCH. /// </summary> /// <param name="plannerProgressTaskBoardTaskFormatToUpdate">The PlannerProgressTaskBoardTaskFormat to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated PlannerProgressTaskBoardTaskFormat.</returns> public async System.Threading.Tasks.Task<PlannerProgressTaskBoardTaskFormat> UpdateAsync(PlannerProgressTaskBoardTaskFormat plannerProgressTaskBoardTaskFormatToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<PlannerProgressTaskBoardTaskFormat>(plannerProgressTaskBoardTaskFormatToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IPlannerProgressTaskBoardTaskFormatRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IPlannerProgressTaskBoardTaskFormatRequest Expand(Expression<Func<PlannerProgressTaskBoardTaskFormat, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IPlannerProgressTaskBoardTaskFormatRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IPlannerProgressTaskBoardTaskFormatRequest Select(Expression<Func<PlannerProgressTaskBoardTaskFormat, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="plannerProgressTaskBoardTaskFormatToInitialize">The <see cref="PlannerProgressTaskBoardTaskFormat"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(PlannerProgressTaskBoardTaskFormat plannerProgressTaskBoardTaskFormatToInitialize) { } } }
// --------------------------------------------------------------------------- // <copyright file="CenteredMessageBox.cs" company="Tethys"> // Copyright (C) 1998-2021 T. Graf // </copyright> // // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 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. // --------------------------------------------------------------------------- // ReSharper disable once CheckNamespace namespace Tethys.Forms { using System; using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; using Tethys.Win32; /// <summary> /// CenteredMessageBox implements a message box that is always centered over /// the parent window like the normal Win32 MessageBox. /// </summary> public static class CenteredMessageBox { #region SHOW() FUNCTIONS /// <summary> /// Displays a message box with specified text. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text) { Init(string.Empty, owner); return MessageBox.Show(owner, text); } // Show() /// <summary> /// Displays a message box with specified text and caption. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the /// message box. </param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption) { Init(caption, owner); return MessageBox.Show(owner, text, caption); } // Show() /// <summary> /// Displays a message box with specified text, caption, and buttons. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the /// message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies /// which buttons to display in the message box.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { Init(caption, owner); return MessageBox.Show(owner, text, caption, buttons); } // Show() /// <summary> /// Displays a message box with specified text, caption, buttons, and /// icon. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the /// message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies /// which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies /// which icon to display in the message box. </param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { Init(caption, owner); return MessageBox.Show(owner, text, caption, buttons, icon); } // Show() /// <summary> /// Displays a message box with the specified text, caption, buttons, /// icon, and default button. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the /// message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies /// which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies /// which icon to display in the message box.</param> /// <param name="defButton">One for the MessageBoxDefaultButton values /// which specifies which is the default button for the message box. /// </param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton) { Init(caption, owner); return MessageBox.Show(owner, text, caption, buttons, icon, defButton); } // Show() /// <summary> /// Displays a message box with the specified text, caption, buttons, /// icon, and default button. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the /// message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies /// which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies /// which icon to display in the message box.</param> /// <param name="defButton">One for the MessageBoxDefaultButton values /// which specifies which is the default button for the message box. /// </param> /// <param name="options">Message box Options.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options) { Init(caption, owner); return MessageBox.Show(owner, text, caption, buttons, icon, defButton, options); } // Show() #endregion // SHOW() FUNCTIONS //// -------------------------------------------------------------------- #region PRIVATE PROPERTIES /// <summary> /// The hook. /// </summary> private static readonly Win32Api.HookProc HookProc = MessageBoxHookProc; /// <summary> /// Hook caption. /// </summary> private static string hookCaption = string.Empty; /// <summary> /// Hook handle. /// </summary> private static IntPtr handleHook = IntPtr.Zero; /// <summary> /// Parent window. /// </summary> private static IWin32Window parent; #endregion // PRIVATE PROPERTIES //// -------------------------------------------------------------------- #region CONTRUCTION /// <summary> /// Initialize hook management. /// </summary> /// <param name="caption">The caption.</param> /// <param name="owner">The owner.</param> /// <exception cref="System.NotSupportedException">multiple /// calls are not supported.</exception> private static void Init(string caption, IWin32Window owner) { if (handleHook != IntPtr.Zero) { // prohibit reentrancy throw new NotSupportedException( "multiple calls are not supported"); } // if // store parent (owner) parent = owner; // create hook hookCaption = caption ?? string.Empty; handleHook = Win32Api.SetWindowsHookEx( (int)WindowsHookCodes.WH_CALLWNDPROCRET, HookProc, IntPtr.Zero, Thread.CurrentThread.ManagedThreadId); } // Init() #endregion // CONTRUCTION //// -------------------------------------------------------------------- #region HOOK /// <summary> /// This is the function called by the Windows hook management. /// We assume, that when an WM_INITDIALOG message is sent and /// the window text is the same like the one of our window that /// the window to hook call comes from is indeed our window. /// We start the timer and unhook ourselves. /// </summary> /// <param name="code">The code.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns>The handle.</returns> private static IntPtr MessageBoxHookProc(int code, IntPtr wParam, IntPtr lParam) { if (code < 0) { return Win32Api.CallNextHookEx(handleHook, code, wParam, lParam); } // if var msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT)); var hook = handleHook; if ((hookCaption != null) && (msg.message == (uint)Msg.WM_INITDIALOG)) { // get window text var length = Win32Api.GetWindowTextLength(msg.hwnd); var text = new StringBuilder(length + 1); var result = Win32Api.GetWindowText(msg.hwnd, text, text.Capacity); Debug.Assert(result > 0, "GetWindowText reports error!"); // check whether this is the text we expect if (hookCaption == text.ToString()) { hookCaption = null; // get size of the parent window var rectParent = default(RECT); var rectClient = default(RECT); if (Win32Api.GetWindowRect(parent.Handle, ref rectParent)) { // calculate center point var centerParent = new Point( (rectParent.left + rectParent.right) / 2, (rectParent.top + rectParent.bottom) / 2); if (Win32Api.GetWindowRect(msg.hwnd, ref rectClient)) { var pt = new Point( centerParent.X - ((rectClient.right - rectClient.left) / 2), centerParent.Y - ((rectClient.bottom - rectClient.top) / 2)); if (pt.X < 0) { pt.X = 0; } // if if (pt.Y < 0) { pt.Y = 0; } // if // set new window position const uint Flags = (uint)SetWindowPosFlags.SWP_NOOWNERZORDER + (uint)SetWindowPosFlags.SWP_NOSIZE + (uint)SetWindowPosFlags.SWP_NOZORDER; Win32Api.SetWindowPos(msg.hwnd, IntPtr.Zero, pt.X, pt.Y, 0, 0, Flags); } // if } // if // unhook Win32Api.UnhookWindowsHookEx(handleHook); handleHook = IntPtr.Zero; } // if } // if // default: call next hook return Win32Api.CallNextHookEx(hook, code, wParam, lParam); } // MessageBoxHookProc() #endregion // HOOK } // CenteredMessageBox } // Tethys.Forms // ========================================== // Tethys.forms: end of centeredmessagebox.cs // ==========================================
/** * MetroFramework - Modern UI for WinForms * * The MIT License (MIT) * Copyright (c) 2011 Sven Walter, http://github.com/viperneo * * 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. */ // Based on original work by // (c) Mick Doherty / Oscar Londono // http://dotnetrix.co.uk/tabcontrol.htm // http://www.pcreview.co.uk/forums/adding-custom-tabpages-design-time-t2904262.html // http://www.codeproject.com/Articles/12185/A-NET-Flat-TabControl-CustomDraw // http://www.codeproject.com/Articles/278/Fully-owner-drawn-tab-control using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Design; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Windows.Forms; using MetroFramework.Components; using MetroFramework.Drawing; using MetroFramework.Interfaces; using MetroFramework.Native; namespace MetroFramework.Controls { #region MetroTabPageCollection [ToolboxItem(false)] [Editor("MetroFramework.Design.MetroTabPageCollectionEditor, " + AssemblyRef.MetroFrameworkDesignSN, typeof(UITypeEditor))] public class MetroTabPageCollection : TabControl.TabPageCollection { public MetroTabPageCollection(MetroTabControl owner) : base(owner) { } } #endregion [Designer("MetroFramework.Design.Controls.MetroTabControlDesigner, " + AssemblyRef.MetroFrameworkDesignSN)] [ToolboxBitmap(typeof(TabControl))] public class MetroTabControl : TabControl, IMetroControl { #region Interface [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaintBackground; protected virtual void OnCustomPaintBackground(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaintBackground != null) { CustomPaintBackground(this, e); } } [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaint; protected virtual void OnCustomPaint(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaint != null) { CustomPaint(this, e); } } [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaintForeground; protected virtual void OnCustomPaintForeground(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaintForeground != null) { CustomPaintForeground(this, e); } } private MetroColorStyle metroStyle = MetroColorStyle.Default; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroColorStyle.Default)] public MetroColorStyle Style { get { if (DesignMode || metroStyle != MetroColorStyle.Default) { return metroStyle; } if (StyleManager != null && metroStyle == MetroColorStyle.Default) { return StyleManager.Style; } if (StyleManager == null && metroStyle == MetroColorStyle.Default) { return MetroDefaults.Style; } return metroStyle; } set { metroStyle = value; } } private MetroThemeStyle metroTheme = MetroThemeStyle.Default; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroThemeStyle.Default)] public MetroThemeStyle Theme { get { if (DesignMode || metroTheme != MetroThemeStyle.Default) { return metroTheme; } if (StyleManager != null && metroTheme == MetroThemeStyle.Default) { return StyleManager.Theme; } if (StyleManager == null && metroTheme == MetroThemeStyle.Default) { return MetroDefaults.Theme; } return metroTheme; } set { metroTheme = value; } } private MetroStyleManager metroStyleManager = null; [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public MetroStyleManager StyleManager { get { return metroStyleManager; } set { metroStyleManager = value; } } private bool useCustomBackColor = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseCustomBackColor { get { return useCustomBackColor; } set { useCustomBackColor = value; } } private bool useCustomForeColor = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseCustomForeColor { get { return useCustomForeColor; } set { useCustomForeColor = value; } } private bool useStyleColors = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseStyleColors { get { return useStyleColors; } set { useStyleColors = value; } } [Browsable(false)] [Category(MetroDefaults.PropertyCategory.Behaviour)] [DefaultValue(false)] public bool UseSelectable { get { return GetStyle(ControlStyles.Selectable); } set { SetStyle(ControlStyles.Selectable, value); } } #endregion #region Fields private SubClass scUpDown = null; private bool bUpDown = false; private const int TabBottomBorderHeight = 3; private MetroTabControlSize metroLabelSize = MetroTabControlSize.Medium; [DefaultValue(MetroTabControlSize.Medium)] [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroTabControlSize FontSize { get { return metroLabelSize; } set { metroLabelSize = value; } } private MetroTabControlWeight metroLabelWeight = MetroTabControlWeight.Light; [DefaultValue(MetroTabControlWeight.Light)] [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroTabControlWeight FontWeight { get { return metroLabelWeight; } set { metroLabelWeight = value; } } private ContentAlignment textAlign = ContentAlignment.MiddleLeft; [DefaultValue(ContentAlignment.MiddleLeft)] [Category(MetroDefaults.PropertyCategory.Appearance)] public ContentAlignment TextAlign { get { return textAlign; } set { textAlign = value; } } [Editor("MetroFramework.Design.MetroTabPageCollectionEditor, " + AssemblyRef.MetroFrameworkDesignSN, typeof(UITypeEditor))] public new TabPageCollection TabPages { get { return base.TabPages; } } private bool isMirrored; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public new bool IsMirrored { get { return isMirrored; } set { if (isMirrored == value) { return; } isMirrored = value; UpdateStyles(); } } #endregion #region Constructor public MetroTabControl() { SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true); Padding = new Point(6, 8); } #endregion #region Paint Methods protected override void OnPaintBackground(PaintEventArgs e) { try { Color backColor = BackColor; if (!useCustomBackColor) { backColor = MetroPaint.BackColor.Form(Theme); } if (backColor.A == 255 && BackgroundImage == null) { e.Graphics.Clear(backColor); return; } base.OnPaintBackground(e); OnCustomPaintBackground(new MetroPaintEventArgs(backColor, Color.Empty, e.Graphics)); } catch { Invalidate(); } } protected override void OnPaint(PaintEventArgs e) { try { if (GetStyle(ControlStyles.AllPaintingInWmPaint)) { OnPaintBackground(e); } OnCustomPaint(new MetroPaintEventArgs(Color.Empty, Color.Empty, e.Graphics)); OnPaintForeground(e); } catch { Invalidate(); } } protected virtual void OnPaintForeground(PaintEventArgs e) { for (var index = 0; index < TabPages.Count; index++) { if (index != SelectedIndex) { DrawTab(index, e.Graphics); } } if (SelectedIndex <= -1) { return; } DrawTabBottomBorder(SelectedIndex, e.Graphics); DrawTab(SelectedIndex, e.Graphics); DrawTabSelected(SelectedIndex, e.Graphics); OnCustomPaintForeground(new MetroPaintEventArgs(Color.Empty, Color.Empty, e.Graphics)); } private void DrawTabBottomBorder(int index, Graphics graphics) { using (Brush bgBrush = new SolidBrush(MetroPaint.BorderColor.TabControl.Normal(Theme))) { Rectangle borderRectangle = new Rectangle(DisplayRectangle.X, GetTabRect(index).Bottom + 2 - TabBottomBorderHeight, DisplayRectangle.Width, TabBottomBorderHeight); graphics.FillRectangle(bgBrush, borderRectangle); } } private void DrawTabSelected(int index, Graphics graphics) { using (Brush selectionBrush = new SolidBrush(MetroPaint.GetStyleColor(Style))) { Rectangle selectedTabRect = GetTabRect(index); Rectangle borderRectangle = new Rectangle(selectedTabRect.X + ((index == 0) ? 2 : 0), GetTabRect(index).Bottom + 2 - TabBottomBorderHeight, selectedTabRect.Width + ((index == 0) ? 0 : 2), TabBottomBorderHeight); graphics.FillRectangle(selectionBrush, borderRectangle); } } private Size MeasureText(string text) { Size preferredSize; using (Graphics g = CreateGraphics()) { Size proposedSize = new Size(int.MaxValue, int.MaxValue); preferredSize = TextRenderer.MeasureText(g, text, MetroFonts.TabControl(metroLabelSize, metroLabelWeight), proposedSize, MetroPaint.GetTextFormatFlags(TextAlign) | TextFormatFlags.NoPadding); } return preferredSize; } private void DrawTab(int index, Graphics graphics) { Color foreColor; Color backColor = BackColor; if (!useCustomBackColor) { backColor = MetroPaint.BackColor.Form(Theme); } TabPage tabPage = TabPages[index]; Rectangle tabRect = GetTabRect(index); if (!Enabled) { foreColor = MetroPaint.ForeColor.Label.Disabled(Theme); } else { if (useCustomForeColor) { foreColor = DefaultForeColor; } else { foreColor = !useStyleColors ? MetroPaint.ForeColor.TabControl.Normal(Theme) : MetroPaint.GetStyleColor(Style); } } if (index == 0) { tabRect.X = DisplayRectangle.X; } Rectangle bgRect = tabRect; tabRect.Width += 20; using (Brush bgBrush = new SolidBrush(backColor)) { graphics.FillRectangle(bgBrush, bgRect); } TextRenderer.DrawText(graphics, tabPage.Text, MetroFonts.TabControl(metroLabelSize, metroLabelWeight), tabRect, foreColor, backColor, MetroPaint.GetTextFormatFlags(TextAlign)); } [SecuritySafeCritical] private void DrawUpDown(Graphics graphics) { Color backColor = Parent != null ? Parent.BackColor : MetroPaint.BackColor.Form(Theme); Rectangle borderRect = new Rectangle(); WinApi.GetClientRect(scUpDown.Handle, ref borderRect); graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.Clear(backColor); using (Brush b = new SolidBrush(MetroPaint.BorderColor.TabControl.Normal(Theme))) { GraphicsPath gp = new GraphicsPath(FillMode.Winding); PointF[] pts = { new PointF(6, 6), new PointF(16, 0), new PointF(16, 12) }; gp.AddLines(pts); graphics.FillPath(b, gp); gp.Reset(); PointF[] pts2 = { new PointF(borderRect.Width - 15, 0), new PointF(borderRect.Width - 5, 6), new PointF(borderRect.Width - 15, 12) }; gp.AddLines(pts2); graphics.FillPath(b, gp); gp.Dispose(); } } #endregion #region Overridden Methods protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); Invalidate(); } protected override void OnParentBackColorChanged(EventArgs e) { base.OnParentBackColorChanged(e); Invalidate(); } protected override void OnResize(EventArgs e) { base.OnResize(e); Invalidate(); } [SecuritySafeCritical] protected override void WndProc(ref Message m) { base.WndProc(ref m); if (!DesignMode) { try { WinApi.ShowScrollBar(Handle, (int)WinApi.ScrollBar.SB_BOTH, 0); } catch { } } } protected override CreateParams CreateParams { [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] get { const int WS_EX_LAYOUTRTL = 0x400000; const int WS_EX_NOINHERITLAYOUT = 0x100000; var cp = base.CreateParams; if (isMirrored) { cp.ExStyle = cp.ExStyle | WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT; } return cp; } } private new Rectangle GetTabRect(int index) { if (index < 0) return new Rectangle(); Rectangle baseRect = base.GetTabRect(index); return baseRect; } protected override void OnMouseWheel(MouseEventArgs e) { if (SelectedIndex != -1) { if (!TabPages[SelectedIndex].Focused) { bool subControlFocused = false; foreach (Control ctrl in TabPages[SelectedIndex].Controls) { if (ctrl.Focused) { subControlFocused = true; return; } } if (!subControlFocused) { TabPages[SelectedIndex].Select(); TabPages[SelectedIndex].Focus(); } } } base.OnMouseWheel(e); } protected override void OnCreateControl() { base.OnCreateControl(); this.OnFontChanged(EventArgs.Empty); FindUpDown(); } protected override void OnControlAdded(ControlEventArgs e) { base.OnControlAdded(e); FindUpDown(); UpdateUpDown(); } protected override void OnControlRemoved(ControlEventArgs e) { base.OnControlRemoved(e); FindUpDown(); UpdateUpDown(); } protected override void OnSelectedIndexChanged(EventArgs e) { base.OnSelectedIndexChanged(e); UpdateUpDown(); Invalidate(); } //send font change to properly resize tab page header rects //http://www.codeproject.com/Articles/13305/Painting-Your-Own-Tabs?msg=2707590#xx2707590xx [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); private const int WM_SETFONT = 0x30; private const int WM_FONTCHANGE = 0x1d; [SecuritySafeCritical] protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); IntPtr hFont = MetroFonts.TabControl(metroLabelSize, metroLabelWeight).ToHfont(); SendMessage(this.Handle, WM_SETFONT, hFont, (IntPtr)(-1)); SendMessage(this.Handle, WM_FONTCHANGE, IntPtr.Zero, IntPtr.Zero); this.UpdateStyles(); } #endregion #region Helper Methods [SecuritySafeCritical] private void FindUpDown() { if (!DesignMode) { bool bFound = false; IntPtr pWnd = WinApi.GetWindow(Handle, WinApi.GW_CHILD); while (pWnd != IntPtr.Zero) { char[] className = new char[33]; int length = WinApi.GetClassName(pWnd, className, 32); string s = new string(className, 0, length); if (s == "msctls_updown32") { bFound = true; if (!bUpDown) { this.scUpDown = new SubClass(pWnd, true); this.scUpDown.SubClassedWndProc += new SubClass.SubClassWndProcEventHandler(scUpDown_SubClassedWndProc); bUpDown = true; } break; } pWnd = WinApi.GetWindow(pWnd, WinApi.GW_HWNDNEXT); } if ((!bFound) && (bUpDown)) bUpDown = false; } } [SecuritySafeCritical] private void UpdateUpDown() { if (bUpDown && !DesignMode) { if (WinApi.IsWindowVisible(scUpDown.Handle)) { Rectangle rect = new Rectangle(); WinApi.GetClientRect(scUpDown.Handle, ref rect); WinApi.InvalidateRect(scUpDown.Handle, ref rect, true); } } } [SecuritySafeCritical] private int scUpDown_SubClassedWndProc(ref Message m) { switch (m.Msg) { case (int)WinApi.Messages.WM_PAINT: IntPtr hDC = WinApi.GetWindowDC(scUpDown.Handle); Graphics g = Graphics.FromHdc(hDC); DrawUpDown(g); g.Dispose(); WinApi.ReleaseDC(scUpDown.Handle, hDC); m.Result = IntPtr.Zero; Rectangle rect = new Rectangle(); WinApi.GetClientRect(scUpDown.Handle, ref rect); WinApi.ValidateRect(scUpDown.Handle, ref rect); return 1; } return 0; } #endregion } }
// // Main.cs // // Author: // Ruben Vermeersch <[email protected]> // Paul Lange <[email protected]> // Evan Briones <[email protected]> // Stephane Delcroix <[email protected]> // // Copyright (C) 2006-2010 Novell, Inc. // Copyright (C) 2010 Ruben Vermeersch // Copyright (C) 2010 Paul Lange // Copyright (C) 2010 Evan Briones // Copyright (C) 2006-2009 Stephane Delcroix // // Licensed under the MIT License. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using FSpot.Resources; using FSpot.Platform; using FSpot.Settings; using FSpot.Utils; using Hyena; using Hyena.CommandLine; using Hyena.Gui; using Mono.Addins; using Mono.Addins.Setup; using Mono.Unix; namespace FSpot { public static class Driver { static void ShowVersion () { Console.WriteLine ($"F-Spot {FSpotConfiguration.Version}"); Console.WriteLine ("http://f-spot.org"); Console.WriteLine ("\t(c)2003-2009, Novell Inc"); Console.WriteLine ("\t(c)2009 Stephane Delcroix"); Console.WriteLine ("Personal photo management for the GNOME Desktop"); } static void ShowAssemblyVersions () { ShowVersion (); Console.WriteLine (); Console.WriteLine ("Mono/.NET Version: " + Environment.Version); Console.WriteLine ($"{Environment.NewLine}Assembly Version Information:"); foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) { AssemblyName name = asm.GetName (); Console.WriteLine ($"\t{name.Name} ({name.Version})"); } } static void ShowHelp () { Console.WriteLine ("Usage: f-spot [options...] [files|URIs...]"); Console.WriteLine (); var commands = new Hyena.CommandLine.Layout ( new LayoutGroup ("help", "Help Options", new LayoutOption ("help", "Show this help"), new LayoutOption ("help-options", "Show command line options"), new LayoutOption ("help-all", "Show all options"), new LayoutOption ("version", "Show version information"), new LayoutOption ("versions", "Show detailed version information")), new LayoutGroup ("options", "General options", new LayoutOption ("basedir=DIR", "Path to the photo database folder"), new LayoutOption ("import=URI", "Import from the given uri"), new LayoutOption ("photodir=DIR", "Default import folder"), new LayoutOption ("view ITEM", "View file(s) or directories"), new LayoutOption ("shutdown", "Shut down a running instance of F-Spot"), new LayoutOption ("slideshow", "Display a slideshow"), new LayoutOption ("debug", "Run in debug mode"))); if (ApplicationContext.CommandLine.Contains ("help-all")) { Console.WriteLine (commands); return; } List<string> errors = null; foreach (var argument in ApplicationContext.CommandLine.Arguments) { switch (argument.Key) { case "help": Console.WriteLine (commands.ToString ("help")); break; case "help-options": Console.WriteLine (commands.ToString ("options")); break; default: if (argument.Key.StartsWith ("help", StringComparison.OrdinalIgnoreCase)) { (errors ??= new List<string> ()).Add (argument.Key); } break; } } if (errors != null) Console.WriteLine (commands.LayoutLine ($"The following help arguments are invalid: {Hyena.Collections.CollectionExtensions.Join (errors, "--", null, ", ")}")); } static string[] FixArgs (IReadOnlyList<string> args) { // Makes sure command line arguments are parsed backwards compatible. var outargs = new List<string> (); for (int i = 0; i < args.Count; i++) { switch (args[i]) { case "-h": case "-help": case "-usage": outargs.Add ("--help"); break; case "-V": case "-version": outargs.Add ("--version"); break; case "-versions": outargs.Add ("--versions"); break; case "-shutdown": outargs.Add ("--shutdown"); break; case "-b": case "-basedir": case "--basedir": outargs.Add ("--basedir=" + (i + 1 == args.Count ? string.Empty : args[++i])); break; case "-p": case "-photodir": case "--photodir": outargs.Add ("--photodir=" + (i + 1 == args.Count ? string.Empty : args[++i])); break; case "-i": case "-import": case "--import": outargs.Add ("--import=" + (i + 1 == args.Count ? string.Empty : args[++i])); break; case "-v": case "-view": outargs.Add ("--view"); break; case "-slideshow": outargs.Add ("--slideshow"); break; default: outargs.Add (args[i]); break; } } return outargs.ToArray (); } static int Main (string[] args) { Logger.CreateLogger (); if (Environment.Is64BitProcess) throw new ApplicationException ("GtkSharp does not support running 64bit"); args = FixArgs (args); ApplicationContext.ApplicationName = "F-Spot"; ApplicationContext.TrySetProcessName (FSpotConfiguration.Package); Paths.ApplicationName = "f-spot"; SynchronizationContext.SetSynchronizationContext (new GtkSynchronizationContext ()); ThreadAssist.InitializeMainThread (); ThreadAssist.ProxyToMainHandler = RunIdle; // Options and Option parsing bool shutdown = false; bool view = false; bool slideshow = false; bool import = false; GLib.GType.Init (); Catalog.Init ("f-spot", FSpotConfiguration.LocaleDir); FSpotConfiguration.PhotoUri = new SafeUri (Preferences.Get<string> (Preferences.StoragePath)); ApplicationContext.CommandLine = new CommandLineParser (args, 0); if (ApplicationContext.CommandLine.ContainsStart ("help")) { ShowHelp (); return 0; } if (ApplicationContext.CommandLine.Contains ("version")) { ShowVersion (); return 0; } if (ApplicationContext.CommandLine.Contains ("versions")) { ShowAssemblyVersions (); return 0; } if (ApplicationContext.CommandLine.Contains ("shutdown")) { Log.Information ("Shutting down existing F-Spot server..."); shutdown = true; } if (ApplicationContext.CommandLine.Contains ("slideshow")) { Log.Information ("Running F-Spot in slideshow mode."); slideshow = true; } if (ApplicationContext.CommandLine.Contains ("basedir")) { string dir = ApplicationContext.CommandLine["basedir"]; if (!string.IsNullOrEmpty (dir)) { FSpotConfiguration.BaseDirectory = dir; Log.Information ($"BaseDirectory is now {dir}"); } else { Log.Error ("f-spot: -basedir option takes one argument"); return 1; } } if (ApplicationContext.CommandLine.Contains ("photodir")) { string dir = ApplicationContext.CommandLine["photodir"]; if (!string.IsNullOrEmpty (dir)) { FSpotConfiguration.PhotoUri = new SafeUri (dir); Log.Information ($"PhotoDirectory is now {dir}"); } else { Log.Error ("f-spot: -photodir option takes one argument"); return 1; } } if (ApplicationContext.CommandLine.Contains ("import")) import = true; if (ApplicationContext.CommandLine.Contains ("view")) view = true; if (ApplicationContext.CommandLine.Contains ("debug")) { Log.Debugging = true; // Debug GdkPixbuf critical warnings var logFunc = new GLib.LogFunc (GLib.Log.PrintTraceLogFunction); GLib.Log.SetLogHandler ("GdkPixbuf", GLib.LogLevelFlags.Critical, logFunc); // Debug Gtk critical warnings GLib.Log.SetLogHandler ("Gtk", GLib.LogLevelFlags.Critical, logFunc); // Debug GLib critical warnings GLib.Log.SetLogHandler ("GLib", GLib.LogLevelFlags.Critical, logFunc); //Debug GLib-GObject critical warnings GLib.Log.SetLogHandler ("GLib-GObject", GLib.LogLevelFlags.Critical, logFunc); GLib.Log.SetLogHandler ("GLib-GIO", GLib.LogLevelFlags.Critical, logFunc); } // Validate command line options if ((import && (view || shutdown || slideshow)) || (view && (shutdown || slideshow)) || (shutdown && slideshow)) { Log.Error ("Can't mix -import, -view, -shutdown or -slideshow"); return 1; } InitializeAddins (); // Gtk initialization Gtk.Application.Init (FSpotConfiguration.Package, ref args); // Maybe we'll add this at a future date //Xwt.Application.InitializeAsGuest (Xwt.ToolkitType.Gtk); // init web proxy globally // FIXME, Reenable this at some point? //FSpotWebProxy.Init (); if (File.Exists (Preferences.Get<string> (Preferences.GtkRc))) { if (File.Exists (Path.Combine (FSpotConfiguration.BaseDirectory, "gtkrc"))) Gtk.Rc.AddDefaultFile (Path.Combine (FSpotConfiguration.BaseDirectory, "gtkrc")); FSpotConfiguration.DefaultRcFiles = Gtk.Rc.DefaultFiles; Gtk.Rc.AddDefaultFile (Preferences.Get<string> (Preferences.GtkRc)); Gtk.Rc.ReparseAllForSettings (Gtk.Settings.Default, true); } try { Gtk.Window.DefaultIconList = new[] { GtkUtil.TryLoadIcon (FSpotConfiguration.IconTheme, "FSpot", 16, 0), GtkUtil.TryLoadIcon (FSpotConfiguration.IconTheme, "FSpot", 22, 0), GtkUtil.TryLoadIcon (FSpotConfiguration.IconTheme, "FSpot", 32, 0), GtkUtil.TryLoadIcon (FSpotConfiguration.IconTheme, "FSpot", 48, 0) }; } catch (Exception ex) { Log.Exception ("Loading default f-spot icons", ex); } GLib.ExceptionManager.UnhandledException += exceptionArgs => { Console.WriteLine ("Unhandled exception handler:"); if (exceptionArgs.ExceptionObject is Exception exception) { Console.WriteLine ($"Message: {exception.Message}"); Console.WriteLine ($"Stack trace: {exception.StackTrace}"); } else { Console.WriteLine ($"Unknown exception type: {exceptionArgs.ExceptionObject.GetType ()}"); } }; CleanRoomStartup.Startup (Startup); // Running threads are preventing the application from quitting // we force it for now until this is fixed Environment.Exit (0); return 0; } static void InitializeAddins () { uint timer = Log.InformationTimerStart ("Initializing Mono.Addins"); try { UpdatePlugins (); } catch (Exception) { Log.Debug ("Failed to initialize plugins, will remove addin-db and try again."); ResetPluginDb (); } var setupService = new SetupService (AddinManager.Registry); foreach (AddinRepository repo in setupService.Repositories.GetRepositories ()) { if (repo.Url.StartsWith ("http://addins.f-spot.org/", StringComparison.OrdinalIgnoreCase)) { Log.Information ($"Unregistering {repo.Url}"); setupService.Repositories.RemoveRepository (repo.Url); } } Log.DebugTimerPrint (timer, "Mono.Addins Initialization took {0}"); } static void UpdatePlugins () { AddinManager.Initialize (FSpotConfiguration.BaseDirectory); AddinManager.Registry.Update (null); } static void ResetPluginDb () { // FIXME, test this. // Nuke addin-db var directory = new DirectoryInfo (new SafeUri (FSpotConfiguration.BaseDirectory)); foreach (var item in directory.EnumerateDirectories ()) { if (item.Name.StartsWith ("addin-db-", StringComparison.OrdinalIgnoreCase)) item.Delete (true); } // Try again UpdatePlugins (); } static void Startup () { if (ApplicationContext.CommandLine.Contains ("slideshow")) App.Instance.Slideshow (null); else if (ApplicationContext.CommandLine.Contains ("shutdown")) App.Instance.Shutdown (); else if (ApplicationContext.CommandLine.Contains ("view")) { if (ApplicationContext.CommandLine.Files.Count == 0) { Log.Error ("f-spot: -view option takes at least one argument"); Environment.Exit (1); } var list = new UriList (); foreach (var f in ApplicationContext.CommandLine.Files) list.AddUnknown (f); if (list.Count == 0) { ShowHelp (); Environment.Exit (1); } App.Instance.View (list); } else if (ApplicationContext.CommandLine.Contains ("import")) { string dir = ApplicationContext.CommandLine["import"]; if (string.IsNullOrEmpty (dir)) { Log.Error ("f-spot: -import option takes one argument"); Environment.Exit (1); } App.Instance.Import (dir); } else App.Instance.Organize (); //if (!App.Instance.IsRunning) try { Gtk.Application.Run (); } catch (Exception ex) { Log.Exception (ex); } } public static void RunIdle (InvokeHandler handler) { GLib.Idle.Add (delegate { handler (); return false; }); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.IdentityModel.Tokens { using System; using System.Collections.Generic; using System.IdentityModel.Selectors; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Security; using System.Xml; using KeyIdentifierEntry = System.IdentityModel.Selectors.SecurityTokenSerializer.KeyIdentifierEntry; class XmlDsigSep2000 : SecurityTokenSerializer.SerializerEntries { KeyInfoSerializer securityTokenSerializer; public XmlDsigSep2000( KeyInfoSerializer securityTokenSerializer ) { this.securityTokenSerializer = securityTokenSerializer; } public override void PopulateKeyIdentifierEntries( IList<KeyIdentifierEntry> keyIdentifierEntries ) { keyIdentifierEntries.Add( new KeyInfoEntry( this.securityTokenSerializer ) ); } public override void PopulateKeyIdentifierClauseEntries( IList<SecurityTokenSerializer.KeyIdentifierClauseEntry> keyIdentifierClauseEntries ) { keyIdentifierClauseEntries.Add( new KeyNameClauseEntry() ); keyIdentifierClauseEntries.Add( new KeyValueClauseEntry() ); keyIdentifierClauseEntries.Add( new X509CertificateClauseEntry() ); } internal class KeyInfoEntry : KeyIdentifierEntry { KeyInfoSerializer securityTokenSerializer; public KeyInfoEntry( KeyInfoSerializer securityTokenSerializer ) { this.securityTokenSerializer = securityTokenSerializer; } protected override XmlDictionaryString LocalName { get { return XD.XmlSignatureDictionary.KeyInfo; } } protected override XmlDictionaryString NamespaceUri { get { return XD.XmlSignatureDictionary.Namespace; } } public override SecurityKeyIdentifier ReadKeyIdentifierCore( XmlDictionaryReader reader ) { reader.ReadStartElement( LocalName, NamespaceUri ); SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier(); while ( reader.IsStartElement() ) { SecurityKeyIdentifierClause clause = this.securityTokenSerializer.ReadKeyIdentifierClause( reader ); if ( clause == null ) { reader.Skip(); } else { keyIdentifier.Add( clause ); } } if ( keyIdentifier.Count == 0 ) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new XmlException( SR.GetString( SR.ErrorDeserializingKeyIdentifierClause ) ) ); } reader.ReadEndElement(); return keyIdentifier; } public override bool SupportsCore( SecurityKeyIdentifier keyIdentifier ) { return true; } public override void WriteKeyIdentifierCore( XmlDictionaryWriter writer, SecurityKeyIdentifier keyIdentifier ) { writer.WriteStartElement( XD.XmlSignatureDictionary.Prefix.Value, LocalName, NamespaceUri ); bool clauseWritten = false; foreach ( SecurityKeyIdentifierClause clause in keyIdentifier ) { this.securityTokenSerializer.InnerSecurityTokenSerializer.WriteKeyIdentifierClause( writer, clause ); clauseWritten = true; } writer.WriteEndElement(); // KeyInfo if ( !clauseWritten ) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityMessageSerializationException( SR.GetString( SR.NoKeyInfoClausesToWrite ) ) ); } } } // <ds:KeyName>name</ds:KeyName> internal class KeyNameClauseEntry : SecurityTokenSerializer.KeyIdentifierClauseEntry { protected override XmlDictionaryString LocalName { get { return XD.XmlSignatureDictionary.KeyName; } } protected override XmlDictionaryString NamespaceUri { get { return XD.XmlSignatureDictionary.Namespace; } } public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore( XmlDictionaryReader reader ) { reader.ReadStartElement( XD.XmlSignatureDictionary.KeyName, NamespaceUri ); string name = reader.ReadString(); reader.ReadEndElement(); return new KeyNameIdentifierClause( name ); } public override bool SupportsCore( SecurityKeyIdentifierClause keyIdentifierClause ) { return keyIdentifierClause is KeyNameIdentifierClause; } public override void WriteKeyIdentifierClauseCore( XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause ) { KeyNameIdentifierClause nameClause = keyIdentifierClause as KeyNameIdentifierClause; writer.WriteElementString( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.KeyName, NamespaceUri, nameClause.KeyName ); } } // so far, we only support one type of KeyValue - RSAKeyValue // <ds:KeyValue> // <ds:RSAKeyValue> // <ds:Modulus>xA7SEU+...</ds:Modulus> // <ds:Exponent>AQAB</Exponent> // </ds:RSAKeyValue> // </ds:KeyValue> internal class KeyValueClauseEntry : SecurityTokenSerializer.KeyIdentifierClauseEntry { protected override XmlDictionaryString LocalName { get { return XD.XmlSignatureDictionary.KeyValue; } } protected override XmlDictionaryString NamespaceUri { get { return XD.XmlSignatureDictionary.Namespace; } } public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore( XmlDictionaryReader reader ) { reader.ReadStartElement( XD.XmlSignatureDictionary.KeyValue, NamespaceUri ); reader.ReadStartElement( XD.XmlSignatureDictionary.RsaKeyValue, NamespaceUri ); reader.ReadStartElement( XD.XmlSignatureDictionary.Modulus, NamespaceUri ); byte[] modulus = Convert.FromBase64String( reader.ReadString() ); reader.ReadEndElement(); reader.ReadStartElement( XD.XmlSignatureDictionary.Exponent, NamespaceUri ); byte[] exponent = Convert.FromBase64String( reader.ReadString() ); reader.ReadEndElement(); reader.ReadEndElement(); reader.ReadEndElement(); RSA rsa = new RSACryptoServiceProvider(); RSAParameters rsaParameters = new RSAParameters(); rsaParameters.Modulus = modulus; rsaParameters.Exponent = exponent; rsa.ImportParameters( rsaParameters ); return new RsaKeyIdentifierClause( rsa ); } public override bool SupportsCore( SecurityKeyIdentifierClause keyIdentifierClause ) { return keyIdentifierClause is RsaKeyIdentifierClause; } public override void WriteKeyIdentifierClauseCore( XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause ) { RsaKeyIdentifierClause rsaClause = keyIdentifierClause as RsaKeyIdentifierClause; writer.WriteStartElement( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.KeyValue, NamespaceUri ); writer.WriteStartElement( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.RsaKeyValue, NamespaceUri ); writer.WriteStartElement( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.Modulus, NamespaceUri ); rsaClause.WriteModulusAsBase64( writer ); writer.WriteEndElement(); writer.WriteStartElement( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.Exponent, NamespaceUri ); rsaClause.WriteExponentAsBase64( writer ); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); } } // so far, we only support two types of X509Data directly under KeyInfo - X509Certificate and X509SKI // <ds:X509Data> // <ds:X509Certificate>...</ds:X509Certificate> // or // <X509SKI>... </X509SKI> // </ds:X509Data> // only support 1 certificate right now internal class X509CertificateClauseEntry : SecurityTokenSerializer.KeyIdentifierClauseEntry { protected override XmlDictionaryString LocalName { get { return XD.XmlSignatureDictionary.X509Data; } } protected override XmlDictionaryString NamespaceUri { get { return XD.XmlSignatureDictionary.Namespace; } } public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore( XmlDictionaryReader reader ) { SecurityKeyIdentifierClause ski = null; reader.ReadStartElement( XD.XmlSignatureDictionary.X509Data, NamespaceUri ); while ( reader.IsStartElement() ) { if ( ski == null && reader.IsStartElement( XD.XmlSignatureDictionary.X509Certificate, NamespaceUri ) ) { X509Certificate2 certificate = null; if ( !SecurityUtils.TryCreateX509CertificateFromRawData( reader.ReadElementContentAsBase64(), out certificate ) ) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityMessageSerializationException( SR.GetString( SR.InvalidX509RawData ) ) ); } ski = new X509RawDataKeyIdentifierClause( certificate ); } else if ( ski == null && reader.IsStartElement( XmlSignatureStrings.X509Ski, NamespaceUri.ToString() ) ) { ski = new X509SubjectKeyIdentifierClause( reader.ReadElementContentAsBase64() ); } else if ( ( ski == null ) && reader.IsStartElement( XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace ) ) { reader.ReadStartElement( XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace ); reader.ReadStartElement( XD.XmlSignatureDictionary.X509IssuerName, XD.XmlSignatureDictionary.Namespace ); string issuerName = reader.ReadContentAsString(); reader.ReadEndElement(); reader.ReadStartElement( XD.XmlSignatureDictionary.X509SerialNumber, XD.XmlSignatureDictionary.Namespace ); string serialNumber = reader.ReadContentAsString(); reader.ReadEndElement(); reader.ReadEndElement(); ski = new X509IssuerSerialKeyIdentifierClause( issuerName, serialNumber ); } else { reader.Skip(); } } reader.ReadEndElement(); return ski; } public override bool SupportsCore( SecurityKeyIdentifierClause keyIdentifierClause ) { return (keyIdentifierClause is X509RawDataKeyIdentifierClause); // This method should not write X509IssuerSerialKeyIdentifierClause or X509SubjectKeyIdentifierClause as that should be written by the WSSecurityXXX classes with SecurityTokenReference tag. // The XmlDsig entries are written by the X509SecurityTokenHandler. } public override void WriteKeyIdentifierClauseCore( XmlDictionaryWriter writer, SecurityKeyIdentifierClause keyIdentifierClause ) { X509RawDataKeyIdentifierClause x509Clause = keyIdentifierClause as X509RawDataKeyIdentifierClause; if ( x509Clause != null ) { writer.WriteStartElement( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509Data, NamespaceUri ); writer.WriteStartElement( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509Certificate, NamespaceUri ); byte[] certBytes = x509Clause.GetX509RawData(); writer.WriteBase64( certBytes, 0, certBytes.Length ); writer.WriteEndElement(); writer.WriteEndElement(); } X509IssuerSerialKeyIdentifierClause issuerSerialClause = keyIdentifierClause as X509IssuerSerialKeyIdentifierClause; if ( issuerSerialClause != null ) { writer.WriteStartElement( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace ); writer.WriteStartElement( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace ); writer.WriteElementString( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509IssuerName, XD.XmlSignatureDictionary.Namespace, issuerSerialClause.IssuerName ); writer.WriteElementString( XD.XmlSignatureDictionary.Prefix.Value, XD.XmlSignatureDictionary.X509SerialNumber, XD.XmlSignatureDictionary.Namespace, issuerSerialClause.IssuerSerialNumber ); writer.WriteEndElement(); writer.WriteEndElement(); return; } X509SubjectKeyIdentifierClause skiClause = keyIdentifierClause as X509SubjectKeyIdentifierClause; if ( skiClause != null ) { writer.WriteStartElement( XmlSignatureConstants.Prefix, XmlSignatureConstants.Elements.X509Data, XmlSignatureConstants.Namespace ); writer.WriteStartElement( XmlSignatureConstants.Prefix, XmlSignatureConstants.Elements.X509SKI, XmlSignatureConstants.Namespace ); byte[] ski = skiClause.GetX509SubjectKeyIdentifier(); writer.WriteBase64( ski, 0, ski.Length ); writer.WriteEndElement(); writer.WriteEndElement(); return; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using McMaster.Extensions.CommandLineUtils; using NuGet.CatalogReader; using NuGet.Common; using NuGet.Packaging; using NuGet.Protocol; using NuGet.Protocol.Core.Types; namespace NuGet.CatalogValidator { /// <summary> /// Validate a v3 feed. /// </summary> internal static class ValidateCommand { public static void Register(CommandLineApplication cmdApp, HttpSource httpSource, ILogger consoleLog) { cmdApp.Command("validate", (cmd) => Run(cmd, httpSource, consoleLog), throwOnUnexpectedArg: true); } private static void Run(CommandLineApplication cmd, HttpSource httpSource, ILogger consoleLog) { cmd.Description = "Validate a v3 feed."; var delay = cmd.Option("--delay", "Avoid downloading the very latest packages on the feed to avoid errors. This value is in minutes. Default: 10", CommandOptionType.SingleValue); var maxThreadsOption = cmd.Option("--max-threads", "Maximum number of concurrent downloads. Default: 8", CommandOptionType.SingleValue); var verbose = cmd.Option("--verbose", "Output additional network information.", CommandOptionType.NoValue); var argRoot = cmd.Argument( "[root]", "V3 feed index.json URI", multipleValues: false); cmd.HelpOption(Constants.HelpOption); cmd.OnExecute(async () => { var timer = new Stopwatch(); timer.Start(); if (string.IsNullOrEmpty(argRoot.Value)) { throw new ArgumentException("Provide the full http url to a v3 nuget feed."); } var index = new Uri(argRoot.Value); if (!index.AbsolutePath.EndsWith("/index.json", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException($"Invalid feed url: '{argRoot.Value}'. Provide the full http url to a v3 nuget feed. For nuget.org use: https://api.nuget.org/v3/index.json"); } var delayTime = TimeSpan.FromMinutes(10); if (delay.HasValue()) { if (int.TryParse(delay.Value(), out int x)) { var delayMinutes = Math.Max(0, x); delayTime = TimeSpan.FromMinutes(delayMinutes); } else { throw new ArgumentException("Invalid --delay value. This must be an integer."); } } var maxThreads = 8; if (maxThreadsOption.HasValue()) { if (int.TryParse(maxThreadsOption.Value(), out int x)) { maxThreads = Math.Max(1, x); } else { throw new ArgumentException("Invalid --max-threads value. This must be an integer."); } } var batchSize = 4096; var start = DateTimeOffset.MinValue; var end = DateTimeOffset.UtcNow.Subtract(delayTime); var token = CancellationToken.None; // Loggers // source -> deep -> file -> Console var log = consoleLog; var deepLogger = new FilterLogger(log, LogLevel.Error); // Init log.LogInformation($"Validating {index.AbsoluteUri}"); log.LogInformation("Range start:\t" + start.ToString("o")); log.LogInformation("Range end:\t" + end.ToString("o")); log.LogInformation($"Batch size:\t{batchSize}"); log.LogInformation($"Threads:\t{maxThreads}"); var success = true; // CatalogReader using (var httpClient = new HttpClient()) using (var cacheContext = new SourceCacheContext()) using (var catalogReader = new CatalogReader.CatalogReader(index, httpSource, cacheContext, TimeSpan.Zero, deepLogger)) { // Find the most recent entry for each package in the range // Order by oldest first IEnumerable<CatalogEntry> entryQuery = (await catalogReader .GetFlattenedEntriesAsync(start, end, token)); var toProcess = new Queue<CatalogEntry>(entryQuery.OrderBy(e => e.CommitTimeStamp)); log.LogInformation($"Catalog entries found: {toProcess.Count}"); var complete = 0; var total = toProcess.Count; // Download files var tasks = new List<Task<ValidationResult>>(maxThreads); var results = new List<ValidationResult>(); // Download with throttling while (toProcess.Count > 0) { // Create batches var batch = new Queue<CatalogEntry>(batchSize); var batchTimer = new Stopwatch(); batchTimer.Start(); while (toProcess.Count > 0 && batch.Count < batchSize) { batch.Enqueue(toProcess.Dequeue()); } var batchCount = batch.Count; while (batch.Count > 0) { if (tasks.Count == maxThreads) { await CompleteTaskAsync(tasks, results); } var entry = batch.Dequeue(); // Run tasks.Add(Task.Run(async () => await VerifyNupkgExistsAsync(entry, httpClient, NullLogger.Instance, token))); } // Wait for all batch downloads while (tasks.Count > 0) { await CompleteTaskAsync(tasks, results); } complete += batchCount; batchTimer.Stop(); // Update cursor log.LogMinimal($"================[batch complete]================"); log.LogMinimal($"Processed:\t\t{complete} / {total}"); log.LogMinimal($"Batch time:\t\t{batchTimer.Elapsed}"); var rate = batchTimer.Elapsed.TotalSeconds / Math.Max(1, batchCount); var timeLeft = TimeSpan.FromSeconds(rate * (total - complete)); var timeLeftString = string.Empty; if (timeLeft.TotalHours >= 1) { timeLeftString = $"{(int)timeLeft.TotalHours} hours"; } else if (timeLeft.TotalMinutes >= 1) { timeLeftString = $"{(int)timeLeft.TotalMinutes} minutes"; } else { timeLeftString = $"{(int)timeLeft.TotalSeconds} seconds"; } log.LogMinimal($"Estimated time left:\t{timeLeftString}"); log.LogMinimal($"================================================"); // Free up space catalogReader.ClearCache(); } timer.Stop(); log.LogMinimal($"Validation time: {timer.Elapsed}"); foreach (var group in results.GroupBy(e => e.Type)) { log.LogMinimal($"=====[Validation: {group.Key}]====="); foreach (var entry in group.OrderBy(e => e.Entry.Id, StringComparer.OrdinalIgnoreCase)) { success = false; log.LogError(entry.Message); } } if (results.Count == 0) { log.LogMinimal("No errors found!"); } } return success ? 0 : 1; }); } private static async Task CompleteTaskAsync(List<Task<ValidationResult>> tasks, List<ValidationResult> results) { var task = await Task.WhenAny(tasks); tasks.Remove(task); if (!task.Result.Success) { results.Add(task.Result); } } private static async Task<ValidationResult> VerifyNupkgExistsAsync(CatalogEntry entry, HttpClient httpClient, ILogger log, CancellationToken token) { var status = await GetStatusCodeAsync(entry.NupkgUri, httpClient, log, token); var result = new ValidationResult() { Entry = entry, Success = status == HttpStatusCode.OK, Message = status == HttpStatusCode.OK ? string.Empty : $"Error: {entry.NupkgUri.AbsoluteUri} Status code: {status} Catalog entry: {entry.Uri.AbsoluteUri} Id: {entry.Id} Version: {entry.Version.ToNormalizedString()}", Type = ValidationType.Nupkg }; return result; } private static async Task<HttpStatusCode> GetStatusCodeAsync(Uri uri, HttpClient httpClient, ILogger log, CancellationToken token) { for (var i = 0; i < 5; i++) { try { var request = new HttpRequestMessage(HttpMethod.Head, uri); var response = await httpClient.SendAsync(request, token); return response.StatusCode; } catch { // Try again. await Task.Delay(100); } } return HttpStatusCode.ServiceUnavailable; } internal class ValidationResult { public bool Success { get; set; } public ValidationType Type { get; set; } public string Message { get; set; } public CatalogEntry Entry { get; set; } } internal enum ValidationType { Nupkg = 1, Nuspec = 2 } } }
using Signum.Utilities; using Signum.Utilities.ExpressionTrees; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; namespace Signum.Entities.Dynamic { [Serializable, EntityKind(EntityKind.Main, EntityData.Master)] public class DynamicTypeEntity : Entity { public DynamicBaseType BaseType { set; get; } [UniqueIndex] [StringLengthValidator(Min = 3, Max = 100), IdentifierValidator(IdentifierType.PascalAscii)] public string TypeName { get; set; } [DbType(Size = int.MaxValue)] string typeDefinition; [StringLengthValidator(Min = 3)] public string TypeDefinition { get { return this.Get(typeDefinition); } set { if (this.Set(ref typeDefinition, value)) this.definition = null; } } static JsonSerializerOptions settings = new JsonSerializerOptions { IncludeFields = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, PropertyNameCaseInsensitive = true, Converters= { new JsonStringEnumConverter(), } }; [Ignore] DynamicTypeDefinition? definition; public DynamicTypeDefinition GetDefinition() { return definition ?? (definition = JsonSerializer.Deserialize<DynamicTypeDefinition>(this.TypeDefinition, settings))!; } public void SetDefinition(DynamicTypeDefinition definition) { this.TypeDefinition = JsonSerializer.Serialize(definition, settings); this.definition = definition; } protected override string? PropertyValidation(PropertyInfo pi) { if (pi.Name == nameof(TypeDefinition)) { var def = this.GetDefinition(); return def.Properties .Where(p => p.Name.HasText() && !IdentifierValidatorAttribute.PascalAscii.IsMatch(p.Name)) .Select(p => ValidationMessage._0DoesNotHaveAValid1IdentifierFormat.NiceToString(p.Name, IdentifierType.PascalAscii)) .ToString("\r\n") .DefaultToNull(); } return base.PropertyValidation(pi); } [AutoExpressionField] public override string ToString() => As.Expression(() => TypeName); } [AutoInit] public static class DynamicTypeOperation { public static readonly ConstructSymbol<DynamicTypeEntity>.Simple Create; public static readonly ConstructSymbol<DynamicTypeEntity>.From<DynamicTypeEntity> Clone; public static readonly ExecuteSymbol<DynamicTypeEntity> Save; public static readonly DeleteSymbol<DynamicTypeEntity> Delete; } public enum DynamicTypeMessage { TypeSaved, [Description("DynamicType '{0}' successfully saved. Go to DynamicPanel now?")] DynamicType0SucessfullySavedGoToDynamicPanelNow, [Description("Server restarted with errors in dynamic code. Fix errors and restart again.")] ServerRestartedWithErrorsInDynamicCodeFixErrorsAndRestartAgain, [Description("Remove Save Operation?")] RemoveSaveOperation, TheEntityShouldBeSynchronizedToApplyMixins, } public class DynamicTypePrimaryKeyDefinition { public string? Name; public string? Type; public bool Identity; } public class DynamicTypeTicksDefinition { public bool HasTicks; public string? Name; public string? Type; } public class DynamicTypeBackMListDefinition { public string? TableName; public bool PreserveOrder; public string? OrderName; public string? BackReferenceName; } public class DynamicTypeDefinition { public EntityKind? EntityKind; public EntityData? EntityData; public string? TableName; public DynamicTypePrimaryKeyDefinition? PrimaryKey; public DynamicTypeTicksDefinition? Ticks; public List<DynamicProperty> Properties; public OperationConstruct? OperationCreate; public OperationExecute? OperationSave; public OperationDelete? OperationDelete; public OperationConstructFrom? OperationClone; public DynamicTypeCustomCode? CustomInheritance; public DynamicTypeCustomCode? CustomEntityMembers; public DynamicTypeCustomCode? CustomStartCode; public DynamicTypeCustomCode? CustomLogicMembers; public DynamicTypeCustomCode? CustomTypes; public DynamicTypeCustomCode? CustomBeforeSchema; public List<string> QueryFields; public MultiColumnUniqueIndex? MultiColumnUniqueIndex; public string? ToStringExpression; } public class MultiColumnUniqueIndex { public List<string> Fields; public string? Where; } public class OperationConstruct { public string Construct; } public class OperationExecute { public string? CanExecute; public string Execute; } public class OperationDelete { public string? CanDelete; public string Delete; } public class OperationConstructFrom { public string? CanConstruct; public string Construct; } public class DynamicTypeCustomCode { public string Code; } public enum DynamicBaseType { Entity, MixinEntity, EmbeddedEntity, ModelEntity, } public class DynamicProperty { public string UID; public string Name; public string? ColumnName; public string Type; public string? ColumnType; public IsNullable IsNullable; public UniqueIndex UniqueIndex; public bool? IsLite; public DynamicTypeBackMListDefinition IsMList; public int? Size; public int? Scale; public string? Unit; public string? Format; public bool? NotifyChanges; public List<DynamicValidator>? Validators; public string? CustomFieldAttributes; public string? CustomPropertyAttributes; } public enum IsNullable { Yes, OnlyInMemory, No, } public enum UniqueIndex { No, Yes, YesAllowNull, } class DynamicValidatorConverter : JsonConverter<DynamicValidator> { public override bool CanConvert(Type objectType) { return (objectType == typeof(DynamicValidator)); } public override DynamicValidator? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using(JsonDocument doc = JsonDocument.ParseValue(ref reader)) { var typeName = doc.RootElement.GetProperty("type").GetString()!; var type = DynamicValidator.GetDynamicValidatorType(typeName); return (DynamicValidator)doc.RootElement.ToObject(type, options); } } public override void Write(Utf8JsonWriter writer, DynamicValidator value, JsonSerializerOptions options) { throw new NotImplementedException(); } } [JsonConverter(typeof(DynamicValidatorConverter))] public class DynamicValidator { public string Type; public static Type GetDynamicValidatorType(string type) { switch (type) { case "NotNull": return typeof(NotNull); case "StringLength": return typeof(StringLength); case "Decimals": return typeof(Decimals); case "NumberIs": return typeof(NumberIs); case "CountIs": return typeof(CountIs); case "NumberBetween": return typeof(NumberBetween); case "DateTimePrecision": return typeof(DateTimePrecision); case "TimeSpanPrecision": return typeof(TimeSpanPrecision); case "StringCase": return typeof(StringCase); default: return typeof(DefaultDynamicValidator); } } public virtual string? ExtraArguments() { return null; } string Value(object obj) { if (obj is decimal) obj = (double)(decimal)obj; return CSharpRenderer.Value(obj); } public class NotNull : DynamicValidator { public bool Disabled; public override string? ExtraArguments() { return new string?[] { Disabled ? "Disabled=true" : null, }.NotNull().ToString(", "); } } public class StringLength : DynamicValidator { public bool MultiLine; public int? Min; public int? Max; public bool? AllowLeadingSpaces; public bool? AllowTrailingSpaces; public override string? ExtraArguments() { return new string?[] { MultiLine ? "MultiLine=true" : null, Min.HasValue ? "Min=" + Value(Min.Value) : null, Max.HasValue ? "Max=" + Value(Max.Value) : null, AllowLeadingSpaces.HasValue ? "AllowLeadingSpaces=" + Value(AllowLeadingSpaces.Value) : null, AllowTrailingSpaces.HasValue ? "AllowTrailingSpaces=" + Value(AllowTrailingSpaces.Value) : null, }.NotNull().ToString(", "); } } public class Decimals : DynamicValidator { public int DecimalPlaces; public override string? ExtraArguments() { return Value(DecimalPlaces); } } public class NumberIs : DynamicValidator { public ComparisonType ComparisonType; public decimal Number; public override string? ExtraArguments() { return Value(ComparisonType) + ", " + Value(Number); } } public class CountIs : DynamicValidator { public ComparisonType ComparisonType; public decimal Number; public override string? ExtraArguments() { return Value(ComparisonType) + ", " + Value(Number); } } public class NumberBetween : DynamicValidator { public decimal Min; public decimal Max; public override string? ExtraArguments() { return Value(Min) + ", " + Value(Max); } } public class DateTimePrecision : DynamicValidator { public Signum.Utilities.DateTimePrecision Precision; public override string? ExtraArguments() { return Value(Precision); } } public class TimeSpanPrecision : DynamicValidator { public Signum.Utilities.DateTimePrecision Precision; public override string? ExtraArguments() { return Value(Precision); } } public class StringCase : DynamicValidator { public Signum.Entities.StringCase TextCase; public override string? ExtraArguments() { return Value(TextCase); } } public class DefaultDynamicValidator : DynamicValidator { } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at [email protected] // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using Microsoft.ApplicationBlocks.Data; using Subtext.Scripting.Exceptions; using Subtext.Framework.Properties; namespace Subtext.Scripting { /// <summary> /// Represents a single executable script within the full SQL script. /// </summary> public class Script : IScript, ITemplateScript { TemplateParameterCollection _parameters; ScriptToken _scriptTokens; /// <summary> /// Creates a new <see cref="TemplateParameter"/> instance. /// </summary> /// <param name="scriptText">Script text.</param> public Script(string scriptText) { OriginalScriptText = scriptText; } /// <summary> /// Gets the script text after applying template parameter replacements. /// This is the text of the script that will actually get executed. /// </summary> /// <value></value> public string ScriptText { get { return ApplyTemplateReplacements(); } } /// <summary> /// Gets the original script text. /// </summary> /// <value>The original script text.</value> public string OriginalScriptText { get; private set; } /// <summary> /// Executes this script. /// </summary> public int Execute(SqlTransaction transaction) { if(transaction == null) { throw new ArgumentNullException("transaction"); } int returnValue = 0; try { returnValue = SqlHelper.ExecuteNonQuery(transaction, CommandType.Text, ScriptText); return returnValue; } catch(SqlException e) { throw new SqlScriptExecutionException( String.Format(CultureInfo.InvariantCulture, Resources.SqlScriptExecutionError_ErrorInScript, ScriptText), this, returnValue, e); } } /// <summary> /// Gets the template parameters embedded in the script. /// </summary> /// <returns></returns> public TemplateParameterCollection TemplateParameters { get { if(_parameters == null) { _parameters = new TemplateParameterCollection(); if(String.IsNullOrEmpty(OriginalScriptText)) { return _parameters; } var regex = new Regex(@"<\s*(?<name>[^()\[\]>,]*)\s*,\s*(?<type>[^>,]*)\s*,\s*(?<default>[^>,]*)\s*>", RegexOptions.Compiled); MatchCollection matches = regex.Matches(OriginalScriptText); _scriptTokens = new ScriptToken(); int lastIndex = 0; foreach(Match match in matches) { if(match.Index > 0) { string textBeforeMatch = OriginalScriptText.Substring(lastIndex, match.Index - lastIndex); _scriptTokens.Append(textBeforeMatch); } lastIndex = match.Index + match.Length; TemplateParameter parameter = _parameters.Add(match); _scriptTokens.Append(parameter); } string textAfterLastMatch = OriginalScriptText.Substring(lastIndex); if(textAfterLastMatch.Length > 0) { _scriptTokens.Append(textAfterLastMatch); } } return _parameters; } } /// <summary> /// Helper method which given a full SQL script, returns /// a <see cref="ScriptCollection"/> of individual <see cref="TemplateParameter"/> /// using "GO" as the delimiter. /// </summary> /// <param name="fullScriptText">Full script text.</param> public static ScriptCollection ParseScripts(string fullScriptText) { var scripts = new ScriptCollection(fullScriptText); var splitter = new ScriptSplitter(fullScriptText); foreach(string script in splitter) { scripts.Add(new Script(script)); } return scripts; } string ApplyTemplateReplacements() { var builder = new StringBuilder(); if(_scriptTokens == null && TemplateParameters == null) { throw new InvalidOperationException(Resources.InvalidOperation_TemplateParametersNull); } if(_scriptTokens != null) { _scriptTokens.AggregateText(builder); } return builder.ToString(); } /// <summary> /// Returns the text of the script. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { if(_scriptTokens != null) { return _scriptTokens.ToString(); } return Resources.ScriptHasNoTokens; } /// <summary> /// Implements a linked list representing the script. This maps the structure /// of a script making it trivial to replace template parameters with their /// values. /// </summary> class ScriptToken { /// <summary> /// Initializes a new instance of the <see cref="ScriptToken"/> class. /// </summary> internal ScriptToken() { } /// <summary> /// Initializes a new instance of the <see cref="ScriptToken"/> class. /// </summary> /// <param name="text">The text.</param> private ScriptToken(string text) { Text = text; } /// <summary> /// Gets the text. /// </summary> /// <value>The text.</value> protected virtual string Text { get; set; } /// <summary> /// Gets or sets the next node. /// </summary> /// <value>The next.</value> protected ScriptToken Next { get; private set; } /// <summary> /// Gets the last node. /// </summary> /// <value>The last.</value> private ScriptToken Last { get { ScriptToken last = this; ScriptToken next = Next; while(next != null) { last = next; next = last.Next; } return last; } } /// <summary> /// Appends the specified text. /// </summary> /// <param name="text">The text.</param> internal void Append(string text) { Last.Next = new ScriptToken(text); } internal void Append(TemplateParameter parameter) { Last.Next = new TemplateParameterToken(parameter); } internal void AggregateText(StringBuilder builder) { builder.Append(Text); if(Next != null) { Next.AggregateText(builder); } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="ScriptToken"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { int length = 0; if(Text != null) { length = Text.Length; } string result = string.Format(CultureInfo.InvariantCulture, @"<ScriptToken length=""{0}"">{1}", length, Environment.NewLine); if(Next != null) { result += Next.ToString(); } return result; } } #region Nested type: TemplateParameterToken /// <summary> /// Represents a template parameter within a script. This is specialized node /// within the ScriptToken linked list. /// </summary> class TemplateParameterToken : ScriptToken { readonly TemplateParameter _parameter; internal TemplateParameterToken(TemplateParameter parameter) { _parameter = parameter; } /// <summary> /// Gets the text of this node. /// </summary> /// <value>The text.</value> protected override string Text { get { return _parameter.Value; } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="TemplateParameterToken"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { string result = "<TemplateParameter"; if(_parameter != null) { result += string.Format(CultureInfo.InvariantCulture, @" name=""{0}"" value=""{1}"" type=""{2}""", _parameter.Name, _parameter.Value, _parameter.DataType); } result += string.Format(" />{0}", Environment.NewLine); if(Next != null) { result += Next.ToString(); } return result; } } #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 Xunit; namespace System.Numerics.Tests { public class arithmaticOperation_BinaryMinus_SubtractTest { private static void VerifyBinaryMinusResult(double realFirst, double imgFirst, double realSecond, double imgSecond) { // Create complex numbers Complex cFirst = new Complex(realFirst, imgFirst); Complex cSecond = new Complex(realSecond, imgSecond); // calculate the expected results double realExpectedResult = realFirst - realSecond; double imgExpectedResult = imgFirst - imgSecond; // local varuables Complex cResult; // arithmetic binary minus operation cResult = cFirst - cSecond; // verify the result Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult, string.Format("Binary Minus test = ({0}, {1}) - ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond)); // arithmetic substract operation cResult = Complex.Subtract(cFirst, cSecond); // verify the result Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult, string.Format("Substract test = ({0}, {1}) - ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond)); } [Fact] public static void RunTests_Zero() { double real = Support.GetRandomDoubleValue(false); double imaginary = Support.GetRandomDoubleValue(false); // Test with Zero VerifyBinaryMinusResult(real, imaginary, 0.0, 0.0); // Verify x-0=0 VerifyBinaryMinusResult(0.0, 0.0, real, imaginary); // Verify 0-x=-x } [Fact] public static void RunTests_BoundaryValues() { double real; double img; // test with 'Max' - (Positive, Positive) real = Support.GetRandomDoubleValue(false); img = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(double.MaxValue, double.MaxValue, real, img); // test with (Positive, Positive) - 'Max' real = Support.GetRandomDoubleValue(false); img = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(real, img, double.MaxValue, double.MaxValue); // test with 'Max' - (Negative, Negative) real = Support.GetRandomDoubleValue(true); img = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(double.MaxValue, double.MaxValue, real, img); // test with (Negative, Negative) - 'Max' real = Support.GetRandomDoubleValue(true); img = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(real, img, double.MaxValue, double.MaxValue); // test with 'Min' - (Positive, Positive) real = Support.GetRandomDoubleValue(false); img = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(double.MinValue, double.MinValue, real, img); // test with (Positive, Positive) - 'Min' real = Support.GetRandomDoubleValue(false); img = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(real, img, double.MinValue, double.MinValue); // test with 'Min' - (Negative, Negative) real = Support.GetRandomDoubleValue(true); img = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(double.MinValue, double.MinValue, real, img); // test with (Negative, Negative) - 'Min' real = Support.GetRandomDoubleValue(true); img = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(real, img, double.MinValue, double.MinValue); } [Fact] public static void RunTests_RandomValidValues() { // Verify test results with ComplexInFirstQuad - ComplexInFirstQuad double realFirst = Support.GetRandomDoubleValue(false); double imgFirst = Support.GetRandomDoubleValue(false); double realSecond = Support.GetRandomDoubleValue(false); double imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFirstQuad - ComplexInSecondQuad realFirst = Support.GetRandomDoubleValue(false); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFirstQuad - ComplexInThirdQuad realFirst = Support.GetRandomDoubleValue(false); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFirstQuad - ComplexInFourthQuad realFirst = Support.GetRandomDoubleValue(false); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInSecondQuad - ComplexInSecondQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInSecondQuad - ComplexInThirdQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInSecondQuad - ComplexInFourthQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInThirdQuad - ComplexInThirdQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(true); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInThirdQuad - ComplexInFourthQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(true); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFourthQuad - ComplexInFourthQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); } [Fact] public static void RunTests_InvalidImaginaryValues() { double realFirst; double imgFirst; double realSecond; double imgSecond; // Verify with (valid, PositiveInfinity) - (valid, PositiveValid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.PositiveInfinity; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, PositiveInfinity) - (valid, NegativeValid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.PositiveInfinity; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, NegativeInfinity) - (valid, PositiveValid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.NegativeInfinity; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, NegativeInfinity) - (valid, NegativeValid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.NegativeInfinity; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, NaN) - (valid, Valid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.NaN; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); } [Fact] public static void RunTests_InvalidRealValues() { double realFirst; double imgFirst; double realSecond; double imgSecond; // Verify with (PositiveInfinity, valid) - (PositiveValid, valid) realFirst = double.PositiveInfinity; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (PositiveInfinity, valid) - (NegativeValid, valid) realFirst = double.PositiveInfinity; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (NegativeInfinity, valid) - (PositiveValid, valid) realFirst = double.NegativeInfinity; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (NegativeInfinity, valid) - (NegativeValid, valid) realFirst = double.NegativeInfinity; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (NaN, valid) - (valid, valid) realFirst = double.NaN; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryMinusResult(realFirst, imgFirst, realSecond, imgSecond); } } }
using System; using System.IO; using System.Reflection; using System.Runtime.Versioning; using Microsoft.Build.Shared; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using Shouldly; using Xunit; namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests { public class ResolveAssemblyReferenceCacheSerialization : IDisposable { // Maintain this two in sync with the constant in SystemState private static readonly byte[] TranslateContractSignature = { (byte)'M', (byte)'B', (byte)'R', (byte)'S', (byte)'C' }; // Microsoft Build RAR State Cache private static readonly byte TranslateContractVersion = 0x01; private readonly string _rarCacheFile; private readonly TaskLoggingHelper _taskLoggingHelper; public ResolveAssemblyReferenceCacheSerialization() { var tempPath = Path.GetTempPath(); _rarCacheFile = Path.Combine(tempPath, Guid.NewGuid() + ".UnitTest.RarCache"); _taskLoggingHelper = new TaskLoggingHelper(new MockEngine(), "TaskA") { TaskResources = AssemblyResources.PrimaryResources }; } public void Dispose() { if (File.Exists(_rarCacheFile)) { FileUtilities.DeleteNoThrow(_rarCacheFile); } } [Fact] public void RoundTripEmptyState() { SystemState systemState = new(); systemState.SerializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); var deserialized = SystemState.DeserializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); deserialized.ShouldNotBeNull(); } [Fact] public void WrongFileSignature() { SystemState systemState = new(); for (int i = 0; i < TranslateContractSignature.Length; i++) { systemState.SerializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); using (var cacheStream = new FileStream(_rarCacheFile, FileMode.Open, FileAccess.ReadWrite)) { cacheStream.Seek(i, SeekOrigin.Begin); cacheStream.WriteByte(0); cacheStream.Close(); } var deserialized = SystemState.DeserializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); deserialized.ShouldBeNull(); } } [Fact] public void WrongFileVersion() { SystemState systemState = new(); systemState.SerializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); using (var cacheStream = new FileStream(_rarCacheFile, FileMode.Open, FileAccess.ReadWrite)) { cacheStream.Seek(TranslateContractSignature.Length, SeekOrigin.Begin); cacheStream.WriteByte((byte) (TranslateContractVersion + 1)); cacheStream.Close(); } var deserialized = SystemState.DeserializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); deserialized.ShouldBeNull(); } [Fact] public void CorrectFileSignature() { SystemState systemState = new(); for (int i = 0; i < TranslateContractSignature.Length; i++) { systemState.SerializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); using (var cacheStream = new FileStream(_rarCacheFile, FileMode.Open, FileAccess.ReadWrite)) { cacheStream.Seek(i, SeekOrigin.Begin); cacheStream.WriteByte(TranslateContractSignature[i]); cacheStream.Close(); } var deserialized = SystemState.DeserializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); deserialized.ShouldNotBeNull(); } } [Fact] public void CorrectFileVersion() { SystemState systemState = new(); systemState.SerializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); using (var cacheStream = new FileStream(_rarCacheFile, FileMode.Open, FileAccess.ReadWrite)) { cacheStream.Seek(TranslateContractSignature.Length, SeekOrigin.Begin); cacheStream.WriteByte(TranslateContractVersion); cacheStream.Close(); } var deserialized = SystemState.DeserializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); deserialized.ShouldNotBeNull(); } [Fact] public void VerifySampleStateDeserialization() { // This test might also fail when binary format is modified. // Any change in SystemState and child class ITranslatable implementation will most probably make this fail. // To fix it, file referred by 'sampleName' needs to be recaptured and constant bellow modified to reflect // the content of that cache. // This sample was captured by compiling https://github.com/dotnet/roslyn/commit/f8107de2a94a01e96ac3d7c1f225acbb61e18830 const string sampleName = "Microsoft.VisualStudio.LanguageServices.Implementation.csprojAssemblyReference.cache"; const string expectedAssemblyPath = @"C:\Users\rokon\.nuget\packages\microsoft.visualstudio.codeanalysis.sdk.ui\15.8.27812-alpha\lib\net46\Microsoft.VisualStudio.CodeAnalysis.Sdk.UI.dll"; const long expectedAssemblyLastWriteTimeTicks = 636644382480000000; const string expectedAssemblyName = "Microsoft.VisualStudio.CodeAnalysis.Sdk.UI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; const string expectedFrameworkName = ".NETFramework,Version=v4.5"; var expectedDependencies = new[] { "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.CodeAnalysis, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.DeveloperTools, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Microsoft.VisualStudio.Shell.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.CodeAnalysis.Sdk, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.Build.Framework, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.Text.Logic, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.Text.UI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.Text.Data, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.Text.UI.Wpf, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.ComponentModelHost, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.VSHelp, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.Shell.Interop.11.0, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.VCProjectEngine, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.Shell.15.0, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.OLE.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Microsoft.VisualStudio.TextManager.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "EnvDTE80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Microsoft.VisualStudio.VirtualTreeGrid, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.Shell.Interop.8.0, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Microsoft.VisualStudio.Editor, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", }; CopyResourceSampleFileIntoRarCacheFile($@"AssemblyDependency\CacheFileSamples\{sampleName}"); var deserializedByTranslator = SystemState.DeserializeCacheByTranslator(_rarCacheFile, _taskLoggingHelper); deserializedByTranslator.ShouldNotBeNull(); deserializedByTranslator.SetGetLastWriteTime(path => { if (path != expectedAssemblyPath) throw new InvalidOperationException("Unexpected file name for this test case"); return new DateTime(expectedAssemblyLastWriteTimeTicks, DateTimeKind.Utc); }); GetAssemblyName getAssemblyName = deserializedByTranslator.CacheDelegate((GetAssemblyName)null); GetAssemblyMetadata getAssemblyMetadata = deserializedByTranslator.CacheDelegate((GetAssemblyMetadata)null); var assemblyName = getAssemblyName(expectedAssemblyPath); getAssemblyMetadata(expectedAssemblyPath, null, out AssemblyNameExtension[] dependencies, out string[] scatterFiles, out FrameworkName frameworkNameAttribute); assemblyName.ShouldNotBeNull(); assemblyName.ShouldBe(new AssemblyNameExtension(expectedAssemblyName, false)); scatterFiles.ShouldBeEmpty(); frameworkNameAttribute.ShouldBe(new FrameworkName(expectedFrameworkName)); dependencies.ShouldNotBeNull(); expectedDependencies.ShouldBe(expectedDependencies, ignoreOrder: true); } private void CopyResourceSampleFileIntoRarCacheFile(string name) { Assembly asm = this.GetType().Assembly; var resource = string.Format($"{asm.GetName().Name}.{name.Replace("\\", ".")}"); using Stream resourceStream = asm.GetManifestResourceStream(resource); if (resourceStream == null) throw new InvalidOperationException($"Resource '{resource}' has not been found."); using FileStream rarCacheFile = new FileStream(_rarCacheFile, FileMode.CreateNew); resourceStream.CopyTo(rarCacheFile); } } }
using System.Collections.Generic; using System.Runtime.Serialization; using Northwind.Common.ServiceModel; namespace Northwind.Common.DataModel { [DataContract] public class NorthwindDtoData { public static NorthwindDtoData Instance = new NorthwindDtoData(); [DataMember] public List<CategoryDto> Categories { get; set; } [DataMember] public List<CustomerDto> Customers { get; set; } [DataMember] public List<EmployeeDto> Employees { get; set; } [DataMember] public List<ShipperDto> Shippers { get; set; } [DataMember] public List<SupplierDto> Suppliers { get; set; } [DataMember] public List<OrderDto> Orders { get; set; } [DataMember] public List<ProductDto> Products { get; set; } [DataMember] public List<OrderDetailDto> OrderDetails { get; set; } [DataMember] public List<CustomerCustomerDemoDto> CustomerCustomerDemos { get; set; } [DataMember] public List<RegionDto> Regions { get; set; } [DataMember] public List<TerritoryDto> Territories { get; set; } [DataMember] public List<EmployeeTerritoryDto> EmployeeTerritories { get; set; } public static void LoadData(bool loadImages) { NorthwindData.LoadData(loadImages); Instance = new NorthwindDtoData { Categories = NorthwindData.Categories.ConvertAll(x => ToCategoryDto(x)), Customers = NorthwindData.Customers.ConvertAll(x => ToCustomerDto(x)), Employees = NorthwindData.Employees.ConvertAll(x => ToEmployeeDto(x)), Shippers = NorthwindData.Shippers.ConvertAll(x => ToShipperDto(x)), Suppliers = NorthwindData.Suppliers.ConvertAll(x => ToSupplierDto(x)), Orders = NorthwindData.Orders.ConvertAll(x => ToOrderDto(x)), Products = NorthwindData.Products.ConvertAll(x => ToProduct(x)), OrderDetails = NorthwindData.OrderDetails.ConvertAll(x => ToOrderDetailDto(x)), CustomerCustomerDemos = NorthwindData.CustomerCustomerDemos.ConvertAll(x => ToCustomerCustomerDemoDto(x)), Regions = NorthwindData.Regions.ConvertAll(x => ToRegionDto(x)), Territories = NorthwindData.Territories.ConvertAll(x => ToTerritoryDto(x)), EmployeeTerritories = NorthwindData.EmployeeTerritories.ConvertAll(x => ToEmployeeTerritoryDto(x)), }; } public static CategoryDto ToCategoryDto(Category model) { return new CategoryDto { CategoryName = model.CategoryName, Description = model.Description, Id = model.Id, Picture = model.Picture, }; } public static CustomerDto ToCustomerDto(Customer model) { return new CustomerDto { Id = model.Id, Picture = model.Picture, CompanyName = model.CompanyName, ContactName = model.ContactName, ContactTitle = model.ContactTitle, Fax = model.Fax, Phone = model.Phone, Address = model.Address, City = model.City, Country = model.Country, PostalCode = model.PostalCode, Region = model.Region, }; } public static EmployeeDto ToEmployeeDto(Employee model) { return new EmployeeDto { Id = model.Id, Address = model.Address, City = model.City, Country = model.Country, PostalCode = model.PostalCode, Region = model.Region, BirthDate = model.BirthDate, Extension = model.Extension, FirstName = model.FirstName, HireDate = model.HireDate, HomePhone = model.HomePhone, LastName = model.LastName, Notes = model.Notes, Photo = model.Photo, PhotoPath = model.PhotoPath, ReportsTo = model.ReportsTo, Title = model.Title, TitleOfCourtesy = model.TitleOfCourtesy, }; } public static ShipperDto ToShipperDto(Shipper model) { return new ShipperDto { Id = model.Id, CompanyName = model.CompanyName, Phone = model.Phone, }; } public static SupplierDto ToSupplierDto(Supplier model) { return new SupplierDto { Id = model.Id, CompanyName = model.CompanyName, ContactName = model.ContactName, ContactTitle = model.ContactTitle, Fax = model.Fax, Phone = model.Phone, Address = model.Address, City = model.City, Country = model.Country, PostalCode = model.PostalCode, Region = model.Region, HomePage = model.HomePage, }; } public static OrderDto ToOrderDto(Order model) { return new OrderDto { Id = model.Id, CustomerId = model.CustomerId, EmployeeId = model.EmployeeId, Freight = model.Freight, OrderDate = model.OrderDate, RequiredDate = model.RequiredDate, ShipAddress = model.ShipAddress, ShipCity = model.ShipCity, ShipCountry = model.ShipCountry, ShipName = model.ShipName, ShippedDate = model.ShippedDate, ShipPostalCode = model.ShipPostalCode, ShipRegion = model.ShipRegion, ShipVia = model.ShipVia, }; } public static ProductDto ToProduct(Product model) { return new ProductDto { Id = model.Id, CategoryId = model.CategoryId, Discontinued = model.Discontinued, ProductName = model.ProductName, QuantityPerUnit = model.QuantityPerUnit, ReorderLevel = model.ReorderLevel, SupplierId = model.SupplierId, UnitPrice = model.UnitPrice, UnitsInStock = model.UnitsInStock, UnitsOnOrder = model.UnitsOnOrder, }; } public static OrderDetailDto ToOrderDetailDto(OrderDetail model) { return new OrderDetailDto { Discount = model.Discount, OrderId = model.OrderId, ProductId = model.ProductId, Quantity = model.Quantity, UnitPrice = model.UnitPrice, }; } public static CustomerCustomerDemoDto ToCustomerCustomerDemoDto(CustomerCustomerDemo model) { return new CustomerCustomerDemoDto { Id = model.Id, CustomerTypeId = model.CustomerTypeId, }; } public static RegionDto ToRegionDto(Region model) { return new RegionDto { Id = model.Id, RegionDescription = model.RegionDescription, }; } public static TerritoryDto ToTerritoryDto(Territory model) { return new TerritoryDto { Id = model.Id, RegionId = model.RegionId, TerritoryDescription = model.TerritoryDescription, }; } public static EmployeeTerritoryDto ToEmployeeTerritoryDto(EmployeeTerritory model) { return new EmployeeTerritoryDto { EmployeeId = model.EmployeeId, TerritoryId = model.TerritoryId, }; } } }
/* * 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 Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace OpenSim.Services.Connectors { public class AssetServicesConnector : IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; private IImprovedAssetCache m_Cache = null; private int m_maxAssetRequestConcurrency = 30; private delegate void AssetRetrievedEx(AssetBase asset); // Keeps track of concurrent requests for the same asset, so that it's only loaded once. // Maps: Asset ID -> Handlers which will be called when the asset has been loaded private Dictionary<string, AssetRetrievedEx> m_AssetHandlers = new Dictionary<string, AssetRetrievedEx>(); public int MaxAssetRequestConcurrency { get { return m_maxAssetRequestConcurrency; } set { m_maxAssetRequestConcurrency = value; } } public AssetServicesConnector() { } public AssetServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public AssetServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig netconfig = source.Configs["Network"]; if (netconfig != null) m_maxAssetRequestConcurrency = netconfig.GetInt("MaxRequestConcurrency", m_maxAssetRequestConcurrency); IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini"); throw new Exception("Asset connector init error"); } string serviceURI = assetConfig.GetString("AssetServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[ASSET CONNECTOR]: No Server URI named in section AssetService"); throw new Exception("Asset connector init error"); } m_ServerURI = serviceURI; } protected void SetCache(IImprovedAssetCache cache) { m_Cache = cache; } public AssetBase Get(string id) { // m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Synchronous get request for {0}", id); string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { asset = SynchronousRestObjectRequester. MakeRequest<int, AssetBase>("GET", uri, 0, m_maxAssetRequestConcurrency); if (m_Cache != null) m_Cache.Cache(asset); } return asset; } public AssetBase GetCached(string id) { // m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Cache request for {0}", id); if (m_Cache != null) return m_Cache.Get(id); return null; } public AssetMetadata GetMetadata(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Metadata; } string uri = m_ServerURI + "/assets/" + id + "/metadata"; AssetMetadata asset = SynchronousRestObjectRequester. MakeRequest<int, AssetMetadata>("GET", uri, 0); return asset; } public byte[] GetData(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Data; } RestClient rc = new RestClient(m_ServerURI); rc.AddResourcePath("assets"); rc.AddResourcePath(id); rc.AddResourcePath("data"); rc.RequestMethod = "GET"; Stream s = rc.Request(); if (s == null) return null; if (s.Length > 0) { byte[] ret = new byte[s.Length]; s.Read(ret, 0, (int)s.Length); return ret; } return null; } public bool Get(string id, Object sender, AssetRetrieved handler) { // m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Potentially asynchronous get request for {0}", id); string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { lock (m_AssetHandlers) { AssetRetrievedEx handlerEx = new AssetRetrievedEx(delegate(AssetBase _asset) { handler(id, sender, _asset); }); AssetRetrievedEx handlers; if (m_AssetHandlers.TryGetValue(id, out handlers)) { // Someone else is already loading this asset. It will notify our handler when done. handlers += handlerEx; return true; } // Load the asset ourselves handlers += handlerEx; m_AssetHandlers.Add(id, handlers); } bool success = false; try { AsynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0, delegate(AssetBase a) { if (a != null && m_Cache != null) m_Cache.Cache(a); AssetRetrievedEx handlers; lock (m_AssetHandlers) { handlers = m_AssetHandlers[id]; m_AssetHandlers.Remove(id); } handlers.Invoke(a); }, m_maxAssetRequestConcurrency); success = true; } finally { if (!success) { lock (m_AssetHandlers) { m_AssetHandlers.Remove(id); } } } } else { handler(id, sender, asset); } return true; } public virtual bool[] AssetsExist(string[] ids) { string uri = m_ServerURI + "/get_assets_exist"; bool[] exist = null; try { exist = SynchronousRestObjectRequester.MakeRequest<string[], bool[]>("POST", uri, ids); } catch (Exception) { // This is most likely to happen because the server doesn't support this function, // so just silently return "doesn't exist" for all the assets. } if (exist == null) exist = new bool[ids.Length]; return exist; } public string Store(AssetBase asset) { if (asset.Local) { if (m_Cache != null) m_Cache.Cache(asset); return asset.ID; } string uri = m_ServerURI + "/assets/"; string newID; try { newID = SynchronousRestObjectRequester. MakeRequest<AssetBase, string>("POST", uri, asset); } catch (Exception e) { m_log.Warn(string.Format("[ASSET CONNECTOR]: Unable to send asset {0} to asset server. Reason: {1} ", asset.ID, e.Message), e); return string.Empty; } // TEMPORARY: SRAS returns 'null' when it's asked to store existing assets if (newID == null) { m_log.DebugFormat("[ASSET CONNECTOR]: Storing of asset {0} returned null; assuming the asset already exists", asset.ID); return asset.ID; } if (string.IsNullOrEmpty(newID)) return string.Empty; asset.ID = newID; if (m_Cache != null) m_Cache.Cache(asset); return newID; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { AssetMetadata metadata = GetMetadata(id); if (metadata == null) return false; asset = new AssetBase(metadata.FullID, metadata.Name, metadata.Type, UUID.Zero.ToString()); asset.Metadata = metadata; } asset.Data = data; string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester. MakeRequest<AssetBase, bool>("POST", uri, asset)) { if (m_Cache != null) m_Cache.Cache(asset); return true; } return false; } public bool Delete(string id) { string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester. MakeRequest<int, bool>("DELETE", uri, 0)) { if (m_Cache != null) m_Cache.Expire(id); return true; } return false; } } }
using ProGaudi.MsgPack.Light; using ProGaudi.Tarantool.Client.Model; using ProGaudi.Tarantool.Client.Utils; namespace ProGaudi.Tarantool.Client.Converters { internal class TupleConverter : IMsgPackConverter<TarantoolTuple> { private IMsgPackConverter<object> _nullConverter; public void Initialize(MsgPackContext context) { _nullConverter = context.NullConverter; } public void Write(TarantoolTuple value, IMsgPackWriter writer) { if (value == null) { _nullConverter.Write(null, writer); return; } writer.WriteArrayHeader(0); } public TarantoolTuple Read(IMsgPackReader reader) { var actual = reader.ReadArrayLength(); if (actual == null) { return null; } const uint expected = 0u; if (actual != expected) { throw ExceptionHelper.InvalidArrayLength(expected, actual); } return TarantoolTuple.Empty; } } public class TupleConverter<T1> : IMsgPackConverter<TarantoolTuple<T1>> { private IMsgPackConverter<object> _nullConverter; private IMsgPackConverter<T1> _t1Converter; public void Initialize(MsgPackContext context) { _nullConverter = context.NullConverter; _t1Converter = context.GetConverter<T1>(); } public void Write(TarantoolTuple<T1> value, IMsgPackWriter writer) { if (value == null) { _nullConverter.Write(null, writer); return; } writer.WriteArrayHeader(1); _t1Converter.Write(value.Item1, writer); } public TarantoolTuple<T1> Read(IMsgPackReader reader) { var actual = reader.ReadArrayLength(); if (actual == null) { return null; } const uint expected = 1u; if (actual != expected) { throw ExceptionHelper.InvalidArrayLength(expected, actual); } var item1 = _t1Converter.Read(reader); return TarantoolTuple.Create(item1); } } public class TupleConverter<T1, T2> : IMsgPackConverter<TarantoolTuple<T1, T2>> { private IMsgPackConverter<object> _nullConverter; private IMsgPackConverter<T1> _t1Converter; private IMsgPackConverter<T2> _t2Converter; public void Initialize(MsgPackContext context) { _nullConverter = context.NullConverter; _t1Converter = context.GetConverter<T1>(); _t2Converter = context.GetConverter<T2>(); } public void Write(TarantoolTuple<T1, T2> value, IMsgPackWriter writer) { if (value == null) { _nullConverter.Write(null, writer); return; } writer.WriteArrayHeader(2); _t1Converter.Write(value.Item1, writer); _t2Converter.Write(value.Item2, writer); } public TarantoolTuple<T1, T2> Read(IMsgPackReader reader) { var actual = reader.ReadArrayLength(); if (actual == null) { return null; } const uint expected = 2u; if (actual != expected) { throw ExceptionHelper.InvalidArrayLength(expected, actual); } var item1 = _t1Converter.Read(reader); var item2 = _t2Converter.Read(reader); return TarantoolTuple.Create(item1, item2); } } public class TupleConverter<T1, T2, T3> : IMsgPackConverter<TarantoolTuple<T1, T2, T3>> { private IMsgPackConverter<object> _nullConverter; private IMsgPackConverter<T1> _t1Converter; private IMsgPackConverter<T2> _t2Converter; private IMsgPackConverter<T3> _t3Converter; public void Initialize(MsgPackContext context) { _nullConverter = context.NullConverter; _t1Converter = context.GetConverter<T1>(); _t2Converter = context.GetConverter<T2>(); _t3Converter = context.GetConverter<T3>(); } public void Write(TarantoolTuple<T1, T2, T3> value, IMsgPackWriter writer) { if (value == null) { _nullConverter.Write(null, writer); return; } writer.WriteArrayHeader(3); _t1Converter.Write(value.Item1, writer); _t2Converter.Write(value.Item2, writer); _t3Converter.Write(value.Item3, writer); } public TarantoolTuple<T1, T2, T3> Read(IMsgPackReader reader) { var actual = reader.ReadArrayLength(); if (actual == null) { return null; } const uint expected = 3u; if (actual != expected) { throw ExceptionHelper.InvalidArrayLength(expected, actual); } var item1 = _t1Converter.Read(reader); var item2 = _t2Converter.Read(reader); var item3 = _t3Converter.Read(reader); return TarantoolTuple.Create(item1, item2, item3); } } public class TupleConverter<T1, T2, T3, T4> : IMsgPackConverter<TarantoolTuple<T1, T2, T3, T4>> { private IMsgPackConverter<object> _nullConverter; private IMsgPackConverter<T1> _t1Converter; private IMsgPackConverter<T2> _t2Converter; private IMsgPackConverter<T3> _t3Converter; private IMsgPackConverter<T4> _t4Converter; public void Initialize(MsgPackContext context) { _nullConverter = context.NullConverter; _t1Converter = context.GetConverter<T1>(); _t2Converter = context.GetConverter<T2>(); _t3Converter = context.GetConverter<T3>(); _t4Converter = context.GetConverter<T4>(); } public void Write(TarantoolTuple<T1, T2, T3, T4> value, IMsgPackWriter writer) { if (value == null) { _nullConverter.Write(null, writer); return; } writer.WriteArrayHeader(4); _t1Converter.Write(value.Item1, writer); _t2Converter.Write(value.Item2, writer); _t3Converter.Write(value.Item3, writer); _t4Converter.Write(value.Item4, writer); } public TarantoolTuple<T1, T2, T3, T4> Read(IMsgPackReader reader) { var actual = reader.ReadArrayLength(); if (actual == null) { return null; } const uint expected = 4u; if (actual != expected) { throw ExceptionHelper.InvalidArrayLength(expected, actual); } var item1 = _t1Converter.Read(reader); var item2 = _t2Converter.Read(reader); var item3 = _t3Converter.Read(reader); var item4 = _t4Converter.Read(reader); return TarantoolTuple.Create(item1, item2, item3, item4); } } public class TupleConverter<T1, T2, T3, T4, T5> : IMsgPackConverter<TarantoolTuple<T1, T2, T3, T4, T5>> { private IMsgPackConverter<object> _nullConverter; private IMsgPackConverter<T1> _t1Converter; private IMsgPackConverter<T2> _t2Converter; private IMsgPackConverter<T3> _t3Converter; private IMsgPackConverter<T4> _t4Converter; private IMsgPackConverter<T5> _t5Converter; public void Initialize(MsgPackContext context) { _nullConverter = context.NullConverter; _t1Converter = context.GetConverter<T1>(); _t2Converter = context.GetConverter<T2>(); _t3Converter = context.GetConverter<T3>(); _t4Converter = context.GetConverter<T4>(); _t5Converter = context.GetConverter<T5>(); } public void Write(TarantoolTuple<T1, T2, T3, T4, T5> value, IMsgPackWriter writer) { if (value == null) { _nullConverter.Write(null, writer); return; } writer.WriteArrayHeader(5); _t1Converter.Write(value.Item1, writer); _t2Converter.Write(value.Item2, writer); _t3Converter.Write(value.Item3, writer); _t4Converter.Write(value.Item4, writer); _t5Converter.Write(value.Item5, writer); } public TarantoolTuple<T1, T2, T3, T4, T5> Read(IMsgPackReader reader) { var actual = reader.ReadArrayLength(); if (actual == null) { return null; } const uint expected = 5u; if (actual != expected) { throw ExceptionHelper.InvalidArrayLength(expected, actual); } var item1 = _t1Converter.Read(reader); var item2 = _t2Converter.Read(reader); var item3 = _t3Converter.Read(reader); var item4 = _t4Converter.Read(reader); var item5 = _t5Converter.Read(reader); return TarantoolTuple.Create(item1, item2, item3, item4, item5); } } public class TupleConverter<T1, T2, T3, T4, T5, T6> : IMsgPackConverter<TarantoolTuple<T1, T2, T3, T4, T5, T6>> { private IMsgPackConverter<object> _nullConverter; private IMsgPackConverter<T1> _t1Converter; private IMsgPackConverter<T2> _t2Converter; private IMsgPackConverter<T3> _t3Converter; private IMsgPackConverter<T4> _t4Converter; private IMsgPackConverter<T5> _t5Converter; private IMsgPackConverter<T6> _t6Converter; public void Initialize(MsgPackContext context) { _nullConverter = context.NullConverter; _t1Converter = context.GetConverter<T1>(); _t2Converter = context.GetConverter<T2>(); _t3Converter = context.GetConverter<T3>(); _t4Converter = context.GetConverter<T4>(); _t5Converter = context.GetConverter<T5>(); _t6Converter = context.GetConverter<T6>(); } public void Write(TarantoolTuple<T1, T2, T3, T4, T5, T6> value, IMsgPackWriter writer) { if (value == null) { _nullConverter.Write(null, writer); return; } writer.WriteArrayHeader(6); _t1Converter.Write(value.Item1, writer); _t2Converter.Write(value.Item2, writer); _t3Converter.Write(value.Item3, writer); _t4Converter.Write(value.Item4, writer); _t5Converter.Write(value.Item5, writer); _t6Converter.Write(value.Item6, writer); } public TarantoolTuple<T1, T2, T3, T4, T5, T6> Read( IMsgPackReader reader) { var actual = reader.ReadArrayLength(); if (actual == null) { return null; } const uint expected = 6u; if (actual != expected) { throw ExceptionHelper.InvalidArrayLength(expected, actual); } var item1 = _t1Converter.Read(reader); var item2 = _t2Converter.Read(reader); var item3 = _t3Converter.Read(reader); var item4 = _t4Converter.Read(reader); var item5 = _t5Converter.Read(reader); var item6 = _t6Converter.Read(reader); return TarantoolTuple.Create(item1, item2, item3, item4, item5, item6); } } public class TupleConverter<T1, T2, T3, T4, T5, T6, T7> : IMsgPackConverter<TarantoolTuple<T1, T2, T3, T4, T5, T6, T7>> { private IMsgPackConverter<object> _nullConverter; private IMsgPackConverter<T1> _t1Converter; private IMsgPackConverter<T2> _t2Converter; private IMsgPackConverter<T3> _t3Converter; private IMsgPackConverter<T4> _t4Converter; private IMsgPackConverter<T5> _t5Converter; private IMsgPackConverter<T6> _t6Converter; private IMsgPackConverter<T7> _t7Converter; public void Initialize(MsgPackContext context) { _nullConverter = context.NullConverter; _t1Converter = context.GetConverter<T1>(); _t2Converter = context.GetConverter<T2>(); _t3Converter = context.GetConverter<T3>(); _t4Converter = context.GetConverter<T4>(); _t5Converter = context.GetConverter<T5>(); _t6Converter = context.GetConverter<T6>(); _t7Converter = context.GetConverter<T7>(); } public void Write(TarantoolTuple<T1, T2, T3, T4, T5, T6, T7> value, IMsgPackWriter writer) { if (value == null) { _nullConverter.Write(null, writer); return; } writer.WriteArrayHeader(7); _t1Converter.Write(value.Item1, writer); _t2Converter.Write(value.Item2, writer); _t3Converter.Write(value.Item3, writer); _t4Converter.Write(value.Item4, writer); _t5Converter.Write(value.Item5, writer); _t6Converter.Write(value.Item6, writer); _t7Converter.Write(value.Item7, writer); } public TarantoolTuple<T1, T2, T3, T4, T5, T6, T7> Read( IMsgPackReader reader) { var actual = reader.ReadArrayLength(); if (actual == null) { return null; } const uint expected = 7u; if (actual != expected) { throw ExceptionHelper.InvalidArrayLength(expected, actual); } var item1 = _t1Converter.Read(reader); var item2 = _t2Converter.Read(reader); var item3 = _t3Converter.Read(reader); var item4 = _t4Converter.Read(reader); var item5 = _t5Converter.Read(reader); var item6 = _t6Converter.Read(reader); var item7 = _t7Converter.Read(reader); return TarantoolTuple.Create(item1, item2, item3, item4, item5, item6, item7); } } public class TupleConverter<T1, T2, T3, T4, T5, T6, T7, TRest> : IMsgPackConverter<TarantoolTuple<T1, T2, T3, T4, T5, T6, T7, TRest>> { private IMsgPackConverter<object> _nullConverter; private IMsgPackConverter<T1> _t1Converter; private IMsgPackConverter<T2> _t2Converter; private IMsgPackConverter<T3> _t3Converter; private IMsgPackConverter<T4> _t4Converter; private IMsgPackConverter<T5> _t5Converter; private IMsgPackConverter<T6> _t6Converter; private IMsgPackConverter<T7> _t7Converter; private IMsgPackConverter<TRest> _t8Converter; public void Initialize(MsgPackContext context) { _nullConverter = context.NullConverter; _t1Converter = context.GetConverter<T1>(); _t2Converter = context.GetConverter<T2>(); _t3Converter = context.GetConverter<T3>(); _t4Converter = context.GetConverter<T4>(); _t5Converter = context.GetConverter<T5>(); _t6Converter = context.GetConverter<T6>(); _t7Converter = context.GetConverter<T7>(); _t8Converter = context.GetConverter<TRest>(); } public void Write(TarantoolTuple<T1, T2, T3, T4, T5, T6, T7, TRest> value, IMsgPackWriter writer) { if (value == null) { _nullConverter.Write(null, writer); return; } writer.WriteArrayHeader(8); _t1Converter.Write(value.Item1, writer); _t2Converter.Write(value.Item2, writer); _t3Converter.Write(value.Item3, writer); _t4Converter.Write(value.Item4, writer); _t5Converter.Write(value.Item5, writer); _t6Converter.Write(value.Item6, writer); _t7Converter.Write(value.Item7, writer); _t8Converter.Write(value.Item8, writer); } public TarantoolTuple<T1, T2, T3, T4, T5, T6, T7, TRest> Read( IMsgPackReader reader) { var actual = reader.ReadArrayLength(); if (actual == null) { return null; } const uint expected = 8u; if (actual != expected) { throw ExceptionHelper.InvalidArrayLength(expected, actual); } var item1 = _t1Converter.Read(reader); var item2 = _t2Converter.Read(reader); var item3 = _t3Converter.Read(reader); var item4 = _t4Converter.Read(reader); var item5 = _t5Converter.Read(reader); var item6 = _t6Converter.Read(reader); var item7 = _t7Converter.Read(reader); var item8 = _t8Converter.Read(reader); return new TarantoolTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, item8); } } }
using System; using System.Collections.Generic; using System.Linq; using Qwack.Core.Basic; using Qwack.Core.Curves; using Qwack.Core.Instruments; using Qwack.Core.Instruments.Asset; using Qwack.Core.Instruments.Funding; using Qwack.Core.Models; using Qwack.Dates; using Qwack.Transport.BasicTypes; using Qwack.Utils.Parallel; namespace Qwack.Models.Calibrators { public class NewtonRaphsonAssetBasisCurveSolver : INewtonRaphsonAssetBasisCurveSolver { public double Tollerance { get; set; } = 0.00000001; public int MaxItterations { get; set; } = 1000; public int UsedItterations { get; set; } private const double JacobianBump = 0.0001; private DateTime _buildDate; private List<IAssetInstrument> _curveInstruments; private DateTime[] _pillars; private IIrCurve _discountCurve; private IPriceCurve _currentCurve; private IPriceCurve _baseCurve; private SparsePriceCurveType _sparseType; private PriceCurveType _curveType; private int _numberOfInstruments; private int _numberOfPillars; private double[] _currentGuess; private double[] _currentPVs; private double[][] _jacobian; private readonly ICurrencyProvider _currencyProvider; public NewtonRaphsonAssetBasisCurveSolver(ICurrencyProvider currencyProvider) => _currencyProvider = currencyProvider; public SparsePriceCurve SolveSparseCurve(List<IAssetInstrument> instruments, List<DateTime> pillars, IIrCurve discountCurve, IPriceCurve baseCurve, DateTime buildDate, SparsePriceCurveType curveType) { _curveInstruments = instruments; _pillars = pillars.ToArray(); _numberOfInstruments = _curveInstruments.Count; _numberOfPillars = pillars.Count; _discountCurve = discountCurve; _buildDate = buildDate; _baseCurve = baseCurve; _sparseType = curveType; _currentGuess = Enumerable.Repeat(0.0, _numberOfPillars).ToArray(); _currentCurve = new SparsePriceCurve(_buildDate, _pillars, _currentGuess, curveType, _currencyProvider); _currentPVs = ComputePVs(_currentCurve); ComputeJacobianSparse(); for (var i = 0; i < MaxItterations; i++) { ComputeNextGuess(); _currentCurve = new SparsePriceCurve(_buildDate, _pillars, _currentGuess, curveType, _currencyProvider); _currentPVs = ComputePVs(_currentCurve); if (_currentPVs.Max(x => System.Math.Abs(x)) < Tollerance) { UsedItterations = i + 1; break; } ComputeJacobianSparse(); } return (SparsePriceCurve)_currentCurve; } public BasicPriceCurve SolveCurve(IEnumerable<IAssetInstrument> instruments, List<DateTime> pillars, IIrCurve discountCurve, IPriceCurve baseCurve, DateTime buildDate, PriceCurveType curveType) { _curveInstruments = instruments.OrderBy(x => x.LastSensitivityDate).ToList(); _pillars = pillars.ToArray(); _numberOfInstruments = _curveInstruments.Count; _numberOfPillars = pillars.Count; _discountCurve = discountCurve; _buildDate = buildDate; _baseCurve = baseCurve; _curveType = curveType; _currentGuess = _curveInstruments.Select(x => InitialGuess(x)).ToArray(); //Enumerable.Repeat(0.0, _numberOfPillars).ToArray(); _currentCurve = new BasicPriceCurve(_buildDate, _pillars, _currentGuess, curveType, _currencyProvider); _currentPVs = ComputePVs(_currentCurve); ComputeJacobian(); for (var i = 0; i < MaxItterations; i++) { ComputeNextGuess(); if (_currentGuess.Any(x => double.IsNaN(x))) throw new Exception($"NaNs detected in solution at step {i}"); _currentCurve = new BasicPriceCurve(_buildDate, _pillars, _currentGuess, curveType, _currencyProvider); _currentPVs = ComputePVs(_currentCurve); if (_currentPVs.Max(x => System.Math.Abs(x)) < Tollerance) { UsedItterations = i + 1; break; } ComputeJacobian(); } return (BasicPriceCurve)_currentCurve; } private void ComputeNextGuess() { var jacobianMi = Math.Matrix.DoubleArrayFunctions.InvertMatrix(_jacobian); var deltaGuess = Math.Matrix.DoubleArrayFunctions.MatrixProduct(_currentPVs, jacobianMi); for (var j = 0; j < _numberOfInstruments; j++) { _currentGuess[j] -= deltaGuess[j]; } } private void ComputeJacobianSparse() { _jacobian = Math.Matrix.DoubleArrayFunctions.MatrixCreate(_numberOfPillars, _numberOfPillars); for (var i = 0; i < _numberOfPillars; i++) { _currentCurve = new SparsePriceCurve(_buildDate, _pillars, _currentGuess.Select((g, ix) => ix == i ? g + JacobianBump : g).ToArray(), _sparseType, _currencyProvider); var bumpedPVs = ComputePVs(_currentCurve); for (var j = 0; j < bumpedPVs.Length; j++) { _jacobian[i][j] = (bumpedPVs[j] - _currentPVs[j]) / JacobianBump; } } } private void ComputeJacobian() { _jacobian = Math.Matrix.DoubleArrayFunctions.MatrixCreate(_numberOfPillars, _numberOfPillars); ParallelUtils.Instance.For(0, _numberOfPillars, 1, i => //for (var i = 0; i < _numberOfPillars; i++) { var currentCurve = new BasicPriceCurve(_buildDate, _pillars, _currentGuess.Select((g, ix) => ix == i ? g + JacobianBump : g).ToArray(), _curveType, _currencyProvider); var bumpedPVs = ComputePVs(currentCurve); for (var j = 0; j < bumpedPVs.Length; j++) { _jacobian[i][j] = (bumpedPVs[j] - _currentPVs[j]) / JacobianBump; } }, false).Wait(); } private double[] ComputePVs(IPriceCurve priceCurve) { var o = new double[_numberOfInstruments]; for (var i = 0; i < o.Length; i++) { o[i] = BasisSwapPv(priceCurve, _curveInstruments[i], _discountCurve, _baseCurve); } return o; } public static double BasisSwapPv(IPriceCurve priceCurve, IAssetInstrument instrument, IIrCurve discountCurve, IPriceCurve baseCurve) { switch (instrument) { case AsianBasisSwap swap: var baseIsPay = (swap.PaySwaplets.First().AssetId == baseCurve.AssetId); var payCurve = baseIsPay ? baseCurve : priceCurve; var recCurve = baseIsPay ? priceCurve : baseCurve; var payPVs = swap.PaySwaplets.Select(s => (payCurve.GetAveragePriceForDates(s.FixingDates.AddPeriod(RollType.F, s.FixingCalendar, s.SpotLag)) - s.Strike) * (s.Direction == TradeDirection.Long ? 1.0 : -1.0) * s.Notional * discountCurve.GetDf(priceCurve.BuildDate, s.PaymentDate)); var recPVs = swap.RecSwaplets.Select(s => (recCurve.GetAveragePriceForDates(s.FixingDates.AddPeriod(RollType.F, s.FixingCalendar, s.SpotLag)) - s.Strike) * (s.Direction == TradeDirection.Long ? 1.0 : -1.0) * s.Notional * discountCurve.GetDf(priceCurve.BuildDate, s.PaymentDate)); return payPVs.Sum() + recPVs.Sum(); case Future fut: var fwd = priceCurve.GetPriceForDate(fut.ExpiryDate); return (fwd - fut.Strike) * fut.ContractQuantity * fut.LotSize; default: throw new Exception("Unable to process instrument type in solver"); } } private double InitialGuess(IAssetInstrument instrument) { switch (instrument) { case AsianBasisSwap swap: var baseIsPay = (swap.PaySwaplets.First().AssetId == _baseCurve.AssetId); return baseIsPay ? _baseCurve.GetPriceForDate(swap.RecSwaplets.Last().LastSensitivityDate) : _baseCurve.GetPriceForDate(swap.PaySwaplets.Last().LastSensitivityDate); case Future fut: return _baseCurve.GetPriceForDate(fut.ExpiryDate); default: throw new Exception("Unable to process instrument type in solver"); } } } }
using System; using Avalonia.Controls.Diagnostics; using Avalonia.Controls.Metadata; using Avalonia.Controls.Primitives; namespace Avalonia.Controls { /// <summary> /// A control which pops up a hint when a control is hovered. /// </summary> /// <remarks> /// You will probably not want to create a <see cref="ToolTip"/> control directly: if added to /// the tree it will act as a simple <see cref="ContentControl"/> styled to look like a tooltip. /// To add a tooltip to a control, use the <see cref="TipProperty"/> attached property, /// assigning the content that you want displayed. /// </remarks> [PseudoClasses(":open")] public class ToolTip : ContentControl, IPopupHostProvider { /// <summary> /// Defines the ToolTip.Tip attached property. /// </summary> public static readonly AttachedProperty<object?> TipProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, object?>("Tip"); /// <summary> /// Defines the ToolTip.IsOpen attached property. /// </summary> public static readonly AttachedProperty<bool> IsOpenProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, bool>("IsOpen"); /// <summary> /// Defines the ToolTip.Placement property. /// </summary> public static readonly AttachedProperty<PlacementMode> PlacementProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, PlacementMode>("Placement", defaultValue: PlacementMode.Pointer); /// <summary> /// Defines the ToolTip.HorizontalOffset property. /// </summary> public static readonly AttachedProperty<double> HorizontalOffsetProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, double>("HorizontalOffset"); /// <summary> /// Defines the ToolTip.VerticalOffset property. /// </summary> public static readonly AttachedProperty<double> VerticalOffsetProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, double>("VerticalOffset", 20); /// <summary> /// Defines the ToolTip.ShowDelay property. /// </summary> public static readonly AttachedProperty<int> ShowDelayProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, int>("ShowDelay", 400); /// <summary> /// Stores the current <see cref="ToolTip"/> instance in the control. /// </summary> internal static readonly AttachedProperty<ToolTip?> ToolTipProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, ToolTip?>("ToolTip"); private IPopupHost? _popupHost; private Action<IPopupHost?>? _popupHostChangedHandler; /// <summary> /// Initializes static members of the <see cref="ToolTip"/> class. /// </summary> static ToolTip() { TipProperty.Changed.Subscribe(ToolTipService.Instance.TipChanged); IsOpenProperty.Changed.Subscribe(ToolTipService.Instance.TipOpenChanged); IsOpenProperty.Changed.Subscribe(IsOpenChanged); HorizontalOffsetProperty.Changed.Subscribe(RecalculatePositionOnPropertyChanged); VerticalOffsetProperty.Changed.Subscribe(RecalculatePositionOnPropertyChanged); PlacementProperty.Changed.Subscribe(RecalculatePositionOnPropertyChanged); } /// <summary> /// Gets the value of the ToolTip.Tip attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// The content to be displayed in the control's tooltip. /// </returns> public static object? GetTip(Control element) { return element.GetValue(TipProperty); } /// <summary> /// Sets the value of the ToolTip.Tip attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">The content to be displayed in the control's tooltip.</param> public static void SetTip(Control element, object? value) { element.SetValue(TipProperty, value); } /// <summary> /// Gets the value of the ToolTip.IsOpen attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating whether the tool tip is visible. /// </returns> public static bool GetIsOpen(Control element) { return element.GetValue(IsOpenProperty); } /// <summary> /// Sets the value of the ToolTip.IsOpen attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating whether the tool tip is visible.</param> public static void SetIsOpen(Control element, bool value) { element.SetValue(IsOpenProperty, value); } /// <summary> /// Gets the value of the ToolTip.Placement attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating how the tool tip is positioned. /// </returns> public static PlacementMode GetPlacement(Control element) { return element.GetValue(PlacementProperty); } /// <summary> /// Sets the value of the ToolTip.Placement attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating how the tool tip is positioned.</param> public static void SetPlacement(Control element, PlacementMode value) { element.SetValue(PlacementProperty, value); } /// <summary> /// Gets the value of the ToolTip.HorizontalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating how the tool tip is positioned. /// </returns> public static double GetHorizontalOffset(Control element) { return element.GetValue(HorizontalOffsetProperty); } /// <summary> /// Sets the value of the ToolTip.HorizontalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating how the tool tip is positioned.</param> public static void SetHorizontalOffset(Control element, double value) { element.SetValue(HorizontalOffsetProperty, value); } /// <summary> /// Gets the value of the ToolTip.VerticalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating how the tool tip is positioned. /// </returns> public static double GetVerticalOffset(Control element) { return element.GetValue(VerticalOffsetProperty); } /// <summary> /// Sets the value of the ToolTip.VerticalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating how the tool tip is positioned.</param> public static void SetVerticalOffset(Control element, double value) { element.SetValue(VerticalOffsetProperty, value); } /// <summary> /// Gets the value of the ToolTip.ShowDelay attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating the time, in milliseconds, before a tool tip opens. /// </returns> public static int GetShowDelay(Control element) { return element.GetValue(ShowDelayProperty); } /// <summary> /// Sets the value of the ToolTip.ShowDelay attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating the time, in milliseconds, before a tool tip opens.</param> public static void SetShowDelay(Control element, int value) { element.SetValue(ShowDelayProperty, value); } private static void IsOpenChanged(AvaloniaPropertyChangedEventArgs e) { var control = (Control)e.Sender; var newValue = (bool)e.NewValue!; ToolTip? toolTip; if (newValue) { var tip = GetTip(control); if (tip == null) return; toolTip = control.GetValue(ToolTipProperty); if (toolTip == null || (tip != toolTip && tip != toolTip.Content)) { toolTip?.Close(); toolTip = tip as ToolTip ?? new ToolTip { Content = tip }; control.SetValue(ToolTipProperty, toolTip); } toolTip.Open(control); } else { toolTip = control.GetValue(ToolTipProperty); toolTip?.Close(); } toolTip?.UpdatePseudoClasses(newValue); } private static void RecalculatePositionOnPropertyChanged(AvaloniaPropertyChangedEventArgs args) { var control = (Control)args.Sender; var tooltip = control.GetValue(ToolTipProperty); if (tooltip == null) { return; } tooltip.RecalculatePosition(control); } IPopupHost? IPopupHostProvider.PopupHost => _popupHost; event Action<IPopupHost?>? IPopupHostProvider.PopupHostChanged { add => _popupHostChangedHandler += value; remove => _popupHostChangedHandler -= value; } internal void RecalculatePosition(Control control) { _popupHost?.ConfigurePosition(control, GetPlacement(control), new Point(GetHorizontalOffset(control), GetVerticalOffset(control))); } private void Open(Control control) { Close(); _popupHost = OverlayPopupHost.CreatePopupHost(control, null); _popupHost.SetChild(this); ((ISetLogicalParent)_popupHost).SetParent(control); _popupHost.ConfigurePosition(control, GetPlacement(control), new Point(GetHorizontalOffset(control), GetVerticalOffset(control))); WindowManagerAddShadowHintChanged(_popupHost, false); _popupHost.Show(); _popupHostChangedHandler?.Invoke(_popupHost); } private void Close() { if (_popupHost != null) { _popupHost.SetChild(null); _popupHost.Dispose(); _popupHost = null; _popupHostChangedHandler?.Invoke(null); } } private void WindowManagerAddShadowHintChanged(IPopupHost host, bool hint) { if (host is PopupRoot pr) { pr.PlatformImpl?.SetWindowManagerAddShadowHint(hint); } } private void UpdatePseudoClasses(bool newValue) { PseudoClasses.Set(":open", newValue); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; namespace VoidEngine.Helpers { public static class MapHelper { /// <summary> /// Returns the formated array from a list of strings. /// '.' and ',' return 0. /// '1'-'9', 'a'-'z', 'A'-'Z', and all symbols on a english keyboard /// except ' and " will return 1 to 84 respectifully. /// </summary> public static uint[,] GetTileArray(List<string> lines) { uint[,] tileArray = new uint[lines[0].Length, lines.Count]; for (int i = 0; i < lines[0].Length; i++) { for (int j = 0; j < lines.Count; j++) { switch (lines[j][i]) { case '.': tileArray[i, j] = 0; break; case ' ': tileArray[i, j] = 0; break; case '1': tileArray[i, j] = 1; break; case '2': tileArray[i, j] = 2; break; case '3': tileArray[i, j] = 3; break; case '4': tileArray[i, j] = 4; break; case '5': tileArray[i, j] = 5; break; case '6': tileArray[i, j] = 6; break; case '7': tileArray[i, j] = 7; break; case '8': tileArray[i, j] = 8; break; case '9': tileArray[i, j] = 9; break; case 'a': tileArray[i, j] = 10; break; case 'b': tileArray[i, j] = 11; break; case 'c': tileArray[i, j] = 12; break; case 'd': tileArray[i, j] = 13; break; case 'e': tileArray[i, j] = 14; break; case 'f': tileArray[i, j] = 15; break; case 'g': tileArray[i, j] = 16; break; case 'h': tileArray[i, j] = 17; break; case 'i': tileArray[i, j] = 18; break; case 'j': tileArray[i, j] = 19; break; case 'k': tileArray[i, j] = 20; break; case 'l': tileArray[i, j] = 21; break; case 'm': tileArray[i, j] = 22; break; case 'n': tileArray[i, j] = 23; break; case 'o': tileArray[i, j] = 24; break; case 'p': tileArray[i, j] = 25; break; case 'q': tileArray[i, j] = 26; break; case 'r': tileArray[i, j] = 27; break; case 's': tileArray[i, j] = 28; break; case 't': tileArray[i, j] = 29; break; case 'u': tileArray[i, j] = 30; break; case 'v': tileArray[i, j] = 31; break; case 'w': tileArray[i, j] = 32; break; case 'x': tileArray[i, j] = 33; break; case 'y': tileArray[i, j] = 34; break; case 'z': tileArray[i, j] = 35; break; case 'A': tileArray[i, j] = 36; break; case 'B': tileArray[i, j] = 37; break; case 'C': tileArray[i, j] = 38; break; case 'D': tileArray[i, j] = 39; break; case 'E': tileArray[i, j] = 40; break; case 'F': tileArray[i, j] = 41; break; case 'G': tileArray[i, j] = 42; break; case 'H': tileArray[i, j] = 43; break; case 'I': tileArray[i, j] = 44; break; case 'J': tileArray[i, j] = 45; break; case 'K': tileArray[i, j] = 46; break; case 'L': tileArray[i, j] = 47; break; case 'M': tileArray[i, j] = 48; break; case 'N': tileArray[i, j] = 49; break; case 'O': tileArray[i, j] = 50; break; case 'P': tileArray[i, j] = 51; break; case 'Q': tileArray[i, j] = 52; break; case 'R': tileArray[i, j] = 53; break; case 'S': tileArray[i, j] = 54; break; case 'T': tileArray[i, j] = 55; break; case 'U': tileArray[i, j] = 56; break; case 'V': tileArray[i, j] = 57; break; case 'W': tileArray[i, j] = 58; break; case 'X': tileArray[i, j] = 58; break; case 'Y': tileArray[i, j] = 59; break; case 'Z': tileArray[i, j] = 60; break; case '!': tileArray[i, j] = 61; break; case '@': tileArray[i, j] = 62; break; case '#': tileArray[i, j] = 63; break; case '$': tileArray[i, j] = 64; break; case '*': tileArray[i, j] = 65; break; case '(': tileArray[i, j] = 66; break; case ')': tileArray[i, j] = 67; break; case '_': tileArray[i, j] = 68; break; case '-': tileArray[i, j] = 69; break; case '+': tileArray[i, j] = 70; break; case '=': tileArray[i, j] = 71; break; case '{': tileArray[i, j] = 72; break; case '}': tileArray[i, j] = 73; break; case '[': tileArray[i, j] = 74; break; case ']': tileArray[i, j] = 75; break; case '|': tileArray[i, j] = 76; break; case ':': tileArray[i, j] = 77; break; case ';': tileArray[i, j] = 78; break; case '<': tileArray[i, j] = 79; break; case ',': tileArray[i, j] = 80; break; case '>': tileArray[i, j] = 81; break; case '?': tileArray[i, j] = 82; break; case '/': tileArray[i, j] = 83; break; default: break; } } } return tileArray; } public static int[,] ImgToLevel(Texture2D texture) { int[,] tempIntArray = new int[texture.Width, texture.Height]; Color[] tempColorArray = new Color[texture.Width * texture.Height]; texture.GetData(tempColorArray); for (int i = 0; i < tempColorArray.Length; i++) { int x = i / texture.Width; int y = i % texture.Width; if (tempColorArray[i] == new Color(0, 0, 0, 0)) { tempIntArray[y, x] = 0; } if (tempColorArray[i] == new Color(128, 128, 128)) { tempIntArray[y, x] = 1; } if (tempColorArray[i] == new Color(0, 114, 70)) { tempIntArray[y, x] = 2; } if (tempColorArray[i] == new Color(200, 200, 200)) { tempIntArray[y, x] = 3; } if (tempColorArray[i] == new Color(64, 64, 64)) { tempIntArray[y, x] = 4; } if (tempColorArray[i] == new Color(255, 255, 0)) { tempIntArray[y, x] = 25; } if (tempColorArray[i] == new Color(0, 255, 255)) { tempIntArray[y, x] = 77; } if (tempColorArray[i] == new Color(68, 255, 78)) { tempIntArray[y, x] = 78; } if (tempColorArray[i] == new Color(174, 85, 167)) { tempIntArray[y, x] = 79; } if (tempColorArray[i] == new Color(255, 193, 86)) { tempIntArray[y, x] = 80; } if (tempColorArray[i] == new Color(249, 0, 0)) { tempIntArray[y, x] = 81; } if (tempColorArray[i] == new Color(255, 142, 217)) { tempIntArray[y, x] = 82; } } return tempIntArray; } } }
// SampSharp // Copyright 2017 Tim Potze // // 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.Linq; using System.Reflection; using SampSharp.GameMode.SAMP.Commands.PermissionCheckers; using SampSharp.GameMode.World; namespace SampSharp.GameMode.SAMP.Commands { /// <summary> /// Represents the default commands manager. /// </summary> public class CommandsManager : ICommandsManager { private static readonly Type[] SupportedReturnTypes = {typeof (bool), typeof (void)}; private readonly List<ICommand> _commands = new List<ICommand>(); /// <summary> /// Initializes a new instance of the <see cref="CommandsManager"/> class. /// </summary> /// <param name="gameMode">The game mode.</param> /// <exception cref="ArgumentNullException"></exception> public CommandsManager(BaseMode gameMode) { if (gameMode == null) throw new ArgumentNullException(nameof(gameMode)); GameMode = gameMode; } #region Implementation of IService /// <summary> /// Gets the game mode. /// </summary> public BaseMode GameMode { get; } #endregion /// <summary> /// Registers the specified command. /// </summary> /// <param name="commandPaths">The command paths.</param> /// <param name="displayName">The display name.</param> /// <param name="ignoreCase">if set to <c>true</c> ignore the case of the command.</param> /// <param name="permissionCheckers">The permission checkers.</param> /// <param name="method">The method.</param> /// <param name="usageMessage">The usage message.</param> public virtual void Register(CommandPath[] commandPaths, string displayName, bool ignoreCase, IPermissionChecker[] permissionCheckers, MethodInfo method, string usageMessage) { Register(CreateCommand(commandPaths, displayName, ignoreCase, permissionCheckers, method, usageMessage)); } /// <summary> /// Creates a command. /// </summary> /// <param name="commandPaths">The command paths.</param> /// <param name="displayName">The display name.</param> /// <param name="ignoreCase">if set to <c>true</c> ignore the case the command.</param> /// <param name="permissionCheckers">The permission checkers.</param> /// <param name="method">The method.</param> /// <param name="usageMessage">The usage message.</param> /// <returns>The created command</returns> protected virtual ICommand CreateCommand(CommandPath[] commandPaths, string displayName, bool ignoreCase, IPermissionChecker[] permissionCheckers, MethodInfo method, string usageMessage) { return new DefaultCommand(commandPaths, displayName, ignoreCase, permissionCheckers, method, usageMessage); } private static IPermissionChecker CreatePermissionChecker(Type type) { if (type == null || !typeof(IPermissionChecker).IsAssignableFrom(type)) return null; return Activator.CreateInstance(type) as IPermissionChecker; } private static IEnumerable<IPermissionChecker> GetCommandPermissionCheckers(Type type) { if (type == null || type == typeof(object)) yield break; foreach (var permissionChecker in GetCommandPermissionCheckers(type.DeclaringType)) yield return permissionChecker; foreach ( var permissionChecker in type.GetCustomAttributes<CommandGroupAttribute>() .Select(a => a.PermissionChecker) .Distinct() .Select(CreatePermissionChecker) .Where(c => c != null)) yield return permissionChecker; } private static IEnumerable<IPermissionChecker> GetCommandPermissionCheckers(MethodInfo method) { foreach (var permissionChecker in GetCommandPermissionCheckers(method.DeclaringType)) yield return permissionChecker; foreach ( var permissionChecker in method.GetCustomAttributes<CommandGroupAttribute>() .Select(a => a.PermissionChecker) .Concat(method.GetCustomAttributes<CommandAttribute>() .Select(a => a.PermissionChecker)) .Distinct() .Select(CreatePermissionChecker) .Where(c => c != null)) yield return permissionChecker; } private static IEnumerable<string> GetCommandGroupPaths(Type type) { if (type == null || type == typeof (object)) yield break; var count = 0; var groups = type.GetCustomAttributes<CommandGroupAttribute>() .SelectMany(a => a.Paths) .Select(g => g.Trim()) .Where(g => !string.IsNullOrEmpty(g)).ToArray(); foreach (var group in GetCommandGroupPaths(type.DeclaringType)) { if (groups.Length == 0) yield return group; else foreach (var g in groups) yield return $"{group} {g}"; count++; } if (count == 0) foreach (var g in groups) yield return g; } private static IEnumerable<string> GetCommandGroupPaths(MethodInfo method) { var count = 0; var groups = method.GetCustomAttributes<CommandGroupAttribute>() .SelectMany(a => a.Paths) .Select(g => g.Trim()) .Where(g => !string.IsNullOrEmpty(g)).ToArray(); foreach (var path in GetCommandGroupPaths(method.DeclaringType)) { if (groups.Length == 0) yield return path; else foreach (var g in groups) yield return $"{path} {g}"; count++; } if (count == 0) foreach (var g in groups) yield return g; } /// <summary> /// Gets the command for the specified command text. /// </summary> /// <param name="player">The player.</param> /// <param name="commandText">The command text.</param> /// <returns>The found command.</returns> public ICommand GetCommandForText(BasePlayer player, string commandText) { ICommand candidate = null; foreach (var command in _commands) { switch (command.CanInvoke(player, commandText)) { case CommandCallableResponse.True: return command; case CommandCallableResponse.Optional: candidate = command; break; } } return candidate; } #region Implementation of ICommandsManager /// <summary> /// Gets a read-only collection of all registered commands. /// </summary> public virtual IReadOnlyCollection<ICommand> Commands => _commands.AsReadOnly(); /// <summary> /// Loads all tagged commands from the assembly containing the specified type. /// </summary> /// <typeparam name="T">A type inside the assembly to load the commands form.</typeparam> public virtual void RegisterCommands<T>() where T : class { RegisterCommands(typeof (T)); } /// <summary> /// Loads all tagged commands from the assembly containing the specified type. /// </summary> /// <param name="typeInAssembly">A type inside the assembly to load the commands form.</param> public virtual void RegisterCommands(Type typeInAssembly) { if (typeInAssembly == null) throw new ArgumentNullException(nameof(typeInAssembly)); RegisterCommands(typeInAssembly.Assembly); } /// <summary> /// Loads all tagged commands from the specified <paramref name="assembly" />. /// </summary> /// <param name="assembly">The assembly to load the commands from.</param> public virtual void RegisterCommands(Assembly assembly) { foreach ( var method in assembly.GetTypes() // Get all classes in the specified assembly. .Where(type => !type.IsInterface && type.IsClass && !type.IsAbstract) // Select the methods in the type. .SelectMany( type => type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) // Exclude abstract methods. (none should be since abstract types are excluded) .Where(method => !method.IsAbstract) // Only include methods with a return type of bool or void. .Where(method => SupportedReturnTypes.Contains(method.ReturnType)) // Only include methods which have a command attribute. .Where(method => method.GetCustomAttribute<CommandAttribute>() != null) // Only include methods which are static and have a player as first argument -or- are a non-static member of a player derived class. .Where(DefaultCommand.IsValidCommandMethod) ) { var attribute = method.GetCustomAttribute<CommandAttribute>(); var commandPaths = GetCommandGroupPaths(method) .SelectMany(g => attribute.Names.Select(n => new CommandPath(g, n))) .ToList(); if (commandPaths.Count == 0) commandPaths.AddRange(attribute.Names.Select(n => new CommandPath(n))); if (!string.IsNullOrWhiteSpace(attribute.Shortcut)) commandPaths.Add(new CommandPath(attribute.Shortcut)); Register(commandPaths.ToArray(), attribute.DisplayName, attribute.IgnoreCase, GetCommandPermissionCheckers(method).ToArray(), method, attribute.UsageMessage); } } /// <summary> /// Registers the specified command. /// </summary> /// <param name="command">The command.</param> public virtual void Register(ICommand command) { if (command == null) throw new ArgumentNullException(nameof(command)); FrameworkLog.WriteLine(FrameworkMessageLevel.Debug, $"Registering command {command}"); _commands.Add(command); } /// <summary> /// Processes the specified player. /// </summary> /// <param name="commandText">The command text.</param> /// <param name="player">The player.</param> /// <returns>true if processed; false otherwise.</returns> public virtual bool Process(string commandText, BasePlayer player) { var command = GetCommandForText(player, commandText); return command != null && command.Invoke(player, commandText); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using PcapDotNet.Base; using PcapDotNet.Packets.Ethernet; namespace PcapDotNet.Packets.Dns { /// <summary> /// Represents a DNS layer. /// <seealso cref="DnsDatagram"/> /// </summary> public sealed class DnsLayer : SimpleLayer, IEquatable<DnsLayer> { /// <summary> /// A 16 bit identifier assigned by the program that generates any kind of query. /// This identifier is copied the corresponding reply and can be used by the requester to match up replies to outstanding queries. /// </summary> public ushort Id { get; set; } /// <summary> /// A one bit field that specifies whether this message is a query (0), or a response (1). /// </summary> public bool IsResponse { get; set; } /// <summary> /// Specifies whether this message is a query or a response. /// </summary> public bool IsQuery { get { return !IsResponse; } set { IsResponse = !value; } } /// <summary> /// Specifies kind of query in this message. /// This value is set by the originator of a query and copied into the response. /// </summary> public DnsOpCode OpCode { get; set; } /// <summary> /// This bit is valid in responses, and specifies that the responding name server is an authority for the domain name in question section. /// Note that the contents of the answer section may have multiple owner names because of aliases. /// The AA bit corresponds to the name which matches the query name, or the first owner name in the answer section. /// </summary> public bool IsAuthoritativeAnswer { get; set; } /// <summary> /// Specifies that this message was truncated due to length greater than that permitted on the transmission channel. /// </summary> public bool IsTruncated { get; set; } /// <summary> /// This bit may be set in a query and is copied into the response. /// If RD is set, it directs the name server to pursue the query recursively. /// Recursive query support is optional. /// </summary> public bool IsRecursionDesired { get; set; } /// <summary> /// This bit is set or cleared in a response, and denotes whether recursive query support is available in the name server. /// </summary> public bool IsRecursionAvailable { get; set; } /// <summary> /// Reserved for future use. /// Must be false in all queries and responses. /// </summary> public bool FutureUse { get; set; } /// <summary> /// The name server side of a security-aware recursive name server must not set the AD bit in a response /// unless the name server considers all RRsets in the Answer and Authority sections of the response to be authentic. /// The name server side should set the AD bit if and only if the resolver side considers all RRsets in the Answer section /// and any relevant negative response RRs in the Authority section to be authentic. /// The resolver side must follow the Authenticating DNS Responses procedure to determine whether the RRs in question are authentic. /// However, for backward compatibility, a recursive name server may set the AD bit when a response includes unsigned CNAME RRs /// if those CNAME RRs demonstrably could have been synthesized from an authentic DNAME RR that is also included in the response /// according to the synthesis rules described in RFC 2672. /// </summary> public bool IsAuthenticData { get; set; } /// <summary> /// Exists in order to allow a security-aware resolver to disable signature validation /// in a security-aware name server's processing of a particular query. /// /// The name server side must copy the setting of the CD bit from a query to the corresponding response. /// /// The name server side of a security-aware recursive name server must pass the state of the CD bit to the resolver side /// along with the rest of an initiating query, /// so that the resolver side will know whether it is required to verify the response data it returns to the name server side. /// If the CD bit is set, it indicates that the originating resolver is willing to perform whatever authentication its local policy requires. /// Thus, the resolver side of the recursive name server need not perform authentication on the RRsets in the response. /// When the CD bit is set, the recursive name server should, if possible, return the requested data to the originating resolver, /// even if the recursive name server's local authentication policy would reject the records in question. /// That is, by setting the CD bit, the originating resolver has indicated that it takes responsibility for performing its own authentication, /// and the recursive name server should not interfere. /// /// If the resolver side implements a BAD cache and the name server side receives a query that matches an entry in the resolver side's BAD cache, /// the name server side's response depends on the state of the CD bit in the original query. /// If the CD bit is set, the name server side should return the data from the BAD cache; /// if the CD bit is not set, the name server side must return RCODE 2 (server failure). /// /// The intent of the above rule is to provide the raw data to clients that are capable of performing their own signature verification checks /// while protecting clients that depend on the resolver side of a security-aware recursive name server to perform such checks. /// Several of the possible reasons why signature validation might fail involve conditions /// that may not apply equally to the recursive name server and the client that invoked it. /// For example, the recursive name server's clock may be set incorrectly, or the client may have knowledge of a relevant island of security /// that the recursive name server does not share. /// In such cases, "protecting" a client that is capable of performing its own signature validation from ever seeing the "bad" data does not help the client. /// </summary> public bool IsCheckingDisabled { get; set; } /// <summary> /// A response of the server that can sign errors or other messages. /// </summary> public DnsResponseCode ResponseCode { get; set; } /// <summary> /// The queries resource records. /// Typically exactly one query will exist. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IList<DnsQueryResourceRecord> Queries { get; set; } /// <summary> /// The answers resource records. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IList<DnsDataResourceRecord> Answers { get; set; } /// <summary> /// The authorities resource records. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IList<DnsDataResourceRecord> Authorities { get; set; } /// <summary> /// The additionals resource records. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IList<DnsDataResourceRecord> Additionals { get; set; } /// <summary> /// All the resource records by the order the will be written. /// </summary> public IEnumerable<DnsResourceRecord> ResourceRecords { get { return new IEnumerable<DnsResourceRecord>[] {Queries, Answers, Authorities, Additionals} .Where(records => records != null).Aggregate<IEnumerable<DnsResourceRecord>, IEnumerable<DnsResourceRecord>>( null, (current, records) => current == null ? records : current.Concat(records)); } } /// <summary> /// How to compress the domain names. /// </summary> public DnsDomainNameCompressionMode DomainNameCompressionMode { get; set; } /// <summary> /// The number of bytes this layer will take. /// </summary> public override int Length { get { return DnsDatagram.GetLength(ResourceRecords, DomainNameCompressionMode); } } /// <summary> /// Writes the layer to the buffer. /// </summary> /// <param name="buffer">The buffer to write the layer to.</param> /// <param name="offset">The offset in the buffer to start writing the layer at.</param> protected override void Write(byte[] buffer, int offset) { DnsDatagram.Write(buffer, offset, Id, IsResponse, OpCode, IsAuthoritativeAnswer, IsTruncated, IsRecursionDesired, IsRecursionAvailable, FutureUse, IsAuthenticData, IsCheckingDisabled, ResponseCode, Queries, Answers, Authorities, Additionals, DomainNameCompressionMode); } /// <summary> /// Finalizes the layer data in the buffer. /// Used for fields that must be calculated according to the layer's payload (like checksum). /// </summary> /// <param name="buffer">The buffer to finalize the layer in.</param> /// <param name="offset">The offset in the buffer the layer starts.</param> /// <param name="payloadLength">The length of the layer's payload (the number of bytes after the layer in the packet).</param> /// <param name="nextLayer">The layer that comes after this layer. null if this is the last layer.</param> public override void Finalize(byte[] buffer, int offset, int payloadLength, ILayer nextLayer) { } /// <summary> /// True iff the two objects are equal Layers. /// </summary> public bool Equals(DnsLayer other) { return other != null && Id.Equals(other.Id) && IsQuery.Equals(other.IsQuery) && OpCode.Equals(other.OpCode) && IsAuthoritativeAnswer.Equals(other.IsAuthoritativeAnswer) && IsTruncated.Equals(other.IsTruncated) && IsRecursionDesired.Equals(other.IsRecursionDesired) && IsRecursionAvailable.Equals(other.IsRecursionAvailable) && FutureUse.Equals(other.FutureUse) && IsAuthenticData.Equals(other.IsAuthenticData) && IsCheckingDisabled.Equals(other.IsCheckingDisabled) && ResponseCode.Equals(other.ResponseCode) && (Queries.IsNullOrEmpty() && other.Queries.IsNullOrEmpty() || Queries.SequenceEqual(other.Queries)) && (Answers.IsNullOrEmpty() && other.Answers.IsNullOrEmpty() || Answers.SequenceEqual(other.Answers)) && (Authorities.IsNullOrEmpty() && other.Authorities.IsNullOrEmpty() || Authorities.SequenceEqual(other.Authorities)) && (Additionals.IsNullOrEmpty() && other.Additionals.IsNullOrEmpty() || Additionals.SequenceEqual(other.Additionals)); } /// <summary> /// True iff the two objects are equal Layers. /// </summary> public override bool Equals(Layer other) { return Equals(other as DnsLayer); } } }
// // 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 Hyak.Common; using System; using System.Collections.Generic; namespace Microsoft.Azure.Management.Rdfe.Models { /// <summary> /// The List Subscription Operations operation response. /// </summary> public partial class SubscriptionListOperationsResponse : AzureOperationResponse { private string _continuationToken; /// <summary> /// Optional. The string that can be used to return the rest of the /// list. Subsequent requests must include this parameter to continue /// listing operations from where the last response left off. This /// element exists only if the complete list of subscription /// operations was not returned. /// </summary> public string ContinuationToken { get { return this._continuationToken; } set { this._continuationToken = value; } } private IList<SubscriptionListOperationsResponse.SubscriptionOperation> _subscriptionOperations; /// <summary> /// Optional. The list of operations that have been performed on the /// subscription during the specified timeframe. /// </summary> public IList<SubscriptionListOperationsResponse.SubscriptionOperation> SubscriptionOperations { get { return this._subscriptionOperations; } set { this._subscriptionOperations = value; } } /// <summary> /// Initializes a new instance of the /// SubscriptionListOperationsResponse class. /// </summary> public SubscriptionListOperationsResponse() { this.SubscriptionOperations = new LazyList<SubscriptionListOperationsResponse.SubscriptionOperation>(); } /// <summary> /// A collection of attributes that identify the source of the /// operation. /// </summary> public partial class OperationCallerDetails { private string _clientIPAddress; /// <summary> /// Optional. The IP address of the client computer that initiated /// the operation. This element is returned only if /// UsedServiceManagementApi is true. /// </summary> public string ClientIPAddress { get { return this._clientIPAddress; } set { this._clientIPAddress = value; } } private string _subscriptionCertificateThumbprint; /// <summary> /// Optional. The thumbprint of the subscription certificate used /// to initiate the operation. /// </summary> public string SubscriptionCertificateThumbprint { get { return this._subscriptionCertificateThumbprint; } set { this._subscriptionCertificateThumbprint = value; } } private bool _usedServiceManagementApi; /// <summary> /// Optional. Indicates whether the operation was initiated by /// using the Service Management API. This will be false if it was /// initiated by another source, such as the Management Portal. /// </summary> public bool UsedServiceManagementApi { get { return this._usedServiceManagementApi; } set { this._usedServiceManagementApi = value; } } private string _userEmailAddress; /// <summary> /// Optional. The email associated with the Windows Live ID of the /// user who initiated the operation from the Management Portal. /// This element is returned only if UsedServiceManagementApi is /// false. /// </summary> public string UserEmailAddress { get { return this._userEmailAddress; } set { this._userEmailAddress = value; } } /// <summary> /// Initializes a new instance of the OperationCallerDetails class. /// </summary> public OperationCallerDetails() { } } /// <summary> /// An operation that has been performed on the subscription during the /// specified timeframe. /// </summary> public partial class SubscriptionOperation { private SubscriptionListOperationsResponse.OperationCallerDetails _operationCaller; /// <summary> /// Optional. A collection of attributes that identify the source /// of the operation. /// </summary> public SubscriptionListOperationsResponse.OperationCallerDetails OperationCaller { get { return this._operationCaller; } set { this._operationCaller = value; } } private DateTime _operationCompletedTime; /// <summary> /// Optional. The time that the operation finished executing. /// </summary> public DateTime OperationCompletedTime { get { return this._operationCompletedTime; } set { this._operationCompletedTime = value; } } private string _operationId; /// <summary> /// Optional. The globally unique identifier (GUID) of the /// operation. /// </summary> public string OperationId { get { return this._operationId; } set { this._operationId = value; } } private string _operationName; /// <summary> /// Optional. The name of the performed operation. /// </summary> public string OperationName { get { return this._operationName; } set { this._operationName = value; } } private string _operationObjectId; /// <summary> /// Optional. The target object for the operation. This value is /// equal to the URL for performing an HTTP GET on the object, and /// corresponds to the same values for the ObjectIdFilter in the /// request. /// </summary> public string OperationObjectId { get { return this._operationObjectId; } set { this._operationObjectId = value; } } private IDictionary<string, string> _operationParameters; /// <summary> /// Optional. The collection of parameters for the performed /// operation. /// </summary> public IDictionary<string, string> OperationParameters { get { return this._operationParameters; } set { this._operationParameters = value; } } private DateTime _operationStartedTime; /// <summary> /// Optional. The time that the operation started to execute. /// </summary> public DateTime OperationStartedTime { get { return this._operationStartedTime; } set { this._operationStartedTime = value; } } private string _operationStatus; /// <summary> /// Optional. An object that contains information on the current /// status of the operation. The object returned has the following /// XML format: <OperationStatus> /// <ID>339c6c13-1f81-412f-9bc6-00e9c5876695</ID> /// <Status>Succeeded</Status> /// <HttpStatusCode>200</HttpStatusCode> </OperationStatus>. /// Possible values of the Status element, whichholds the /// operation status, are: Succeeded, Failed, or InProgress. /// </summary> public string OperationStatus { get { return this._operationStatus; } set { this._operationStatus = value; } } /// <summary> /// Initializes a new instance of the SubscriptionOperation class. /// </summary> public SubscriptionOperation() { this.OperationParameters = new LazyDictionary<string, string>(); } } } }
// 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.Threading; #if ES_BUILD_PCL using System.Threading.Tasks; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// Provides the ability to collect statistics through EventSource /// </summary> public class EventCounter { /// <summary> /// Initializes a new instance of the <see cref="EventCounter"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="eventSource">The event source.</param> public EventCounter(string name, EventSource eventSource) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (eventSource == null) { throw new ArgumentNullException(nameof(eventSource)); } InitializeBuffer(); _name = name; EventCounterGroup.AddEventCounter(eventSource, this); } /// <summary> /// Writes the metric. /// </summary> /// <param name="value">The value.</param> public void WriteMetric(float value) { Enqueue(value); } #region private implementation private readonly string _name; #region Buffer Management // Values buffering private const int BufferedSize = 10; private const float UnusedBufferSlotValue = float.NegativeInfinity; private const int UnsetIndex = -1; private volatile float[] _bufferedValues; private volatile int _bufferedValuesIndex; private void InitializeBuffer() { _bufferedValues = new float[BufferedSize]; for (int i = 0; i < _bufferedValues.Length; i++) { _bufferedValues[i] = UnusedBufferSlotValue; } } private void Enqueue(float value) { // It is possible that two threads read the same bufferedValuesIndex, but only one will be able to write the slot, so that is okay. int i = _bufferedValuesIndex; while (true) { float result = Interlocked.CompareExchange(ref _bufferedValues[i], value, UnusedBufferSlotValue); i++; if (_bufferedValues.Length <= i) { // It is possible that two threads both think the buffer is full, but only one get to actually flush it, the other // will eventually enter this code path and potentially calling Flushing on a buffer that is not full, and that's okay too. lock (_bufferedValues) { Flush(); } i = 0; } if (result == UnusedBufferSlotValue) { // CompareExchange succeeded _bufferedValuesIndex = i; return; } } } private void Flush() { for (int i = 0; i < _bufferedValues.Length; i++) { var value = Interlocked.Exchange(ref _bufferedValues[i], UnusedBufferSlotValue); if (value != UnusedBufferSlotValue) { OnMetricWritten(value); } } _bufferedValuesIndex = 0; } #endregion // Buffer Management #region Statistics Calculation // Statistics private int _count; private float _sum; private float _sumSquared; private float _min; private float _max; private void OnMetricWritten(float value) { _sum += value; _sumSquared += value * value; if (_count == 0 || value > _max) { _max = value; } if (_count == 0 || value < _min) { _min = value; } _count++; } internal EventCounterPayload GetEventCounterPayload() { lock (_bufferedValues) { Flush(); EventCounterPayload result = new EventCounterPayload(); result.Name = _name; result.Count = _count; result.Mean = _sum / _count; result.StandardDerivation = (float)Math.Sqrt(_sumSquared / _count - _sum * _sum / _count / _count); result.Min = _min; result.Max = _max; ResetStatistics(); return result; } } private void ResetStatistics() { _count = 0; _sum = 0; _sumSquared = 0; _min = 0; _max = 0; } #endregion // Statistics Calculation #endregion // private implementation } #region internal supporting classes [EventData] internal class EventCounterPayload : IEnumerable<KeyValuePair<string, object>> { public string Name { get; set; } public float Mean { get; set; } public float StandardDerivation { get; set; } public int Count { get; set; } public float Min { get; set; } public float Max { get; set; } public float IntervalSec { get; internal set; } #region Implementation of the IEnumerable interface public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return ForEnumeration.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ForEnumeration.GetEnumerator(); } private IEnumerable<KeyValuePair<string, object>> ForEnumeration { get { yield return new KeyValuePair<string, object>("Name", Name); yield return new KeyValuePair<string, object>("Mean", Mean); yield return new KeyValuePair<string, object>("StandardDerivation", StandardDerivation); yield return new KeyValuePair<string, object>("Count", Count); yield return new KeyValuePair<string, object>("Min", Min); yield return new KeyValuePair<string, object>("Max", Max); } } #endregion // Implementation of the IEnumerable interface } internal class EventCounterGroup : IDisposable { private readonly EventSource _eventSource; private readonly int _eventSourceIndex; private readonly List<EventCounter> _eventCounters; internal EventCounterGroup(EventSource eventSource, int eventSourceIndex) { _eventSource = eventSource; _eventSourceIndex = eventSourceIndex; _eventCounters = new List<EventCounter>(); RegisterCommandCallback(); } private void Add(EventCounter eventCounter) { _eventCounters.Add(eventCounter); } #region EventSource Command Processing private void RegisterCommandCallback() { _eventSource.EventCommandExecuted += OnEventSourceCommand; } private void OnEventSourceCommand(object sender, EventCommandEventArgs e) { if (e.Command == EventCommand.Enable || e.Command == EventCommand.Update) { string valueStr; float value; if (e.Arguments.TryGetValue("EventCounterIntervalSec", out valueStr) && float.TryParse(valueStr, out value)) { EnableTimer(value); } } } #endregion // EventSource Command Processing #region Global EventCounterGroup Array management private static EventCounterGroup[] s_eventCounterGroups; internal static void AddEventCounter(EventSource eventSource, EventCounter eventCounter) { int eventSourceIndex = EventListenerHelper.EventSourceIndex(eventSource); EventCounterGroup.EnsureEventSourceIndexAvailable(eventSourceIndex); EventCounterGroup eventCounterGroup = GetEventCounterGroup(eventSource); eventCounterGroup.Add(eventCounter); } private static void EnsureEventSourceIndexAvailable(int eventSourceIndex) { if (EventCounterGroup.s_eventCounterGroups == null) { EventCounterGroup.s_eventCounterGroups = new EventCounterGroup[eventSourceIndex + 1]; } else if (eventSourceIndex >= EventCounterGroup.s_eventCounterGroups.Length) { EventCounterGroup[] newEventCounterGroups = new EventCounterGroup[eventSourceIndex + 1]; Array.Copy(EventCounterGroup.s_eventCounterGroups, 0, newEventCounterGroups, 0, EventCounterGroup.s_eventCounterGroups.Length); EventCounterGroup.s_eventCounterGroups = newEventCounterGroups; } } private static EventCounterGroup GetEventCounterGroup(EventSource eventSource) { int eventSourceIndex = EventListenerHelper.EventSourceIndex(eventSource); EventCounterGroup result = EventCounterGroup.s_eventCounterGroups[eventSourceIndex]; if (result == null) { result = new EventCounterGroup(eventSource, eventSourceIndex); EventCounterGroup.s_eventCounterGroups[eventSourceIndex] = result; } return result; } #endregion // Global EventCounterGroup Array management #region Timer Processing private DateTime _timeStampSinceCollectionStarted; private int _pollingIntervalInMilliseconds; private Timer _pollingTimer; private void EnableTimer(float pollingIntervalInSeconds) { if (pollingIntervalInSeconds == 0) { if (_pollingTimer != null) { _pollingTimer.Dispose(); _pollingTimer = null; } _pollingIntervalInMilliseconds = 0; } else if (_pollingIntervalInMilliseconds == 0 || pollingIntervalInSeconds < _pollingIntervalInMilliseconds) { _pollingIntervalInMilliseconds = (int)(pollingIntervalInSeconds * 1000); if (_pollingTimer != null) { _pollingTimer.Dispose(); _pollingTimer = null; } _timeStampSinceCollectionStarted = DateTime.Now; _pollingTimer = new Timer(OnTimer, null, _pollingIntervalInMilliseconds, _pollingIntervalInMilliseconds); } } private void OnTimer(object state) { if (_eventSource.IsEnabled()) { DateTime now = DateTime.Now; TimeSpan elapsed = now - _timeStampSinceCollectionStarted; lock (_pollingTimer) { foreach (var eventCounter in _eventCounters) { EventCounterPayload payload = eventCounter.GetEventCounterPayload(); payload.IntervalSec = (float)elapsed.TotalSeconds; _eventSource.Write("EventCounters", new EventSourceOptions() { Level = EventLevel.LogAlways }, new { Payload = payload }); } _timeStampSinceCollectionStarted = now; } } else { _pollingTimer.Dispose(); _pollingTimer = null; EventCounterGroup.s_eventCounterGroups[_eventSourceIndex] = null; } } #region PCL timer hack #if ES_BUILD_PCL internal delegate void TimerCallback(object state); internal sealed class Timer : CancellationTokenSource, IDisposable { private int _period; private TimerCallback _callback; private object _state; internal Timer(TimerCallback callback, object state, int dueTime, int period) { _callback = callback; _state = state; _period = period; Schedule(dueTime); } private void Schedule(int dueTime) { Task.Delay(dueTime, Token).ContinueWith(OnTimer, null, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); } private void OnTimer(Task t, object s) { Schedule(_period); _callback(_state); } public new void Dispose() { base.Cancel(); } } #endif #endregion // PCL timer hack #endregion // Timer Processing #region Implementation of the IDisposable interface private bool _disposed = false; public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { if (_pollingTimer != null) { _pollingTimer.Dispose(); _pollingTimer = null; } } _disposed = true; } #endregion // Implementation of the IDisposable interface } // This class a work-around because .NET V4.6.2 did not make EventSourceIndex public (it was only protected) // We make this helper class to get around that protection. We want V4.6.3 to make this public at which // point this class is no longer needed and can be removed. internal class EventListenerHelper : EventListener { public new static int EventSourceIndex(EventSource eventSource) { return EventListener.EventSourceIndex(eventSource); } protected override void OnEventWritten(EventWrittenEventArgs eventData) { } // override abstact methods to keep compiler happy } #endregion // internal supporting classes }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Edubase.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* The MIT License(MIT) ===================== Copyright(c) 2008, Cagatay Dogan Permission is hereby granted, free of charge, to any person obtaining a cop of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the right to use, copy, modify, merge, publish, distribute, sublicense, and/or sel 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 O IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL TH AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHE 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 I THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Xml; using Sweet.BRE; namespace Sweet.BRETest { class Program { private delegate void RunTestMethod(out IRuleset rs, out IFactList facts, out IVariableList vars, out IRuleDebugger debugger); private delegate IProject ProjectMethod(); private class Test { public string Name; public RunTestMethod RunMethod; public ProjectMethod ProjectMethod; } private class NativeTest { public string Name; public Action RunMethod; } private static List<Test> testMethods = new List<Test>(); private static List<NativeTest> nativeTestMethods = new List<NativeTest>(); private static ConsoleKey GetTestKey() { while (true) { ConsoleKey key = Console.ReadKey(true).Key; if (key == ConsoleKey.Escape) { return key; } int testNo = (int)key; if (testNo >= (int)ConsoleKey.D1 && testNo <= ((int)ConsoleKey.D0 + testMethods.Count)) { testNo -= (int)ConsoleKey.D1; return (ConsoleKey)testNo; } if (testNo >= (int)ConsoleKey.NumPad1 && testNo <= ((int)ConsoleKey.NumPad0 + testMethods.Count)) { testNo -= (int)ConsoleKey.NumPad1; return (ConsoleKey)testNo; } } } private static ConsoleKey GetNativeTestKey() { while (true) { ConsoleKey key = Console.ReadKey(true).Key; if (key == ConsoleKey.Escape) { return key; } int testNo = (int)key; if (testNo >= (int)ConsoleKey.D1 && testNo <= ((int)ConsoleKey.D0 + nativeTestMethods.Count)) { testNo -= (int)ConsoleKey.D1; return (ConsoleKey)testNo; } if (testNo >= (int)ConsoleKey.NumPad1 && testNo <= ((int)ConsoleKey.NumPad0 + nativeTestMethods.Count)) { testNo -= (int)ConsoleKey.NumPad1; return (ConsoleKey)testNo; } } } private static ConsoleKey GetTypeKey() { while (true) { ConsoleKey key = Console.ReadKey(true).Key; if (key == ConsoleKey.Escape) { return key; } int testNo = (int)key; if (testNo == (int)ConsoleKey.D1 || testNo == (int)ConsoleKey.D2 || testNo == (int)ConsoleKey.D3) { testNo -= (int)ConsoleKey.D1; return (ConsoleKey)testNo; } if (testNo == (int)ConsoleKey.NumPad1 || testNo == (int)ConsoleKey.NumPad2 || testNo == (int)ConsoleKey.NumPad3) { testNo -= (int)ConsoleKey.NumPad1; return (ConsoleKey)testNo; } } } static void Main(string[] args) { testMethods.Add(new Test { Name = "Fahrenheit to Celcius Test", RunMethod = FahrenheitToCelciusTest, ProjectMethod = FahrenheitToCelciusTestProject }); testMethods.Add(new Test { Name = "Celcius to Fahrenheit Test", RunMethod = CelciusToFahrenheitTest, ProjectMethod = CelciusToFahrenheitTestProject }); testMethods.Add(new Test { Name = "Index Test", RunMethod = IndexTest, ProjectMethod = IndexTestProject }); testMethods.Add(new Test { Name = "Reflection Test", RunMethod = ReflectionTest, ProjectMethod = ReflectionTestProject }); testMethods.Add(new Test { Name = "Try & Catch Test", RunMethod = TryCatchTest, ProjectMethod = TryCatchTestProject }); testMethods.Add(new Test { Name = "General Test", RunMethod = GeneralTest, ProjectMethod = GeneralTestProject }); testMethods.Add(new Test { Name = "Save Test", RunMethod = SaveTest, ProjectMethod = SaveTestProject }); nativeTestMethods.Add(new NativeTest { Name = "Fahrenheit to Celcius Test", RunMethod = FahrenheitToCelciusNativeTest }); nativeTestMethods.Add(new NativeTest { Name = "Celcius to Fahrenheit Test", RunMethod = CelciusToFahrenheitNativeTest }); while (true) { Console.Clear(); Console.WriteLine("Select an action:"); Console.WriteLine("--------------------------------"); Console.WriteLine("1. Run project"); Console.WriteLine("2. Run native projects"); Console.WriteLine("3. Print project"); Console.WriteLine("--------------------------------"); Console.WriteLine("Press ESC to exit or select the test to run..."); Console.WriteLine(); ConsoleKey key = GetTypeKey(); if (key == ConsoleKey.Escape) break; int testNo = (int)key; if (testNo == 0) { RunTests(); } else if (testNo == 1) { RunNativeTests(); } else { PrintTests(); } } } private static void RunNativeTests() { while (true) { Console.Clear(); Console.WriteLine("RUN NATIVE"); Console.WriteLine("--------------------------------"); for (int i = 0; i < nativeTestMethods.Count; i++) { Console.WriteLine("{0}. {1}", i + 1, nativeTestMethods[i].Name); } Console.WriteLine("--------------------------------"); Console.WriteLine("Press ESC to exit or select the test to run..."); Console.WriteLine(); ConsoleKey key = GetNativeTestKey(); if (key == ConsoleKey.Escape) break; int testNo = (int)key; Console.WriteLine("Test: " + nativeTestMethods[testNo].Name); Console.WriteLine("--------------------------------"); try { Stopwatch sw = new Stopwatch(); sw.Start(); try { nativeTestMethods[testNo].RunMethod(); } finally { sw.Stop(); Console.WriteLine(); } Console.WriteLine("Eval time: {0} ms", sw.Elapsed.TotalMilliseconds); } catch (Exception e) { Console.WriteLine("Error:"); Console.WriteLine(e); } Console.WriteLine("--------------------------------"); Console.WriteLine("Press ESC to exit, any key to continue..."); if (Console.ReadKey(true).Key == ConsoleKey.Escape) break; } } private static void RunTests() { while (true) { Console.Clear(); Console.WriteLine("RUN"); Console.WriteLine("--------------------------------"); for (int i = 0; i < testMethods.Count; i++) { Console.WriteLine("{0}. {1}", i + 1, testMethods[i].Name); } Console.WriteLine("--------------------------------"); Console.WriteLine("Press ESC to exit or select the test to run..."); Console.WriteLine(); ConsoleKey key = GetTestKey(); if (key == ConsoleKey.Escape) break; int testNo = (int)key; Console.WriteLine("Test: " + testMethods[testNo].Name); Console.WriteLine("--------------------------------"); try { IRuleset rs; IFactList facts; IVariableList vars; IRuleDebugger debugger; Stopwatch sw = new Stopwatch(); sw.Start(); try { testMethods[testNo].RunMethod(out rs, out facts, out vars, out debugger); } finally { sw.Stop(); } if (!ReferenceEquals(rs, null)) { using (IEvaluationContext ec = RuleEngineRuntime.Initialize((Ruleset)rs, debugger)) { ec.StopOnError = true; try { sw.Reset(); sw.Start(); ec.Evaluate(facts, vars); } finally { sw.Stop(); Console.WriteLine(); } } } Console.WriteLine("Eval time: {0} ms", sw.Elapsed.TotalMilliseconds); } catch (Exception e) { Console.WriteLine("Error:"); Console.WriteLine(e); } Console.WriteLine("--------------------------------"); Console.WriteLine("Press ESC to exit, any key to continue..."); if (Console.ReadKey(true).Key == ConsoleKey.Escape) break; } } private static void PrintTests() { while (true) { Console.Clear(); Console.WriteLine("PRINT"); Console.WriteLine("--------------------------------"); for (int i = 0; i < testMethods.Count; i++) { Console.WriteLine("{0}. {1}", i + 1, testMethods[i].Name); } Console.WriteLine("--------------------------------"); Console.WriteLine("Press ESC to exit or select the test to print..."); Console.WriteLine(); ConsoleKey key = GetTestKey(); if (key == ConsoleKey.Escape) break; int testNo = (int)key; Console.Clear(); Console.WriteLine("Project: " + testMethods[testNo].Name); Console.WriteLine("--------------------------------"); try { IProject project = testMethods[testNo].ProjectMethod(); if (!ReferenceEquals(project, null)) { Console.WriteLine(project); } } catch (Exception e) { Console.WriteLine("Error:"); Console.WriteLine(e); } Console.WriteLine("--------------------------------"); Console.WriteLine("Press ESC to exit, any key to continue..."); if (Console.ReadKey(true).Key == ConsoleKey.Escape) break; } } private static IProject IndexTestProject() { IProject project = Project.As() .RegisterFunctionAlias("Month name", "MonthName") .RegisterFunctionAlias("Convert to string", "String") .RegisterFunctionAlias("Write to console", "WriteLn"); project .DefineRuleset("main") .DefineRule("2").Do( ((FunctionStm)"Write to console") .Params( Predef.Round( DivideStm.As((FactStm)"celcius" * 9, 5) + 32, 2, "awayFromZero" ) ) ) .SetSubPriority(46) .Ruleset .DefineRule("1").Do( ((FunctionStm)"Write to console") .Params( ((FunctionStm)"Month name") .Params( ((FunctionStm)"Convert to string") .Params( ItemOfStm.As((FactStm)"fact1", 2) ) , "nl" ) ) ) ; return project; } private static void IndexTest(out IRuleset rs, out IFactList facts, out IVariableList vars, out IRuleDebugger debugger) { vars = null; List<object> list = new List<object>(new object[] { 1, "a", DateTime.Now, double.NaN }); facts = new FactList() .Set("fact1", list) .Set("celcius", 18); debugger = new DefaultRuleDebugger(delegate (DebugEventArgs e) { Console.WriteLine(e.Status); if (e.Error != null) { Console.WriteLine(e.Error); } }); rs = IndexTestProject().GetRuleset("main"); } private static void CelciusToFahrenheitNativeTest() { Dictionary<string, object> facts = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); facts["celcius"] = 18; facts["fahrenheit"] = 64; object obj; double celcius; double fahrenheit; facts.TryGetValue("celcius", out obj); celcius = Convert.ToDouble(obj); if (celcius == 18) { fahrenheit = Math.Round(((celcius * 9) / 5) + 32); Console.WriteLine(String.Format("Fahrenheit: ", fahrenheit)); } facts.TryGetValue("fahrenheit", out obj); fahrenheit = Convert.ToDouble(obj); if (fahrenheit == 64) { celcius = Math.Round((fahrenheit - 32) * 5 / 9); Console.WriteLine(String.Format("Celcius: ", celcius)); } } private static IProject CelciusToFahrenheitTestProject() { IProject project = Project.As(); project .DefineRuleset("main") .DefineRule("1") .When((FactStm)"celcius" == 18) .Do( Predef.PrintLine( "Fahrenheit: ", Predef.Round( DivideStm.As((FactStm)"celcius" * 9, 5) + 32, 2, "awayFromZero" ) ) ) .Ruleset .DefineRule("2") .When((FactStm)"fahrenheit" == (NumericStm)64) .Do( Predef.PrintLine( "Celcius: ", Predef.Round( MultiplyStm.As((FactStm)"fahrenheit" - 32, 5) / 9, 2, "awayFromZero" ) ) ) ; return project; } private static void CelciusToFahrenheitTest(out IRuleset rs, out IFactList facts, out IVariableList vars, out IRuleDebugger debugger) { vars = null; debugger = null; facts = new FactList() .Set("fahrenheit", 64) .Set("celcius", 18); rs = CelciusToFahrenheitTestProject().GetRuleset("main"); } private static void FahrenheitToCelciusNativeTest() { Dictionary<string, object> facts = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); facts["fahrenheit"] = 64.4; object obj; facts.TryGetValue("fahrenheit", out obj); double fahrenheit = Convert.ToDouble(obj); double celcius = Math.Round((fahrenheit - 32) * 5 / 9); Console.WriteLine(celcius); } private static IProject FahrenheitToCelciusTestProject() { IProject project = Project.As(); project .DefineRuleset("main") .DefineRule("main") .Do( Predef.Print( Predef.Round( (((FactStm)"fahrenheit" - 32) * 5) / 9, // MultiplyStm.As((FactStm)"fahrenheit" - 32, 5) / 9 2, "AwayFromZero" ) ) ) ; return project; } private static void FahrenheitToCelciusTest(out IRuleset rs, out IFactList facts, out IVariableList vars, out IRuleDebugger debugger) { vars = null; debugger = null; facts = new FactList() .Set("fahrenheit", 64.4); rs = FahrenheitToCelciusTestProject().GetRuleset("main"); } private static IProject ReflectionTestProject() { IProject project = Project.As(); project .DefineRuleset("main") .DefineRule("1") .Do( Predef.PrintLine( Predef.Format( "%fact3?", // "%fact3?" equals (FactStm)"fact3" "s" ) ) ) .Ruleset .DefineRule("2") .Do( Predef.PrintLine( ReflectionStm.As("%fact1?", // "%fact1?" equals (FactStm)"fact1" "[2].ToString('s').Replace('T', ' ').Split($0)[1].ToCharArray()[2]", "%fact2?") // "%fact2?" equals (FactStm)"fact2" ) ) ; return project; } private static void ReflectionTest(out IRuleset rs, out IFactList facts, out IVariableList vars, out IRuleDebugger debugger) { vars = null; debugger = null; DateTime now = DateTime.Now; List<object> list = new List<object>(new object[] { 1, "a", now, double.NaN }); facts = new FactList() .Set("fact1", list) .Set("fact2", new char[] { ' ' }) .Set("fact3", now); rs = ReflectionTestProject().GetRuleset("main"); } private static IProject TryCatchTestProject() { IProject project = Project.As(); project .DefineRuleset("main") .DefineRule("CelciusToFahrenheit") .Do( Predef.Print( Predef.Round( DivideStm.As((FactStm)"celcius" * 9, 5) + 32, 2, "awayFromZero" ) ) ) .Ruleset .DefineRule("TryCatch") .Do( TryStm.As() .Do( Predef.Print( (StringStm)"Fact1: " + ReflectionStm.As((FactStm)"fact1", "ToString()") ), RaiseErrorStm.As("test") ) .OnError( Predef.Print( "Status: " + ReflectionStm.As(Statement.Null, "Status") ), SetFactStm.As("error") .Set( ReflectionStm.As(ContextStm.As(), "GetLastError()") ), Predef.Print( ReflectionStm.As((FactStm)"error", (string)null) ) ) ); return project; } private static void TryCatchTest(out IRuleset rs, out IFactList facts, out IVariableList vars, out IRuleDebugger debugger) { vars = null; debugger = null; IProject project = TryCatchTestProject(); facts = new FactList() .Set("fact1", 7) .Set("project", project) .Set("celcius", 18); rs = project.GetRuleset("main"); } private static IProject GeneralTestProject() { IProject project = Project.As(); // table DecisionTable table = project.DefineDecisionTable("decisionTable1"); table.Conditions.Add("@var1", DecisionValueType.Integer); table.Conditions.Add("@var2", DecisionValueType.Integer); table.Conditions.Add("@var3", DecisionValueType.Integer); table.Actions.Add("@var1", DecisionValueType.Integer); table.Actions.Add("@var2", DecisionValueType.Integer); table.Actions.Add("@var3", DecisionValueType.Integer); table.Rows.Add(new string[] { "0", "0", "0" }, new string[] { "0", "0", "1" }); table.Rows.Add(new string[] { "0", "0", "1" }, new string[] { "0", "0", "2" }); table.Rows.Add(new string[] { "0", "0", "2" }, new string[] { "0", "1", "0" }); table.Rows.Add(new string[] { "0", "1", "0" }, new string[] { "0", "1", "1" }); table.Rows.Add(new string[] { "0", "1", "1" }, new string[] { "0", "1", "2" }); table.Rows.Add(new string[] { "0", "1", "2" }, new string[] { "0", "2", "0" }); table.Rows.Add(new string[] { "0", "2", "0" }, new string[] { "0", "2", "1" }); table.Rows.Add(new string[] { "0", "2", "1" }, new string[] { "0", "2", "2" }); table.Rows.Add(new string[] { "0", "2", "2" }, new string[] { "1", "0", "0" }); table.Rows.Add(new string[] { "1", "0", "0" }, new string[] { "1", "0", "1" }); table.Rows.Add(new string[] { "1", "0", "1" }, new string[] { "1", "0", "2" }); table.Rows.Add(new string[] { "1", "0", "2" }, new string[] { "1", "1", "0" }); table.Rows.Add(new string[] { "1", "1", "0" }, new string[] { "1", "1", "1" }); table.Rows.Add(new string[] { "1", "1", "1" }, new string[] { "1", "1", "2" }); table.Rows.Add(new string[] { "1", "1", "2" }, new string[] { "1", "2", "0" }); table.Rows.Add(new string[] { "1", "2", "0" }, new string[] { "1", "2", "1" }); table.Rows.Add(new string[] { "1", "2", "1" }, new string[] { "1", "2", "2" }); table.Rows.Add(new string[] { "1", "2", "2" }, new string[] { "2", "0", "0" }); table.Rows.Add(new string[] { "2", "0", "0" }, new string[] { "2", "0", "1" }); table.Rows.Add(new string[] { "2", "0", "1" }, new string[] { "2", "0", "2" }); table.Rows.Add(new string[] { "2", "0", "2" }, new string[] { "2", "1", "0" }); table.Rows.Add(new string[] { "2", "1", "0" }, new string[] { "2", "1", "1" }); table.Rows.Add(new string[] { "2", "1", "1" }, new string[] { "2", "1", "2" }); table.Rows.Add(new string[] { "2", "1", "2" }, new string[] { "2", "2", "0" }); table.Rows.Add(new string[] { "2", "2", "0" }, new string[] { "2", "2", "1" }); table.Rows.Add(new string[] { "2", "2", "1" }, new string[] { "2", "2", "2" }); table.Rows.Add(new string[] { "2", "2", "2" }, new string[] { "0", "0", "0" }); table.MergeCells(); // tree // row1 DecisionConditionNode tc1 = project.DefineDecisionTree("tree1"); tc1.SetVariable("@var1").SetValues(new string[] { "0" }); DecisionConditionNode tc2 = new DecisionConditionNode("@var2", new string[] { "0" }); tc1.SetOnMatch(tc2); DecisionActionNode ta1 = new DecisionActionNode("@var1", "0"); tc2.SetOnMatch(ta1); ta1.SetFurtherMore(new DecisionActionNode("@var2", "1")); // row2 DecisionConditionNode tc3 = new DecisionConditionNode("@var2", new string[] { "1" }); tc2.SetElse(tc3); DecisionActionNode ta2 = new DecisionActionNode("@var1", "1"); tc3.SetOnMatch(ta2); ta1.SetFurtherMore(new DecisionActionNode("@var2", "0")); // row3 DecisionConditionNode tc4 = new DecisionConditionNode("@var1", new string[] { "1" }); tc1.SetElse(tc4); DecisionConditionNode tc5 = new DecisionConditionNode("@var2", new string[] { "0" }); tc4.SetOnMatch(tc5); DecisionActionNode ta3 = new DecisionActionNode("@var1", "1"); tc5.SetOnMatch(ta3); ta3.SetFurtherMore(new DecisionActionNode("@var2", "1")); // row4 DecisionConditionNode tc6 = new DecisionConditionNode("@var2", new string[] { "1" }); tc5.SetElse(tc6); DecisionActionNode ta4 = new DecisionActionNode("@var1", "0"); tc6.SetOnMatch(ta4); ta4.SetFurtherMore(new DecisionActionNode("@var2", "0")); // ruleset project.DefineRuleset("main") .DefineRule("main") .Do( ForStm.As("i", 1000) .Do( EvaluateTableStm.As("DecisionTable1") ) .Do( EvaluateTreeStm.As("tree1") ) .Do( Predef.Printfln( "@var1: {0}, @var2: {1}, @var3: {2}", (VariableStm)"@var1", (VariableStm)"@var2", (VariableStm)"@var3" ) ) .Do( ContinueStm.As( (VariableStm)"Count" >= 1000 ) ) .Do( IfThenStm.As( (VariableStm)"VarA" > 0 ) .Then( ((SetVariableStm)"VarA") .Set( ArithmeticGroupStm.As((VariableStm)"VarA") .Add(2) .Subtract(1) ) ) ) .Do( IfThenStm.As( (VariableStm)"VarA" > 10 ) .Then( ((SetVariableStm)"VarA") .Set(1) ) ) .Do( ((SetVariableStm)"Count") .Set( ArithmeticGroupStm.As((VariableStm)"Count").Add(1) ) , Predef.PrintLine( "Count: " + (VariableStm)"Count" ) , Predef.PrintLine( "VarA: " + (VariableStm)"VarA" ) , Predef.Printfln( "Date: {0}, Count: {1}", Predef.AddTimeToDate( (DateStm)"12.10.2005", (TimeStm)"1.23:45:56" ), (VariableStm)"Count" ) , Predef.PrintLine( "AddDate: " + Predef.AddDate( (DateStm)"12.10.2005", -2, -1, 3 ) ) ) ) ; return project; } private static void GeneralTest(out IRuleset rs, out IFactList facts, out IVariableList vars, out IRuleDebugger debugger) { vars = null; facts = null; debugger = null; vars = new VariableList() .Set("VarA", 7) .Set("Count", 0) .Set("@var1", 0) .Set("@var2", 0) .Set("@var3", 0); rs = GeneralTestProject().GetRuleset("main"); } private static IProject SaveTestProject() { IProject project = Project.As(); // Variables project.Variables .Set("@var1", (string)null) .Set("@var2", 1) .Set("@bool", true); // Function aliases project .RegisterFunctionAlias("Month name", "MonthName") .RegisterFunctionAlias("Convert to string", "String") .RegisterFunctionAlias("Write to console", "PrintLine"); // table DecisionTable table = project.DefineDecisionTable("decisionTable1"); table.Conditions.Add("@var1", DecisionValueType.Integer); table.Conditions.Add("@var2", DecisionValueType.Integer); table.Conditions.Add("@var3", DecisionValueType.Integer); table.Actions.Add("@var1", DecisionValueType.Integer); table.Actions.Add("@var2", DecisionValueType.Integer); table.Actions.Add("@var3", DecisionValueType.Integer); table.Rows.Add(new string[] { "0", "0", "0" }, new string[] { "0", "0", "1" }); table.Rows.Add(new string[] { "0", "0", "1" }, new string[] { "0", "0", "2" }); table.Rows.Add(new string[] { "0", "0", "2" }, new string[] { "0", "1", "0" }); table.Rows.Add(new string[] { "0", "1", "0" }, new string[] { "0", "1", "1" }); table.Rows.Add(new string[] { "0", "1", "1" }, new string[] { "0", "1", "2" }); table.Rows.Add(new string[] { "0", "1", "2" }, new string[] { "0", "2", "0" }); table.Rows.Add(new string[] { "0", "2", "0" }, new string[] { "0", "2", "1" }); table.Rows.Add(new string[] { "0", "2", "1" }, new string[] { "0", "2", "2" }); table.Rows.Add(new string[] { "0", "2", "2" }, new string[] { "1", "0", "0" }); table.Rows.Add(new string[] { "1", "0", "0" }, new string[] { "1", "0", "1" }); table.Rows.Add(new string[] { "1", "0", "1" }, new string[] { "1", "0", "2" }); table.Rows.Add(new string[] { "1", "0", "2" }, new string[] { "1", "1", "0" }); table.Rows.Add(new string[] { "1", "1", "0" }, new string[] { "1", "1", "1" }); table.Rows.Add(new string[] { "1", "1", "1" }, new string[] { "1", "1", "2" }); table.Rows.Add(new string[] { "1", "1", "2" }, new string[] { "1", "2", "0" }); table.Rows.Add(new string[] { "1", "2", "0" }, new string[] { "1", "2", "1" }); table.Rows.Add(new string[] { "1", "2", "1" }, new string[] { "1", "2", "2" }); table.Rows.Add(new string[] { "1", "2", "2" }, new string[] { "2", "0", "0" }); table.Rows.Add(new string[] { "2", "0", "0" }, new string[] { "2", "0", "1" }); table.Rows.Add(new string[] { "2", "0", "1" }, new string[] { "2", "0", "2" }); table.Rows.Add(new string[] { "2", "0", "2" }, new string[] { "2", "1", "0" }); table.Rows.Add(new string[] { "2", "1", "0" }, new string[] { "2", "1", "1" }); table.Rows.Add(new string[] { "2", "1", "1" }, new string[] { "2", "1", "2" }); table.Rows.Add(new string[] { "2", "1", "2" }, new string[] { "2", "2", "0" }); table.Rows.Add(new string[] { "2", "2", "0" }, new string[] { "2", "2", "1" }); table.Rows.Add(new string[] { "2", "2", "1" }, new string[] { "2", "2", "2" }); table.Rows.Add(new string[] { "2", "2", "2" }, new string[] { "0", "0", "0" }); table.MergeCells(); // tree // row1 DecisionConditionNode tc1 = project.DefineDecisionTree("tree1"); tc1.SetVariable("@var1").SetValues(new string[] { "0" }); DecisionConditionNode tc2 = new DecisionConditionNode("@var2", new string[] { "0" }); tc1.SetOnMatch(tc2); DecisionActionNode ta1 = new DecisionActionNode("@var1", "0"); tc2.SetOnMatch(ta1); ta1.SetFurtherMore(new DecisionActionNode("@var2", "1")); // row2 DecisionConditionNode tc3 = new DecisionConditionNode("@var2", new string[] { "1" }); tc2.SetElse(tc3); DecisionActionNode ta2 = new DecisionActionNode("@var1", "1"); tc3.SetOnMatch(ta2); ta1.SetFurtherMore(new DecisionActionNode("@var2", "0")); // row3 DecisionConditionNode tc4 = new DecisionConditionNode("@var1", new string[] { "1" }); tc1.SetElse(tc4); DecisionConditionNode tc5 = new DecisionConditionNode("@var2", new string[] { "0" }); tc4.SetOnMatch(tc5); DecisionActionNode ta3 = new DecisionActionNode("@var1", "1"); tc5.SetOnMatch(ta3); ta3.SetFurtherMore(new DecisionActionNode("@var2", "1")); // row4 DecisionConditionNode tc6 = new DecisionConditionNode("@var2", new string[] { "1" }); tc5.SetElse(tc6); DecisionActionNode ta4 = new DecisionActionNode("@var1", "0"); tc6.SetOnMatch(ta4); ta4.SetFurtherMore(new DecisionActionNode("@var2", "0")); // ruleset project .DefineRuleset("main") .DefineRule("main") .When((VariableStm)"@var2" == 1) .Do( TryStm.As() .Do( ((FunctionStm)"Write to console") .Params( ReflectionStm.As((FactStm)"fact1", "[2].ToString('s').Replace('T', ' ').Split($0)[1].ToCharArray()[2]", (FactStm)"fact2") ) ) .Do( Predef.Print( ReflectionStm.As((FactStm)"fact1", "ToString()") ) , RaiseErrorStm.As("test") ) .OnError( SetFactStm.As("error").Set( ReflectionStm.As(ContextStm.As(), "GetLastError()") ) , Predef.PrintLine( (StringStm)"Error: " + ReflectionStm.As((FactStm)"error", ".") ) ) ) .Do( Predef.PrintLn( ItemOfStm.As((FactStm)"fact1", 2) ) ) .Do( ForStm.As("i", 50) .Do( EvaluateTableStm.As("DecisionTable1") ) .Do( Predef.WriteLine( ArithmeticGroupStm.As((StringStm)"@var1: ") .Add((VariableStm)"@var1") .Add((StringStm)", @var2: ") .Add((VariableStm)"@var2") ) ) .Do( ContinueStm.As( (VariableStm)"Count" >= 1000 ) ) .Do( IfThenStm.As( (VariableStm)"VarA" > 0 ) .Then( ((SetVariableStm)"VarA") .Set( ArithmeticGroupStm.As((VariableStm)"VarA") .Add(2) .Subtract(1) ) ) ) .Do( IfThenStm.As( (VariableStm)"VarA" > 10 ) .Then( ((SetVariableStm)"VarA") .Set(1) ) ) .Do( ((SetVariableStm)"Count") .Set( ArithmeticGroupStm.As((VariableStm)"Count").Add(1) ) , Predef.WriteLn( "Count: " + (VariableStm)"Count" ) , Predef.PrintLn( "VarA: " + (VariableStm)"VarA" ) , Predef.PrintLn( (DateStm)"12.10.2005" + (TimeStm)"11.00:00:00" + (VariableStm)"Count" ) , Predef.PrintLn( Predef.AddDate( (DateStm)"12.10.2005", -2, -1, 3 ) ) ) ) ; return project; } private static void SaveTest(out IRuleset rs, out IFactList facts, out IVariableList vars, out IRuleDebugger debugger) { rs = null; vars = null; facts = null; debugger = null; IProject project = SaveTestProject(); XmlDocument doc = null; try { doc = ProjectWriter.Write((Project)project); } finally { doc.Save("." + Path.DirectorySeparatorChar.ToString() + "a.xml"); } Project prj = null; try { prj = ProjectReader.Read(doc); } finally { Console.WriteLine(prj); } } } }
namespace MindEngine.Core.Scene.Entity { using System; using System.Runtime.Serialization; using Core; using Microsoft.Xna.Framework; public class MMDrawEnabledChangedEventArgs : EventArgs { public MMDrawEnabledChangedEventArgs(bool drawEnabled) { this.DrawEnabled = drawEnabled; } public bool DrawEnabled { get; } } public class MMDrawOrderChangedEventArgs : EventArgs { public MMDrawOrderChangedEventArgs(int drawOrder) { this.DrawOrder = drawOrder; } public int DrawOrder { get; } } public interface IMMEntityDrawable : IMMEntityUpdatable, IMMDrawableOperations, IComparable<MMEntityDrawable> { #region Entity Events event EventHandler<MMDrawEnabledChangedEventArgs> DrawEnabledChanged; event EventHandler<MMDrawOrderChangedEventArgs> DrawOrderChanged; #endregion #region Entity Properties bool DrawEnabled { get; set; } int DrawOrder { get; set; } #endregion } [Serializable] public class MMEntityDrawable : MMEntityUpdatable, IMMEntityDrawable { #region Constructors protected MMEntityDrawable() { } ~MMEntityDrawable() { this.Dispose(true); } #endregion #region State Data private bool drawEnabled = true; public virtual bool DrawEnabled { get { return this.drawEnabled; } set { var changed = this.drawEnabled != value; if (changed) { this.drawEnabled = value; this.OnDrawEnabledChanged(); } } } #endregion #region Comparison public int CompareTo(MMEntityDrawable other) { return this.DrawOrder.CompareTo(other.DrawOrder); } #endregion #region Draw private int drawOrder; /// <summary> /// Z Order. The smaller, the further from the screen, because the /// smaller the value, the later it get drawn in a sorting collection. /// This usually is set by the scene graph system like node class and its /// manager class. /// </summary> public virtual int DrawOrder { get { return this.drawOrder; } set { var changed = this.drawOrder != value; if (changed) { this.drawOrder = value; this.OnDrawOrderChanged(); } } } /// <summary> /// Standard draw routine. /// </summary> /// <remarks> /// It is recommended not to call SpriteBatch.Begin and SpriteBatch.End /// in this method and its override version. /// </remarks>> /// <param name="time"></param> public virtual void Draw(GameTime time) { if (this.DrawEnabled) { this.DrawInternal(time); } } protected virtual void DrawInternal(GameTime time) { } #endregion #region Events public event EventHandler<MMDrawOrderChangedEventArgs> DrawOrderChanged = delegate {}; public event EventHandler<MMDrawEnabledChangedEventArgs> DrawEnabledChanged = delegate {}; #endregion #region Event Ons protected virtual void OnDrawOrderChanged() { this.DrawOrderChanged?.Invoke(this, new MMDrawOrderChangedEventArgs(this.DrawOrder)); } protected virtual void OnDrawEnabledChanged() { this.DrawEnabledChanged?.Invoke(this, new MMDrawEnabledChangedEventArgs(this.DrawEnabled)); } #endregion #region IDisposable private bool IsDisposed { get; set; } protected override void Dispose(bool disposing) { try { if (disposing) { if (!this.IsDisposed) { this.DisposeEventHandlers(); } this.IsDisposed = true; } } catch { // Ignored } finally { base.Dispose(disposing); } } private void DisposeEventHandlers() { this.DrawOrderChanged = null; this.DrawEnabledChanged = null; } #endregion } }
/** * Pairing Utility - A Bluetooth Pairing Utility for the PlayStation Move controller * Copyright (C) 2011, Copenhagen Game Collective (http://www.cphgc.org) * Douglas Wilson (http://www.doougle.net) * * Version 0.3 (Beta) * 2011-07-18 * * Email us at: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **/ using System; using System.Collections; using System.Runtime.InteropServices; using UnityEngine; public enum PSMoveConnectionType { Bluetooth, USB, Unknown, }; public class PairingUtility : MonoBehaviour { /**********************************************/ /******* Constants & Instance Variables *******/ /**********************************************/ public static bool DEBUG_MODE = true; public static int MAX_NUM_CONTROLLERS = 6; private int numControllers = 0; private int numUSBConnections = 0; private int nextScreen = 0; private Color background = new Color(0.78f, 0.682f, 0.831f); private int textAreaWidth; private int textAreaHeight; public GUIStyle titleStyle; public GUIStyle textStyle; private String title = ""; private String text = ""; private bool displayTitle = true; private bool errorEncountered = false; public AudioClip SOUND_REGISTRATION; public static AudioSource efxSource; /**********************************************/ /***********************/ /******* Methods *******/ /***********************/ void Awake() { title = "PLAYSTATION MOVE\nPAIRING UTILITY"; text = "By Douglas Wilson &\n" + "the Copenhagen Game Collective\n" + "(www.cphgc.org)\n\n" + "Press ENTER to continue"; } void Start() { Camera.mainCamera.backgroundColor = background; GUI.backgroundColor = background; textAreaWidth = (int) (Screen.width * .8); textAreaHeight = (int) (Screen.height * .8); // Sound removed from the open-source version // efxSource = gameObject.AddComponent<AudioSource>(); } void OnGUI() { GUILayout.BeginArea(new Rect((Screen.width - textAreaWidth) / 2, (Screen.height - textAreaHeight) / 2, textAreaWidth, textAreaHeight)); if (displayTitle) GUILayout.Label(title, titleStyle); GUILayout.Label(text, textStyle); GUILayout.EndArea(); } void Update() { if (Input.GetKey(KeyCode.Escape)) Exit(); if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter)) { switch (nextScreen) { case 0: displayTitle = false; text = "Each Move controller must be \"paired\" to this computer via Bluetooth.\n\n" + "You'll only ever need to do this once for each controller - or at least until you pair it to another computer or PS3.\n\n" + "Press ENTER to continue"; nextScreen++; break; case 1: text = "Connect the Move controller(s) to this computer by mini-USB wire.\n\n" + "Press ENTER when you're ready"; nextScreen++; break; case 2: PairControllers(); // This is where all the pairing magic happens if (numUSBConnections <= 0) { text = "No USB-connected Move controllers detected!\n\n" + "First connect the Move controller(s) to this computer.\n\n" + "Press ENTER to try again.\n\n" + "Or press ESC to quit"; nextScreen--; break; } else if (numUSBConnections > 0) { // Sound removed from the public open-source version // efxSource.PlayOneShot(SOUND_REGISTRATION); text = "Just paired " + numUSBConnections + " PS Move controller(s)!\n\n" + "Press the small circular PS button to connect it via Bluetooth.\n\n" + "Wait a second or two...\n\n" + "Then press ENTER to continue"; nextScreen++; break; } // Should never get here... Exit(); break; case 3: text = "The controller(s) should now be visible in your Bluetooth Preferences.\n\n" + "You can now unplug it.\n\n" + "Press ENTER to continue"; nextScreen++; break; case 4: text = "Remember, whenever you want to start an application that uses this controller(s), make sure to first press " + "the PS button to wirelessly connect the controller via Bluetooth.\n\n" + "Press ENTER to continue"; nextScreen++; break; case 5: text = "Press ENTER if you'd like to pair additional controllers.\n\n" + "Or press ESC to quit"; nextScreen = 1; break; default: break; } } } private void PairControllers() { numUSBConnections = 0; numControllers = psmove_count_connected(); if (numControllers >= MAX_NUM_CONTROLLERS) numControllers = MAX_NUM_CONTROLLERS; for (int i = 0; i < numControllers; i++) { PairOneController(i); if (errorEncountered) break; } } private void PairOneController(int id) { IntPtr controller = psmove_connect_by_id(id); if (controller == IntPtr.Zero) { ErrorText("Error! Controller " + id + " did not connect."); return; } PSMoveConnectionType ctype = psmove_connection_type(controller); if (ctype == PSMoveConnectionType.USB) // This avoids trying to pair any Bluetooth-connected controller objects { numUSBConnections++; if (psmove_pair(controller) == 0) { ErrorText("Error! Controller " + id + " failed to pair."); return; } } } public void ErrorText(String msg) { title = ""; text = msg + "\n\n Press ESC to quit"; nextScreen = -1; errorEncountered = true; } public static void Exit() { Application.Quit(); } /* The following functions are bindings to Thomas Perl's C API for the PlayStation Move (http://thp.io/2010/psmove/) * I don't use most of these functions in this application. But here they are just in case... * See README for more information * * TODO: Expose hooks to psmove_get_btaddr() and psmove_set_btadd() * These functions are already called by psmove_pair(), so unless you need to do something special, you won't need them. * * It's not clear to us whether we can just pass in a char array (depends on how memory is laid out in C#?) * When we were trying to get this to work in Windows, we compiled in our own versions of the two functions * that took six separate char arguments. When we have time for more testing, we may add these back in. */ #region importfunctions [DllImport("PSMove")] private static extern int psmove_count_connected(); [DllImport("PSMove")] private static extern IntPtr psmove_connect(); [DllImport("PSMove")] private static extern IntPtr psmove_connect_by_id(int id); [DllImport("PSMove")] private static extern int psmove_pair(IntPtr move); [DllImport("PSMove")] private static extern PSMoveConnectionType psmove_connection_type(IntPtr move); [DllImport("PSMove")] private static extern void psmove_set_leds(IntPtr move, char r, char g, char b); [DllImport("PSMove")] private static extern int psmove_update_leds(IntPtr move); [DllImport("PSMove")] private static extern void psmove_set_rumble(IntPtr move, char rumble); [DllImport("PSMove")] private static extern uint psmove_poll(IntPtr move); [DllImport("PSMove")] private static extern uint psmove_get_buttons(IntPtr move); [DllImport("PSMove")] private static extern char psmove_get_trigger(IntPtr move); [DllImport("PSMove")] private static extern void psmove_get_accelerometer(IntPtr move, ref int ax, ref int ay, ref int az); [DllImport("PSMove")] private static extern void psmove_get_gyroscope(IntPtr move, ref int gx, ref int gy, ref int gz); [DllImport("PSMove")] private static extern void psmove_disconnect(IntPtr move); #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. /****************************************************************************** * 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 BlendVariableDouble() { var test = new SimpleTernaryOpTest__BlendVariableDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__BlendVariableDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = 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.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public Vector128<Double> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (double)(((i % 2) == 0) ? -0.0 : 1.0); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__BlendVariableDouble testClass) { var result = Sse41.BlendVariable(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__BlendVariableDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) fixed (Vector128<Double>* pFld3 = &_fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)), Sse2.LoadVector128((Double*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Double[] _data3 = new Double[Op3ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private static Vector128<Double> _clsVar3; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private Vector128<Double> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__BlendVariableDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (double)(((i % 2) == 0) ? -0.0 : 1.0); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleTernaryOpTest__BlendVariableDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (double)(((i % 2) == 0) ? -0.0 : 1.0); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (double)(((i % 2) == 0) ? -0.0 : 1.0); } _dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.BlendVariable( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.BlendVariable( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.BlendVariable( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.BlendVariable( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) fixed (Vector128<Double>* pClsVar3 = &_clsVar3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)), Sse2.LoadVector128((Double*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr)); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var op3 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr)); var result = Sse41.BlendVariable(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__BlendVariableDouble(); var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__BlendVariableDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) fixed (Vector128<Double>* pFld3 = &test._fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)), Sse2.LoadVector128((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.BlendVariable(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) fixed (Vector128<Double>* pFld3 = &_fld3) { var result = Sse41.BlendVariable( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)), Sse2.LoadVector128((Double*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.BlendVariable( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)), Sse2.LoadVector128((Double*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] inArray3 = new Double[Op3ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (((BitConverter.DoubleToInt64Bits(thirdOp[0]) >> 63) & 1) == 1 ? BitConverter.DoubleToInt64Bits(secondOp[0]) != BitConverter.DoubleToInt64Bits(result[0]) : BitConverter.DoubleToInt64Bits(firstOp[0]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (((BitConverter.DoubleToInt64Bits(thirdOp[i]) >> 63) & 1) == 1 ? BitConverter.DoubleToInt64Bits(secondOp[i]) != BitConverter.DoubleToInt64Bits(result[i]) : BitConverter.DoubleToInt64Bits(firstOp[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.BlendVariable)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// 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.Search { 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 Microsoft.Rest.Azure; using Models; /// <summary> /// DocumentsProxyOperations operations. /// </summary> internal partial class DocumentsProxyOperations : IServiceOperations<SearchIndexClient>, IDocumentsProxyOperations { /// <summary> /// Initializes a new instance of the DocumentsProxyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DocumentsProxyOperations(SearchIndexClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the SearchIndexClient /// </summary> public SearchIndexClient Client { get; private set; } /// <summary> /// Queries the number of documents in the Azure Search index. /// <see href="https://msdn.microsoft.com/library/azure/dn798924.aspx" /> /// </summary> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<long?>> CountWithHttpMessagesAsync(SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Count", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "docs/$count").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } 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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<long?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<long?>(_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; } } }
// 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 MultiplyDouble() { var test = new SimpleBinaryOpTest__MultiplyDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MultiplyDouble { 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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); 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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyDouble testClass) { var result = Sse2.Multiply(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Multiply( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MultiplyDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__MultiplyDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Multiply( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Multiply( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Multiply( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Multiply), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Multiply), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Multiply), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Multiply( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.Multiply( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.Multiply(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Multiply(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Multiply(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyDouble(); var result = Sse2.Multiply(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__MultiplyDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.Multiply( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Multiply(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Multiply( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Multiply(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Multiply( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(left[0] * right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i] * right[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Multiply)}<Double>(Vector128<Double>, Vector128<Double>): {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; } } } }
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * What is this file about? * * Revision history: * Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here * xxxx-xx-xx, author, fix bug about xxx */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using rDSN.Tron.Contract; using rDSN.Tron.Utility; namespace rDSN.Tron.LanguageProvider { class ThriftSpecProvider : ISpecProvider { public new ServiceSpecType GetType() { return ServiceSpecType.Thrift; } //public string[] ToCommonSpec(ServiceSpec spec, string dir) //{ // var translator = IdlTranslator.GetInstance(GetType()); // var inputDir = spec.Directory; // var file = spec.MainSpecFile; // var outDir = dir; // var args = new List<string> // { // "-out " + outDir, // "-r" // recursively generate all included files // }; // if (!translator.ToCommonInterface(inputDir, file, outDir, args)) return null; // const int threshhold = 30; // filter the .cs files by their LastWriteTimes // var output = SystemHelper.GetFilesByLastWrite(outDir, "*_common.cs", SearchOption.TopDirectoryOnly, threshhold); // return output.ToArray(); //} private static FlowErrorCode GenerateRdsnClient(ServiceSpec spec, string dir, out LinkageInfo linkinfo) { linkinfo = new LinkageInfo(); var appName = Path.GetFileNameWithoutExtension(spec.MainSpecFile); if ( SystemHelper.RunProcess("php.exe", Path.Combine(Environment.GetEnvironmentVariable("DSN_ROOT"), "bin/dsn.generate_code.php") + " " + Path.Combine(spec.Directory, spec.MainSpecFile) + " csharp " + dir + " json layer3") != 0) return FlowErrorCode.ProcessStartFailed; var thriftGenPath = Path.Combine(dir, "thrift"); linkinfo.Sources.Add(Path.Combine(dir, "ThriftJsonHelper.cs")); linkinfo.Sources.Add(Path.Combine(dir, appName + ".client.cs")); linkinfo.Sources.Add(Path.Combine(dir, appName + ".code.definition.cs")); linkinfo.Sources.AddRange(Directory.GetFiles(thriftGenPath, "*.cs", SearchOption.AllDirectories)); return FlowErrorCode.Success; } public FlowErrorCode GenerateServiceClient( ServiceSpec spec, string dir, ClientLanguage lang, ClientPlatform platform, out LinkageInfo linkInfo ) { if (spec.IsRdsnRpc) { return GenerateRdsnClient(spec, dir, out linkInfo); } var compiler = LanguageHelper.GetCompilerPath(GetType(), platform); linkInfo = new LinkageInfo(); if (compiler == "") { return FlowErrorCode.SpecCompilerNotFound; } var arguments = new List<string>(); var languageName = GetLanguageName(lang); arguments.Add(" "); arguments.Add("--" + languageName); arguments.Add("-r"); arguments.Add("-out " + dir); arguments.Add(Path.Combine(spec.Directory, spec.MainSpecFile)); if (SystemHelper.RunProcess(compiler, string.Join(" ", arguments)) != 0) return FlowErrorCode.ExceptionError; // generally, thrift.exe will generate a folder in the name of the mainspec's namespace to the output dir,e.g. gen-csharp // all language libraries are availabe in the source code of thrift project, placed in the thrift\\lib\\{language} dir // in Tron project, we place thrift compiler at "external\\thrift\\bin", and place the libraries in at"external\\thrift\\lib\\{language}" switch (lang) { case ClientLanguage.Client_CSharp: { var sourceDir = Path.Combine(dir, "gen-" + languageName); linkInfo.IncludeDirectories.Add(sourceDir); linkInfo.LibraryPaths.Add(Path.Combine(Directory.GetParent(compiler).FullName, "lib\\csharp")); linkInfo.LibraryPaths.Add(dir); linkInfo.DynamicLibraries.AddRange(new List<string> { "Thrift.dll" }); var searchPattern = "*." + LanguageHelper.GetSourceExtension(lang); linkInfo.Sources.AddRange(SystemHelper.GetFilesByLastWrite(sourceDir, searchPattern, SearchOption.AllDirectories, 15).Select(Path.GetFileName)); break; } case ClientLanguage.Client_CPlusPlus: { var sourceDir = Path.Combine(dir, "gen-" + languageName); linkInfo.IncludeDirectories.Add(sourceDir); linkInfo.LibraryPaths.Add(sourceDir); linkInfo.LibraryPaths.Add(Path.Combine(Directory.GetParent(compiler).FullName, "lib\\cpp")); var searchPattern = "*." + LanguageHelper.GetSourceExtension(lang); linkInfo.Sources.AddRange(SystemHelper.GetFilesByLastWrite(sourceDir, searchPattern, SearchOption.AllDirectories, 15)); break; } case ClientLanguage.Client_Java: { var sourceDir = Path.Combine(dir, "gen-" + languageName); linkInfo.IncludeDirectories.Add(sourceDir); linkInfo.LibraryPaths.Add(sourceDir); linkInfo.LibraryPaths.Add(Path.Combine(Directory.GetParent(compiler).FullName, "lib\\java")); var searchPattern = "*." + LanguageHelper.GetSourceExtension(lang); linkInfo.Sources.AddRange(SystemHelper.GetFilesByLastWrite(sourceDir, searchPattern, SearchOption.AllDirectories, 15)); break; } default: break; } return FlowErrorCode.Success; } public FlowErrorCode GenerateServiceSketch( ServiceSpec spec, string dir, ClientLanguage lang, ClientPlatform platform, out LinkageInfo linkInfo ) { linkInfo = null; return FlowErrorCode.NotImplemented; } private string GetLanguageName(ClientLanguage lang) { var map = new Dictionary<ClientLanguage, string> { {ClientLanguage.Client_CPlusPlus, "cpp"}, {ClientLanguage.Client_CSharp, "csharp"}, {ClientLanguage.Client_Java, "java"}, {ClientLanguage.Client_Javascript, "js"}, {ClientLanguage.Client_Python, "py"} }; return map.ContainsKey(lang) ? map[lang] : ""; } public void GenerateClientCall(CodeBuilder builder, MethodCallExpression call, Service svc, Dictionary<Type, string> reWrittenTypes) { builder.AppendLine(call.Method.ReturnType.FullName.GetCompilableTypeName() + " resp;"); builder.AppendLine("while (" + (call.Object as MemberExpression).Member.Name + "." + call.Method.Name + "(req, out resp) != ErrorCode.ERR_OK) {}"); builder.AppendLine("return resp;"); } public void GenerateClientDeclaration(CodeBuilder builder, MemberExpression exp, Service svc) { throw new NotImplementedException(); } } }
namespace PB { partial class EditableListBox { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditableListBox)); this.textbox = new System.Windows.Forms.TextBox(); this.listbox = new System.Windows.Forms.ListBox(); this.buttonSort = new System.Windows.Forms.Button(); this.imagelistSmallButtons = new System.Windows.Forms.ImageList(this.components); this.imagelistLargeButtons = new System.Windows.Forms.ImageList(this.components); this.buttonUp = new System.Windows.Forms.Button(); this.buttonDown = new System.Windows.Forms.Button(); this.buttonAdd = new System.Windows.Forms.Button(); this.buttonRemove = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textbox // this.textbox.AccessibleRole = System.Windows.Forms.AccessibleRole.ListItem; this.textbox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textbox.Location = new System.Drawing.Point(1, 28); this.textbox.Name = "textbox"; this.textbox.Size = new System.Drawing.Size(148, 20); this.textbox.TabIndex = 0; this.textbox.TabStop = false; this.textbox.Visible = false; this.textbox.Leave += new System.EventHandler(this.textbox_Leave); // // listbox // this.listbox.AccessibleRole = System.Windows.Forms.AccessibleRole.List; this.listbox.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.listbox.FormattingEnabled = true; this.listbox.Location = new System.Drawing.Point(0, 27); this.listbox.Name = "listbox"; this.listbox.Size = new System.Drawing.Size(150, 121); this.listbox.TabIndex = 5; this.listbox.DoubleClick += new System.EventHandler(this.listbox_DoubleClick); // // buttonSort // this.buttonSort.AccessibleDescription = "Sort the list alphanumerically"; this.buttonSort.AccessibleName = "Sort"; this.buttonSort.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.buttonSort.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonSort.ImageIndex = 0; this.buttonSort.ImageList = this.imagelistSmallButtons; this.buttonSort.Location = new System.Drawing.Point(30, 0); this.buttonSort.Margin = new System.Windows.Forms.Padding(0); this.buttonSort.Name = "buttonSort"; this.buttonSort.Size = new System.Drawing.Size(24, 24); this.buttonSort.TabIndex = 0; this.buttonSort.UseVisualStyleBackColor = true; this.buttonSort.Click += new System.EventHandler(this.buttonSort_Click); // // imagelistSmallButtons // this.imagelistSmallButtons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imagelistSmallButtons.ImageStream"))); this.imagelistSmallButtons.TransparentColor = System.Drawing.Color.Transparent; this.imagelistSmallButtons.Images.SetKeyName(0, "sort_small.png"); this.imagelistSmallButtons.Images.SetKeyName(1, "up_small.png"); this.imagelistSmallButtons.Images.SetKeyName(2, "down_small.png"); this.imagelistSmallButtons.Images.SetKeyName(3, "add_small.png"); this.imagelistSmallButtons.Images.SetKeyName(4, "remove_small.png"); // // imagelistLargeButtons // this.imagelistLargeButtons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imagelistLargeButtons.ImageStream"))); this.imagelistLargeButtons.TransparentColor = System.Drawing.Color.Transparent; this.imagelistLargeButtons.Images.SetKeyName(0, "icons/sort_large.png"); this.imagelistLargeButtons.Images.SetKeyName(1, "icons/up_large.png"); this.imagelistLargeButtons.Images.SetKeyName(2, "icons/down_large.png"); this.imagelistLargeButtons.Images.SetKeyName(3, "icons/add_large.png"); this.imagelistLargeButtons.Images.SetKeyName(4, "icons/remove_large.png"); // // buttonUp // this.buttonUp.AccessibleDescription = "Move the selected item up the list"; this.buttonUp.AccessibleName = "Move up"; this.buttonUp.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.ImageIndex = 1; this.buttonUp.ImageList = this.imagelistSmallButtons; this.buttonUp.Location = new System.Drawing.Point(54, 0); this.buttonUp.Margin = new System.Windows.Forms.Padding(0); this.buttonUp.Name = "buttonUp"; this.buttonUp.Size = new System.Drawing.Size(24, 24); this.buttonUp.TabIndex = 1; this.buttonUp.UseVisualStyleBackColor = true; this.buttonUp.Click += new System.EventHandler(this.buttonUp_Click); // // buttonDown // this.buttonDown.AccessibleDescription = "Move the selected item down the list"; this.buttonDown.AccessibleName = "Move down"; this.buttonDown.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonDown.ImageIndex = 2; this.buttonDown.ImageList = this.imagelistSmallButtons; this.buttonDown.Location = new System.Drawing.Point(78, 0); this.buttonDown.Margin = new System.Windows.Forms.Padding(0); this.buttonDown.Name = "buttonDown"; this.buttonDown.Size = new System.Drawing.Size(24, 24); this.buttonDown.TabIndex = 2; this.buttonDown.UseVisualStyleBackColor = true; this.buttonDown.Click += new System.EventHandler(this.buttonDown_Click); // // buttonAdd // this.buttonAdd.AccessibleDescription = "Add a new item to the list"; this.buttonAdd.AccessibleName = "Add item"; this.buttonAdd.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.buttonAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonAdd.ImageIndex = 3; this.buttonAdd.ImageList = this.imagelistSmallButtons; this.buttonAdd.Location = new System.Drawing.Point(102, 0); this.buttonAdd.Margin = new System.Windows.Forms.Padding(0); this.buttonAdd.Name = "buttonAdd"; this.buttonAdd.Size = new System.Drawing.Size(24, 24); this.buttonAdd.TabIndex = 3; this.buttonAdd.UseVisualStyleBackColor = true; this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click); // // buttonRemove // this.buttonRemove.AccessibleDescription = "Remove the selected item from the list"; this.buttonRemove.AccessibleName = "Remove item"; this.buttonRemove.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.buttonRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonRemove.ImageIndex = 4; this.buttonRemove.ImageList = this.imagelistSmallButtons; this.buttonRemove.Location = new System.Drawing.Point(126, 0); this.buttonRemove.Margin = new System.Windows.Forms.Padding(0); this.buttonRemove.Name = "buttonRemove"; this.buttonRemove.Size = new System.Drawing.Size(24, 24); this.buttonRemove.TabIndex = 4; this.buttonRemove.UseVisualStyleBackColor = true; this.buttonRemove.Click += new System.EventHandler(this.buttonRemove_Click); // // EditableListBox // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.Transparent; this.Controls.Add(this.textbox); this.Controls.Add(this.buttonRemove); this.Controls.Add(this.buttonAdd); this.Controls.Add(this.buttonDown); this.Controls.Add(this.buttonUp); this.Controls.Add(this.buttonSort); this.Controls.Add(this.listbox); this.Name = "EditableListBox"; this.Size = new System.Drawing.Size(150, 148); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListBox listbox; private System.Windows.Forms.TextBox textbox; private System.Windows.Forms.Button buttonSort; private System.Windows.Forms.ImageList imagelistLargeButtons; private System.Windows.Forms.Button buttonUp; private System.Windows.Forms.Button buttonDown; private System.Windows.Forms.Button buttonAdd; private System.Windows.Forms.Button buttonRemove; private System.Windows.Forms.ImageList imagelistSmallButtons; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; namespace Microsoft.Azure.Management.Sql { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public partial class SqlManagementClient : ServiceClient<SqlManagementClient>, ISqlManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IAuditingPolicyOperations _auditingPolicy; /// <summary> /// Represents all the operations to manage Azure SQL Database and /// Database Server Audit policy. Contains operations to: Create, /// Retrieve and Update audit policy. /// </summary> public virtual IAuditingPolicyOperations AuditingPolicy { get { return this._auditingPolicy; } } private ICapabilitiesOperations _capabilities; /// <summary> /// Represents all the operations for determining the set of /// capabilites available in a specified region. /// </summary> public virtual ICapabilitiesOperations Capabilities { get { return this._capabilities; } } private IDatabaseActivationOperations _databaseActivation; /// <summary> /// Represents all the operations for operating pertaining to /// activation on Azure SQL Data Warehouse databases. Contains /// operations to: Pause and Resume databases /// </summary> public virtual IDatabaseActivationOperations DatabaseActivation { get { return this._databaseActivation; } } private IDatabaseBackupOperations _databaseBackup; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// database backups. /// </summary> public virtual IDatabaseBackupOperations DatabaseBackup { get { return this._databaseBackup; } } private IDatabaseOperations _databases; /// <summary> /// Represents all the operations for operating on Azure SQL Databases. /// Contains operations to: Create, Retrieve, Update, and Delete /// databases, and also includes the ability to get the event logs for /// a database. /// </summary> public virtual IDatabaseOperations Databases { get { return this._databases; } } private IDataMaskingOperations _dataMasking; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// data masking. Contains operations to: Create, Retrieve, Update, /// and Delete data masking rules, as well as Create, Retreive and /// Update data masking policy. /// </summary> public virtual IDataMaskingOperations DataMasking { get { return this._dataMasking; } } private IElasticPoolOperations _elasticPools; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Elastic Pools. Contains operations to: Create, Retrieve, Update, /// and Delete. /// </summary> public virtual IElasticPoolOperations ElasticPools { get { return this._elasticPools; } } private IFirewallRuleOperations _firewallRules; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Server Firewall Rules. Contains operations to: Create, Retrieve, /// Update, and Delete firewall rules. /// </summary> public virtual IFirewallRuleOperations FirewallRules { get { return this._firewallRules; } } private IImportExportOperations _importExport; /// <summary> /// Represents all the operations for import/export on Azure SQL /// Databases. Contains operations to: Import, Export, Get /// Import/Export status for a database. /// </summary> public virtual IImportExportOperations ImportExport { get { return this._importExport; } } private IJobAccountOperations _jobAccounts; /// <summary> /// Represents all the operations for operating on Azure SQL Job /// Accounts. Contains operations to: Create, Retrieve, Update, and /// Delete Job Accounts /// </summary> public virtual IJobAccountOperations JobAccounts { get { return this._jobAccounts; } } private IRecommendedElasticPoolOperations _recommendedElasticPools; /// <summary> /// Represents all the operations for operating on Azure SQL /// Recommended Elastic Pools. Contains operations to: Retrieve. /// </summary> public virtual IRecommendedElasticPoolOperations RecommendedElasticPools { get { return this._recommendedElasticPools; } } private IRecommendedIndexOperations _recommendedIndexes; /// <summary> /// Represents all the operations for managing recommended indexes on /// Azure SQL Databases. Contains operations to retrieve recommended /// index and update state. /// </summary> public virtual IRecommendedIndexOperations RecommendedIndexes { get { return this._recommendedIndexes; } } private IReplicationLinkOperations _databaseReplicationLinks; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Replication Links. Contains operations to: Delete and Retrieve /// replication links. /// </summary> public virtual IReplicationLinkOperations DatabaseReplicationLinks { get { return this._databaseReplicationLinks; } } private ISecureConnectionPolicyOperations _secureConnection; /// <summary> /// Represents all the operations for managing Azure SQL Database /// secure connection. Contains operations to: Create, Retrieve and /// Update secure connection policy . /// </summary> public virtual ISecureConnectionPolicyOperations SecureConnection { get { return this._secureConnection; } } private ISecurityAlertPolicyOperations _securityAlertPolicy; /// <summary> /// Represents all the operations to manage Azure SQL Database and /// Database Server Security Alert policy. Contains operations to: /// Create, Retrieve and Update policy. /// </summary> public virtual ISecurityAlertPolicyOperations SecurityAlertPolicy { get { return this._securityAlertPolicy; } } private IServerAdministratorOperations _serverAdministrators; /// <summary> /// Represents all the operations for operating on Azure SQL Server /// Active Directory Administrators. Contains operations to: Create, /// Retrieve, Update, and Delete Azure SQL Server Active Directory /// Administrators. /// </summary> public virtual IServerAdministratorOperations ServerAdministrators { get { return this._serverAdministrators; } } private IServerCommunicationLinkOperations _communicationLinks; /// <summary> /// Represents all the operations for operating on Azure SQL Server /// communication links. Contains operations to: Create, Retrieve, /// Update, and Delete. /// </summary> public virtual IServerCommunicationLinkOperations CommunicationLinks { get { return this._communicationLinks; } } private IServerDisasterRecoveryConfigurationOperations _serverDisasterRecoveryConfigurations; /// <summary> /// Represents all the operations for operating on Azure SQL Server /// disaster recovery configurations. Contains operations to: Create, /// Retrieve, Update, Failover, and Delete. /// </summary> public virtual IServerDisasterRecoveryConfigurationOperations ServerDisasterRecoveryConfigurations { get { return this._serverDisasterRecoveryConfigurations; } } private IServerOperations _servers; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Servers. Contains operations to: Create, Retrieve, Update, and /// Delete servers. /// </summary> public virtual IServerOperations Servers { get { return this._servers; } } private IServerUpgradeOperations _serverUpgrades; /// <summary> /// Represents all the operations for Azure SQL Database Server Upgrade /// </summary> public virtual IServerUpgradeOperations ServerUpgrades { get { return this._serverUpgrades; } } private IServiceObjectiveOperations _serviceObjectives; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Service Objectives. Contains operations to: Retrieve service /// objectives. /// </summary> public virtual IServiceObjectiveOperations ServiceObjectives { get { return this._serviceObjectives; } } private IServiceTierAdvisorOperations _serviceTierAdvisors; /// <summary> /// Represents all the operations for operating on service tier /// advisors. Contains operations to: Retrieve. /// </summary> public virtual IServiceTierAdvisorOperations ServiceTierAdvisors { get { return this._serviceTierAdvisors; } } private ITransparentDataEncryptionOperations _transparentDataEncryption; /// <summary> /// Represents all the operations of Azure SQL Database Transparent /// Data Encryption. Contains operations to: Retrieve, and Update /// Transparent Data Encryption. /// </summary> public virtual ITransparentDataEncryptionOperations TransparentDataEncryption { get { return this._transparentDataEncryption; } } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> public SqlManagementClient() : base() { this._auditingPolicy = new AuditingPolicyOperations(this); this._capabilities = new CapabilitiesOperations(this); this._databaseActivation = new DatabaseActivationOperations(this); this._databaseBackup = new DatabaseBackupOperations(this); this._databases = new DatabaseOperations(this); this._dataMasking = new DataMaskingOperations(this); this._elasticPools = new ElasticPoolOperations(this); this._firewallRules = new FirewallRuleOperations(this); this._importExport = new ImportExportOperations(this); this._jobAccounts = new JobAccountOperations(this); this._recommendedElasticPools = new RecommendedElasticPoolOperations(this); this._recommendedIndexes = new RecommendedIndexOperations(this); this._databaseReplicationLinks = new ReplicationLinkOperations(this); this._secureConnection = new SecureConnectionPolicyOperations(this); this._securityAlertPolicy = new SecurityAlertPolicyOperations(this); this._serverAdministrators = new ServerAdministratorOperations(this); this._communicationLinks = new ServerCommunicationLinkOperations(this); this._serverDisasterRecoveryConfigurations = new ServerDisasterRecoveryConfigurationOperations(this); this._servers = new ServerOperations(this); this._serverUpgrades = new ServerUpgradeOperations(this); this._serviceObjectives = new ServiceObjectiveOperations(this); this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this); this._transparentDataEncryption = new TransparentDataEncryptionOperations(this); this._apiVersion = "2014-04-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public SqlManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public SqlManagementClient(HttpClient httpClient) : base(httpClient) { this._auditingPolicy = new AuditingPolicyOperations(this); this._capabilities = new CapabilitiesOperations(this); this._databaseActivation = new DatabaseActivationOperations(this); this._databaseBackup = new DatabaseBackupOperations(this); this._databases = new DatabaseOperations(this); this._dataMasking = new DataMaskingOperations(this); this._elasticPools = new ElasticPoolOperations(this); this._firewallRules = new FirewallRuleOperations(this); this._importExport = new ImportExportOperations(this); this._jobAccounts = new JobAccountOperations(this); this._recommendedElasticPools = new RecommendedElasticPoolOperations(this); this._recommendedIndexes = new RecommendedIndexOperations(this); this._databaseReplicationLinks = new ReplicationLinkOperations(this); this._secureConnection = new SecureConnectionPolicyOperations(this); this._securityAlertPolicy = new SecurityAlertPolicyOperations(this); this._serverAdministrators = new ServerAdministratorOperations(this); this._communicationLinks = new ServerCommunicationLinkOperations(this); this._serverDisasterRecoveryConfigurations = new ServerDisasterRecoveryConfigurationOperations(this); this._servers = new ServerOperations(this); this._serverUpgrades = new ServerUpgradeOperations(this); this._serviceObjectives = new ServiceObjectiveOperations(this); this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this); this._transparentDataEncryption = new TransparentDataEncryptionOperations(this); this._apiVersion = "2014-04-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public SqlManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// SqlManagementClient instance /// </summary> /// <param name='client'> /// Instance of SqlManagementClient to clone to /// </param> protected override void Clone(ServiceClient<SqlManagementClient> client) { base.Clone(client); if (client is SqlManagementClient) { SqlManagementClient clonedClient = ((SqlManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
using System; using System.IO; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UGFramework.Utility; using UGFramework.Extension; using UGFramework.Log; namespace UGFramework.Res { public partial class ResManager : MonoBehaviour { // Resources hotupdating/uncompress process info public struct ProcessInfo { // Current updating filepath public string File; // If error is empty meaning success public string Error; // Index of current updating file in updating files public int Index; // Count of updating files public int Count; public float Percent { get { if (Count <= 0) return 1f; return (float)(Index + 1) / Count; } } public ulong DownloadedSize; public ulong DownloadedMaxSize; } public static ResManager Instance { get; private set; } ResManager() {} public bool Simulate = false; void Awake() { Instance = this; } void OnDestroy() { #if UNITY_EDITOR // Delete hotupdate directory if (Directory.Exists(ResConfig.MOBILE_HOTUPDATE_PATH)) Directory.Delete(ResConfig.MOBILE_HOTUPDATE_PATH, true); #endif } public void Init() { this.InitForAssetBundle(); this.InitForLoader(); this.InitForHotUpdate(); this.InitForCompress(); } public void Reset() { this.ClearAssetBundles(); } public byte[] LoadTxt(string fullpath) { var textAssets = this.Load<TextAsset>(fullpath); var bytes = new byte[textAssets.bytes.Length]; textAssets.bytes.CopyTo(bytes, 0); this.UnloadAsset(fullpath); return bytes; } /** * If is editor, load lua file by fileStream. * If is mobile, load lua file by assetBundle. * @path : start from Assets(exclude), like "Scripts/*.cs" */ public byte[] LoadLua(string path) { var fullpath = ResConfig.LUA_ROOT + "/" + path; // Editor if (Application.isMobilePlatform == false && this.Simulate == false) { fullpath = Application.dataPath + "/" + ResConfig.RES_ROOT + "/" + fullpath + ResConfig.LUA_EXTENSION; return FileUtility.ReadFileBytes(fullpath); } // Mobile fullpath = fullpath + ResConfig.MOBILE_LUA_EXTENSION; return this.LoadTxt(fullpath); } // @path : contains file extension, like "bgBlack.png"(without "Runtime"), "IconBG/IconBG_1.png" public Sprite LoadSprite(string path) { var fileName = Path.GetFileName(path); var bundlePath = path.ReplaceLast(fileName, ""); if (bundlePath.EndsWith("/")) bundlePath = bundlePath.ReplaceLast("/", ""); var assetName = "Assets/" + ResConfig.UI_TEXTURE_RUNTIME + "/" + path; // Assets in runtime.bundle if (string.IsNullOrEmpty(bundlePath)) { bundlePath = ResConfig.UI_TEXTURE_RUNTIME_BUNDLE; assetName = "Assets/" + ResConfig.UI_TEXTURE_RUNTIME + "/" + fileName; LogManager.Error(string.Format( "Load sprite from runtime.assetbundle is obsoleted! sprite({0})", assetName )); return null; } else { bundlePath = ResConfig.UI_TEXTURE_RUNTIME_BUNDLE + "/" + bundlePath; } path = ResConfig.UI_TEXTURE + "/" + bundlePath; var sprite = this.Load<Sprite>(path, assetName); return sprite; } public void UnloadSprite(string path) { var fileName = Path.GetFileName(path); var bundlePath = path.ReplaceLast(fileName, ""); if (bundlePath.EndsWith("/")) bundlePath = bundlePath.ReplaceLast("/", ""); var assetName = "Assets/" + ResConfig.UI_TEXTURE_RUNTIME + "/" + path; // Assets in runtime.bundle if (string.IsNullOrEmpty(bundlePath)) { bundlePath = ResConfig.UI_TEXTURE_RUNTIME_BUNDLE; assetName = "Assets/" + ResConfig.UI_TEXTURE_RUNTIME + "/" + fileName; LogManager.Error(string.Format( "Unload sprite from runtime.assetbundle is obsoleted! sprite({0})", assetName )); return; } else { bundlePath = ResConfig.UI_TEXTURE_RUNTIME_BUNDLE + "/" + bundlePath; } path = ResConfig.UI_TEXTURE + "/" + bundlePath; this.UnloadAsset(path, assetName); } // @path : start from UIRoot(exclude), like "Login/Login(prefab)" public GameObject LoadUI(string path) { path = ResConfig.UI_PREFABS_ROOT + "/" + path + ".prefab"; return this.Load<GameObject>(path); } public void UnloadUI(string path) { var bundlePathWithoutExtension = ResConfig.UI_PREFABS_ROOT + "/" + path + ".prefab"; this.UnloadAsset(bundlePathWithoutExtension); } // @return : scene path public string LoadScene(string sceneName) { var path = ResConfig.SCENE_ROOT + "/" + sceneName; // Editor if (Application.isMobilePlatform == false && this.Simulate == false) { path = ResConfig.RES_ROOT + "/" + path; return path; } // Mobile or Simulate path = path + ".unity"; var loadedAssetBundle = this.LoadAssetBundle(path); if (loadedAssetBundle == null) return null; return loadedAssetBundle.ScenePaths[0]; } public void UnloadScene(string sceneName) { // Editor if (Application.isMobilePlatform == false && this.Simulate == false) { return; } // Mobile or Simulate var path = ResConfig.SCENE_ROOT + "/" + sceneName; path = path + ".unity"; this.UnloadAssetBundle(path, false); } /** * If is editor, load asset by assetDatabase. * If is mobile, load asset by assetBundle. * @path : start from ResRoot(exclude), like "Lua/*.lua" */ public T Load<T>(string path, string assetName = null) where T : UnityEngine.Object { var bundlePathWithoutExtension = path; // NOTE: Load asset from bundle will increase referenceCount of this bundle! var assetFromCacheOrBundle = this.LoadFromCacheOrBundle<T>(bundlePathWithoutExtension, assetName); return assetFromCacheOrBundle; } /** * You must know what you are going to do, and be careful of unloading asset * Note: @assetName is useless, cause unloading specific asset from an assetBundle is not implemented. */ public void UnloadAsset(string bundlePathWithoutExtension, string assetName = null) { this.Unload(bundlePathWithoutExtension, assetName); } /** * Unload all unused assets, usually call this function when changing scene */ Coroutine _unloadUnusedAssetCoroutine = null; public void UnloadUnusedAssets() { if (_unloadUnusedAssetCoroutine != null) return; _unloadUnusedAssetCoroutine = this.StartCoroutine(_UnloadUnusedAssets()); } IEnumerator _UnloadUnusedAssets() { yield return 1; yield return Resources.UnloadUnusedAssets(); _unloadUnusedAssetCoroutine = null; } } }
using System; using System.ComponentModel.DataAnnotations; using System.Linq; using Csla; using Csla.Data; using CslaMVC.Repository; using CslaMVC.Rules; using Csla.Rules; using System.Collections.Generic; namespace CslaMVC.Library { [Serializable] public partial class Customer : BusinessBase<Customer> { #region Business Methods public static readonly PropertyInfo<int> CustomerNoProperty = RegisterProperty<int>(o => o.CustomerNo, "Customer No"); public int CustomerNo { get { return GetProperty(CustomerNoProperty); } internal set { SetProperty(CustomerNoProperty, value); } } public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(o => o.Name, "Name"); [Required(ErrorMessage = "'Name' is required")] [StringLength(25, ErrorMessage = "Name must be less than 25 characters")] public string Name { get { return GetProperty(NameProperty); } set { SetProperty(NameProperty, value); } } public static readonly PropertyInfo<int> GroupNoProperty = RegisterProperty<int>(o => o.GroupNo, "Group No"); [Range(0, 9, ErrorMessage = "'GroupNo' must be between 0 and 9")] public int GroupNo { get { return GetProperty(GroupNoProperty); } set { SetProperty(GroupNoProperty, value); } } public static readonly PropertyInfo<string> CityProperty = RegisterProperty<string>(o => o.City, "City"); public string City { get { return GetProperty(CityProperty); } set { SetProperty(CityProperty, value); } } //{0} = prop name //{1} = rule arg[1] public static readonly PropertyInfo<string> StateProperty = RegisterProperty<string>(o => o.State, "State"); [RegularExpression(@"[a-zA-Z]{2}", ErrorMessage = "'State' must be standard 2 character state code")] public string State { get { return GetProperty(StateProperty); } set { SetProperty(StateProperty, value); } } public static readonly PropertyInfo<string> ZipcodeProperty = RegisterProperty<string>(o => o.Zipcode, "Zipcode"); [RegularExpression(@"\d{5}(-\d{4})?", ErrorMessage = "'Zipcode' is invalid")] public string Zipcode { get { return GetProperty(ZipcodeProperty); } set { SetProperty(ZipcodeProperty, value); } } public static readonly PropertyInfo<DateTime> StartProperty = RegisterProperty<DateTime>(o => o.Start, "Start"); public DateTime Start { get { return GetProperty(StartProperty); } set { SetProperty(StartProperty, value); } } public static readonly PropertyInfo<DateTime> EndProperty = RegisterProperty<DateTime>(o => o.End, "End"); public DateTime End { get { return GetProperty(EndProperty); } set { SetProperty(EndProperty, value); } } #endregion #region Validation Rules protected override void AddBusinessRules() { base.AddBusinessRules(); //include any data annotation attribute rules BusinessRules.AddRule(new Rules.UpperCaseRule(StateProperty) { Priority = 1 }); //modifies data, priority 1 (default is 0) BusinessRules.AddRule(new Rules.AlsoRequiredRule(CityProperty, CityProperty, StateProperty)); //multiple related properties BusinessRules.AddRule(new Rules.AlsoRequiredRule(StateProperty, CityProperty, StateProperty)); //multiple related properties BusinessRules.AddRule(new Rules.IsInListRule<string>(StateProperty, new List<string> { "IL", "MN", "WA" })); //BusinessRules.AddRule(new Csla.Rules.CommonRules.Lambda(c => TestRuleAction(c))); //object rule, always broken BusinessRules.AddRule(new PrivateRule() { }); //object rule } protected static void AddObjectAuthorizationRules() { //auth rules Csla.Rules.BusinessRules.AddRule(typeof(Customer), new Csla.Rules.CommonRules.IsInRole(AuthorizationActions.EditObject, new List<string> { "Foo" })); Csla.Rules.BusinessRules.AddRule(typeof(Customer), new Csla.Rules.CommonRules.IsInRole(AuthorizationActions.ReadProperty, ZipcodeProperty, "Foo")); Csla.Rules.BusinessRules.AddRule(typeof(Customer), new AuthRule(AuthorizationActions.DeleteObject)); } private void TestRuleAction(IRuleContext context) { context.AddErrorResult("lambda rule broken"); } class PrivateRule : BusinessRule { protected override void Execute(IRuleContext context) { var cust = (Customer)context.Target; if (cust.Zipcode == "12345") context.AddErrorResult("private rule failed"); } } class AuthRule : AuthorizationRule { public AuthRule(AuthorizationActions action) : base(action) { } protected override void Execute(AuthorizationContext context) { //crude custom rule context.HasPermission = (DateTime.Now.Minute % 2 == 0); } } #endregion #region Factory Methods public static Customer NewCustomer() { return DataPortal.Create<Customer>(); } public static Customer GetCustomer(int CustomerNo) { return DataPortal.Fetch<Customer>( new SingleCriteria<Customer, int>(CustomerNo)); } internal static Customer GetCustomer(object data) { var customer = new Customer(); DataMapper.Map(data, customer); customer.MarkAsChild(); return customer; } public static void DeleteCustomer(int CustomerNo) { DataPortal.Delete<Customer>(new SingleCriteria<Customer, int>(CustomerNo)); } public Customer() { /* Require use of factory methods */ } #endregion #region Data Access public new Customer Save() { return base.Save(); } [RunLocal] protected override void DataPortal_Create() { var now = DateTime.Now; this.Start = now; this.End = now; base.DataPortal_Create(); } private void DataPortal_Fetch(SingleCriteria<Customer, int> criteria) { var data = Data.Connect(); var customer = data.Customers.Where(c => c.CustomerNo == criteria.Value).SingleOrDefault(); if (customer == null) return; BusinessRules.SuppressRuleChecking = true; DataMapper.Map(customer, this); BusinessRules.SuppressRuleChecking = false; } protected override void DataPortal_Insert() { var data = Data.Connect(); var customer = new CslaMVC.Repository.Customer(); this.CustomerNo = data.Customers.Select(c => c.CustomerNo).Max() + 1; DataMapper.Map(this, customer, "Start", "End"); data.Customers.Add(customer); } protected override void DataPortal_Update() { var data = Data.Connect(); var customer = data.Customers.Where(c => c.CustomerNo == this.CustomerNo).SingleOrDefault(); var index = data.Customers.IndexOf(customer); if (customer == null) return; DataMapper.Map(this, customer, "Start", "End"); data.Customers[index] = customer; } protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new SingleCriteria<Customer, int>(this.CustomerNo)); } private void DataPortal_Delete(SingleCriteria<Customer, int> criteria) { var data = Data.Connect(); var customer = data.Customers.Where(c => c.CustomerNo == this.CustomerNo).SingleOrDefault(); if (customer == null) return; data.Customers.Remove(customer); } #endregion #region ICheckRules Members /// <summary> /// Invokes all rules for the business type. /// </summary> public void CheckRules() { BusinessRules.CheckRules(); } /// <summary> /// Invokes all business rules attached at the class level of a business type. /// </summary> public void CheckObjectRules() { BusinessRules.CheckObjectRules(); } #endregion } }
using System; using System.Threading; using Microsoft.SPOT; /* * Copyright 2012-2014 Stefan Thoolen (http://www.netmftoolbox.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Toolbox.NETMF.NET { /// <summary> /// A telnet server with minimal TELNET and ANSI support /// </summary> /// <remarks> /// I found these links very useful: /// ANSI escapes: http://isthe.com/chongo/tech/comp/ansi_escapes.html /// Telnet commands: http://www.networksorcery.com/enp/protocol/telnet.htm /// </remarks> public class TelnetServer { private const char IAC = (char)255; // Interpret as Command private const char WILL = (char)251; private const char WONT = (char)252; private const char DO = (char)253; private const char DONT = (char)254; private const char ECHO = (char)1; private const char SUPPRESSGOAHEAD = (char)3; /// <summary>When true, user inputted data gets echoed</summary> public bool EchoEnabled { get; set; } /// <summary>Reference to the socket</summary> private SimpleSocket _Sock; /// <summary>Local data buffer</summary> private string _Buffer = ""; /// <summary> /// Returns the amount of bytes waiting for this.Input() /// </summary> public int InputBuffer { get { this._Read(); return this._Buffer.Length; } } /// <summary>The client address</summary> public string RemoteAddress { get { return this._Sock.Hostname; } } /// <summary>Some commands, like color, will be buffered to avoid small data packets. This actually speeds up the server.</summary> private string _WriteBuffer = ""; /// <summary> /// Creates a new telnet server /// </summary> /// <param name="Socket">The socket</param> public TelnetServer(SimpleSocket Socket) { this._Sock = Socket; this.EchoEnabled = true; // We handle our line endings ourself this._Sock.LineEnding = ""; } /// <summary> /// Closes the connection /// </summary> public void Close() { this._Sock.Close(); } /// <summary> /// True when there's a connection /// </summary> public bool IsConnected { get { return this._Sock.IsConnected; } } /// <summary> /// Listens and waits until we have a connection /// </summary> public void Listen() { this._Sock.Listen(); // We handle echoing ourselves this._Write(new char[] { IAC, DONT, ECHO }, true); this._Write(new char[] { IAC, WILL, ECHO }, true); // We want to receive every byte when it's received, don't wait for it! this._Write(new char[] { IAC, DO, SUPPRESSGOAHEAD }, true); this._Write(new char[] { IAC, WILL, SUPPRESSGOAHEAD }); Thread.Sleep(100); this._Read(); } /// <summary> /// Writes data to the client /// </summary> /// <param name="Data">Data to write</param> /// <param name="Buffered">When true, data will be sent in front of the next packet</param> private void _Write(string Data, bool Buffered = false) { if (Buffered) { this._WriteBuffer += Data; } else { string Out = this._WriteBuffer + Data; this._WriteBuffer = ""; if (this.IsConnected) this._Sock.Send(Out); } } /// <summary> /// Writes data to the client /// </summary> /// <param name="Data">Data to write</param> /// <param name="Buffered">When true, data will be sent in front of the next packet</param> private void _Write(char[] Data, bool Buffered = false) { this._Write(new string(Data), Buffered); } /// <summary> /// Sends a beep to the client /// </summary> public void Beep() { this._Write("\x07"); } /// <summary> /// Reads data from the client /// </summary> private void _Read() { string NewData = this._Sock.Receive(); if (NewData == "") return; for (int i = 0; i < NewData.Length; ++i) { if (NewData[i] == IAC) { char Command = NewData[++i]; // Lets only support DO, DONT, WILL and WONT for now if (Command == DO || Command == DONT || Command == WILL || Command == WONT) { // Lets see what the other party wants to tell us char Option = NewData[++i]; // Server will echo if (Command == DO && Option == ECHO) this._Write(new char[] { IAC, WILL, ECHO }); // Client shouldn't echo else if (Command == WILL && Option == ECHO) this._Write(new char[] { IAC, DONT, ECHO }); // We will suppress go-aheads else if (Command == DO && Option == SUPPRESSGOAHEAD) this._Write(new char[] { IAC, WILL, SUPPRESSGOAHEAD }); // Fine that you will ;-) else if (Command == WILL) { /* Ignored */ } // But I won't do the rest! else this._Write(new char[] { IAC, WONT, Option }); } } else { // Backspace if (NewData[i] == '\x08') { if (this._Buffer.Length > 0) { this._Buffer = this._Buffer.Substring(0, this._Buffer.Length - 1); if (EchoEnabled) this._Write("\x08 \x08"); } } // Escape else if (NewData[i] == '\x1b') { if (this._Buffer.Length > 0) { if (EchoEnabled) for (int Cnt = 0; Cnt < this._Buffer.Length; ++Cnt) this._Write("\x08 \x08"); this._Buffer = ""; } } // All other characters else { this._Buffer += NewData[i]; if (EchoEnabled) this._Write(NewData.Substring(i, 1)); } } } } /// <summary> /// Reads out input from the terminal /// </summary> /// <param name="Length">The amount of bytes to read, if 0, it reads until a carriage return</param> /// <param name="Blocking">When set to false, it won't wait for data, it will just return empty if there's no data</param> public string Input(int Length = 0, bool Blocking = true) { while (true) { if (!this.IsConnected) return ""; this._Read(); // Amount of bytes? if (Length > 0 && this._Buffer.Length >= Length) { // Gets the data string Data = this._Buffer.Substring(0, Length); // Removes the data from the buffer this._Buffer = this._Buffer.Substring(Length); return Data; } // Carriage return? int Pos = this._Buffer.IndexOf('\r'); if (Length == 0 && Pos >= 0) { // Gets the data string Data = this._Buffer.Substring(0, Pos); // Removes the data from the buffer this._Buffer = this._Buffer.Substring(Pos + 1); // Removes additional newline if sent if (this._Buffer.Substring(0, 1) == "\n") this._Buffer = this._Buffer.Substring(1); return Data; } // Ctrl+C ? Pos = this._Buffer.IndexOf('\x03'); if (Length == 0 && Pos >= 0) { if (this.EchoEnabled) this.Print("\x08^C\r\n"); this._Buffer = ""; return "\x03"; } // Do we disable blocking? if (!Blocking) return ""; Thread.Sleep(100); } } /// <summary> /// Prints a text to the screen /// </summary> /// <param name="Text">Text to print</param> /// <param name="NoNewLine">Normally a Print call will print the text and go to the next line. Set this to true to avoid that behaviour.</param> /// <param name="Buffered">When true, data won't be sent immediately but stored in a buffer.</param> public void Print(string Text, bool NoNewLine = false, bool Buffered = false) { if (NoNewLine) this._Write(Text, Buffered); else this._Write(Text + "\r\n", Buffered); } /// <summary>Clears the terminal's screen</summary> public void ClearScreen() { this._Write("\x1b[2J"); } /// <summary>Available colors</summary> public enum Colors { /// <summary>Black</summary> Black = 0, /// <summary>Blue</summary> Blue = 1, /// <summary>Green</summary> Green = 2, /// <summary>Cyan</summary> Cyan = 3, /// <summary>Red</summary> Red = 4, /// <summary>Magenta</summary> Magenta = 5, /// <summary>Brown/orange</summary> Brown = 6, /// <summary>White</summary> White = 7, /// <summary>Gray</summary> Gray = 8, /// <summary>Light blue</summary> LightBlue = 9, /// <summary>Light green</summary> LightGreen = 10, /// <summary>Light cyan</summary> LightCyan = 11, /// <summary>Light red</summary> LightRed = 12, /// <summary>Light magenta</summary> LightMagenta = 13, /// <summary>Yellow</summary> Yellow = 14, /// <summary>High-intensity white</summary> HighIntensityWhite = 15, /// <summary>The default of the terminal</summary> TerminalDefault = 255, } /// <summary> /// Sets the terminal colors /// </summary> /// <param name="Foreground">Forground color</param> public void Color(Colors Foreground) { this.Color(Foreground, (Colors)17); } /// <summary> /// Sets the terminal colors /// </summary> /// <param name="Foreground">Forground color</param> /// <param name="Background">Background color</param> public void Color(Colors Foreground, Colors Background) { string Data = ""; // Foreground color parameters if ((int)Foreground == 0) Data += ";00;30"; // black if ((int)Foreground == 1) Data += ";00;34"; // blue if ((int)Foreground == 2) Data += ";00;32"; // green if ((int)Foreground == 3) Data += ";00;36"; // cyan if ((int)Foreground == 4) Data += ";00;31"; // red if ((int)Foreground == 5) Data += ";00;35"; // magenta if ((int)Foreground == 6) Data += ";00;33"; // brown if ((int)Foreground == 7) Data += ";00;37"; // white if ((int)Foreground == 8) Data += ";01;30"; // gray if ((int)Foreground == 9) Data += ";01;34"; // light blue if ((int)Foreground == 10) Data += ";01;32"; // light green if ((int)Foreground == 11) Data += ";01;36"; // light cyan if ((int)Foreground == 12) Data += ";01;31"; // light red if ((int)Foreground == 13) Data += ";01;35"; // light magenta if ((int)Foreground == 14) Data += ";01;33"; // yellow if ((int)Foreground == 15) Data += ";01;37"; // high-intensity white if ((int)Foreground == 255) Data += ";00;39";// Default color // Background color parameters if ((int)Background == 0) Data += ";40"; // black if ((int)Background == 1) Data += ";44"; // blue if ((int)Background == 2) Data += ";42"; // green if ((int)Background == 3) Data += ";46"; // cyan if ((int)Background == 4) Data += ";41"; // red if ((int)Background == 5) Data += ";45"; // magenta if ((int)Background == 6) Data += ";43"; // brown if ((int)Background == 7) Data += ";47"; // white if ((int)Background == 8) Data += ";40"; // black if ((int)Background == 9) Data += ";44"; // blue if ((int)Background == 10) Data += ";42"; // green if ((int)Background == 11) Data += ";46"; // cyan if ((int)Background == 12) Data += ";41"; // red if ((int)Background == 13) Data += ";45"; // magenta if ((int)Background == 14) Data += ";43"; // brown if ((int)Background == 15) Data += ";47"; // white if ((int)Background == 255) Data += ";49"; // Default color if (Data != "") this._Write("\x1b[" + Data.Substring(1) + "m", true); } /// <summary> /// Moves the cursor position /// </summary> /// <param name="Line">Line (starts at 1 instead of 0!)</param> /// <param name="Column">Column (starts at 1 instead of 0!)</param> /// <param name="Buffered">When true, data won't be sent immediately but stored in a buffer.</param> public void Locate(int Line, int Column, bool Buffered = false) { this._Write("\x1b[" + Line.ToString() + ";" + Column.ToString() + "f", Buffered); } } }