context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace dotless.Core.Parser.Tree { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Exceptions; using Infrastructure; using Infrastructure.Nodes; using Utils; public class Color : Node, IOperable, IComparable { private static readonly Dictionary<string, int> Html4Colors = new Dictionary<string, int> { {"aliceblue", 0xf0f8ff}, {"antiquewhite", 0xfaebd7}, {"aqua", 0x00ffff}, {"aquamarine", 0x7fffd4}, {"azure", 0xf0ffff}, {"beige", 0xf5f5dc}, {"bisque", 0xffe4c4}, {"black", 0x000000}, {"blanchedalmond", 0xffebcd}, {"blue", 0x0000ff}, {"blueviolet", 0x8a2be2}, {"brown", 0xa52a2a}, {"burlywood", 0xdeb887}, {"cadetblue", 0x5f9ea0}, {"chartreuse", 0x7fff00}, {"chocolate", 0xd2691e}, {"coral", 0xff7f50}, {"cornflowerblue", 0x6495ed}, {"cornsilk", 0xfff8dc}, {"crimson", 0xdc143c}, {"cyan", 0x00ffff}, {"darkblue", 0x00008b}, {"darkcyan", 0x008b8b}, {"darkgoldenrod", 0xb8860b}, {"darkgray", 0xa9a9a9}, {"darkgrey", 0xa9a9a9}, {"darkgreen", 0x006400}, {"darkkhaki", 0xbdb76b}, {"darkmagenta", 0x8b008b}, {"darkolivegreen", 0x556b2f}, {"darkorange", 0xff8c00}, {"darkorchid", 0x9932cc}, {"darkred", 0x8b0000}, {"darksalmon", 0xe9967a}, {"darkseagreen", 0x8fbc8f}, {"darkslateblue", 0x483d8b}, {"darkslategray", 0x2f4f4f}, {"darkslategrey", 0x2f4f4f}, {"darkturquoise", 0x00ced1}, {"darkviolet", 0x9400d3}, {"deeppink", 0xff1493}, {"deepskyblue", 0x00bfff}, {"dimgray", 0x696969}, {"dimgrey", 0x696969}, {"dodgerblue", 0x1e90ff}, {"firebrick", 0xb22222}, {"floralwhite", 0xfffaf0}, {"forestgreen", 0x228b22}, {"fuchsia", 0xff00ff}, {"gainsboro", 0xdcdcdc}, {"ghostwhite", 0xf8f8ff}, {"gold", 0xffd700}, {"goldenrod", 0xdaa520}, {"gray", 0x808080}, {"grey", 0x808080}, {"green", 0x008000}, {"greenyellow", 0xadff2f}, {"honeydew", 0xf0fff0}, {"hotpink", 0xff69b4}, {"indianred", 0xcd5c5c}, {"indigo", 0x4b0082}, {"ivory", 0xfffff0}, {"khaki", 0xf0e68c}, {"lavender", 0xe6e6fa}, {"lavenderblush", 0xfff0f5}, {"lawngreen", 0x7cfc00}, {"lemonchiffon", 0xfffacd}, {"lightblue", 0xadd8e6}, {"lightcoral", 0xf08080}, {"lightcyan", 0xe0ffff}, {"lightgoldenrodyellow", 0xfafad2}, {"lightgray", 0xd3d3d3}, {"lightgrey", 0xd3d3d3}, {"lightgreen", 0x90ee90}, {"lightpink", 0xffb6c1}, {"lightsalmon", 0xffa07a}, {"lightseagreen", 0x20b2aa}, {"lightskyblue", 0x87cefa}, {"lightslategray", 0x778899}, {"lightslategrey", 0x778899}, {"lightsteelblue", 0xb0c4de}, {"lightyellow", 0xffffe0}, {"lime", 0x00ff00}, {"limegreen", 0x32cd32}, {"linen", 0xfaf0e6}, {"magenta", 0xff00ff}, {"maroon", 0x800000}, {"mediumaquamarine", 0x66cdaa}, {"mediumblue", 0x0000cd}, {"mediumorchid", 0xba55d3}, {"mediumpurple", 0x9370d8}, {"mediumseagreen", 0x3cb371}, {"mediumslateblue", 0x7b68ee}, {"mediumspringgreen", 0x00fa9a}, {"mediumturquoise", 0x48d1cc}, {"mediumvioletred", 0xc71585}, {"midnightblue", 0x191970}, {"mintcream", 0xf5fffa}, {"mistyrose", 0xffe4e1}, {"moccasin", 0xffe4b5}, {"navajowhite", 0xffdead}, {"navy", 0x000080}, {"oldlace", 0xfdf5e6}, {"olive", 0x808000}, {"olivedrab", 0x6b8e23}, {"orange", 0xffa500}, {"orangered", 0xff4500}, {"orchid", 0xda70d6}, {"palegoldenrod", 0xeee8aa}, {"palegreen", 0x98fb98}, {"paleturquoise", 0xafeeee}, {"palevioletred", 0xd87093}, {"papayawhip", 0xffefd5}, {"peachpuff", 0xffdab9}, {"peru", 0xcd853f}, {"pink", 0xffc0cb}, {"plum", 0xdda0dd}, {"powderblue", 0xb0e0e6}, {"purple", 0x800080}, {"red", 0xff0000}, {"rosybrown", 0xbc8f8f}, {"royalblue", 0x4169e1}, {"saddlebrown", 0x8b4513}, {"salmon", 0xfa8072}, {"sandybrown", 0xf4a460}, {"seagreen", 0x2e8b57}, {"seashell", 0xfff5ee}, {"sienna", 0xa0522d}, {"silver", 0xc0c0c0}, {"skyblue", 0x87ceeb}, {"slateblue", 0x6a5acd}, {"slategray", 0x708090}, {"slategrey", 0x708090}, {"snow", 0xfffafa}, {"springgreen", 0x00ff7f}, {"steelblue", 0x4682b4}, {"tan", 0xd2b48c}, {"teal", 0x008080}, {"thistle", 0xd8bfd8}, {"tomato", 0xff6347}, {"turquoise", 0x40e0d0}, {"violet", 0xee82ee}, {"wheat", 0xf5deb3}, {"white", 0xffffff}, {"whitesmoke", 0xf5f5f5}, {"yellow", 0xffff00}, {"yellowgreen", 0x9acd32} }; private static readonly Dictionary<int, string> Html4ColorsReverse = Html4Colors.GroupBy(kvp => kvp.Value).ToDictionary(g => g.Key, g => g.First().Key); public static Color From(string keywordOrHex) { return GetColorFromKeyword(keywordOrHex) ?? FromHex(keywordOrHex); } public static Color GetColorFromKeyword(string keyword) { if (keyword == "transparent") { return new Color(0, 0, 0, 0.0, keyword); } int rgb; if (Html4Colors.TryGetValue(keyword, out rgb)) { var r = (rgb >> 16) & 0xFF; var g = (rgb >> 8) & 0xFF; var b = rgb & 0xFF; return new Color(r, g, b, 1.0, keyword); } return null; } public static string GetKeyword(int[] rgb) { var color = (rgb[0] << 16) + (rgb[1] << 8) + rgb[2]; string keyword; if (Html4ColorsReverse.TryGetValue(color, out keyword)) { return keyword; } return null; } public static Color FromHex(string hex) { hex = hex.TrimStart('#'); double[] rgb; var alpha = 1.0; var text = '#' + hex; if (hex.Length == 8) { rgb = ParseRgb(hex.Substring(2)); alpha = Parse(hex.Substring(0, 2))/255.0; } else if (hex.Length == 6) { rgb = ParseRgb(hex); } else { rgb = hex.ToCharArray().Select(c => Parse("" + c + c)).ToArray(); } return new Color(rgb, alpha, text); } private static double[] ParseRgb(string hex) { return Enumerable.Range(0, 3) .Select(i => hex.Substring(i*2, 2)) .Select(Parse) .ToArray(); } private static double Parse(string hex) { return int.Parse(hex, NumberStyles.HexNumber); } private readonly string _text; public Color(int color) { RGB = new double[3]; B = color & 0xff; color >>= 8; G = color & 0xff; color >>= 8; R = color & 0xff; Alpha = 1; } public Color(string hex) { hex = hex.TrimStart('#'); double[] rgb; var alpha = 1.0; var text = '#' + hex; if (hex.Length == 8) { rgb = ParseRgb(hex.Substring(2)); alpha = Parse(hex.Substring(0, 2))/255.0; } else if (hex.Length == 6) { rgb = ParseRgb(hex); } else { rgb = hex.ToCharArray().Select(c => Parse("" + c + c)).ToArray(); } R = rgb[0]; G = rgb[1]; B = rgb[2]; Alpha = alpha; _text = text; } public Color(IEnumerable<Number> rgb, Number alpha) { RGB = rgb.Select(d => d.Normalize()).ToArray(); Alpha = alpha.Normalize(); } public Color(double r, double g, double b) : this(r, g, b, 1) { } public Color(double r, double g, double b, double alpha) : this(new[] {r, g, b}, alpha) { } public Color(double[] rgb) : this(rgb, 1) { } public Color(double[] rgb, double alpha) : this(rgb, alpha, null) { } public Color(double[] rgb, double alpha, string text) { RGB = rgb.Select(c => NumberExtensions.Normalize(c, 255.0)).ToArray(); Alpha = NumberExtensions.Normalize(alpha, 1.0); _text = text; } public Color(double red, double green, double blue, double alpha = 1.0, string text = null) : this(new[] {red, green, blue}, alpha, text) { } // TODO: A RGB color should really be represented by int[], or better: a compressed int. public readonly double[] RGB = new double[3]; public readonly double Alpha; public double R { get { return RGB[0]; } set { RGB[0] = value; } } public double G { get { return RGB[1]; } set { RGB[1] = value; } } public double B { get { return RGB[2]; } set { RGB[2] = value; } } /// <summary> /// Transforms the linear to SRBG. Formula derivation decscribed <a href="http://en.wikipedia.org/wiki/SRGB#Theory_of_the_transformation">here</a> /// </summary> /// <param name="linearChannel">The linear channel, for example R/255</param> /// <returns>The sRBG value for the given channel</returns> private double TransformLinearToSrbg(double linearChannel) { const double decodingGamma = 2.4; const double phi = 12.92; const double alpha = .055; return (linearChannel <= 0.03928) ? linearChannel / phi : Math.Pow(((linearChannel + alpha) / (1 + alpha)), decodingGamma); } /// <summary> /// Calculates the luma value based on the <a href="http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef">W3 Standard</a> /// </summary> /// <value> /// The luma value for the current color /// </value> public double Luma { get { var linearR = R / 255; var linearG = G / 255; var linearB = B / 255; var red = TransformLinearToSrbg(linearR); var green = TransformLinearToSrbg(linearG); var blue = TransformLinearToSrbg(linearB); return 0.2126 * red + 0.7152 * green + 0.0722 * blue; } } protected override Node CloneCore() { return new Color(RGB.ToArray(), Alpha); } public override void AppendCSS(Env env) { if (_text != null) { env.Output.Append(_text); return; } var rgb = ConvertToInt(RGB); if (Alpha < 1.0) { env.Output.AppendFormat("rgba({0}, {1}, {2}, {3})", rgb[0], rgb[1], rgb[2], Alpha); return; } var hex = GetHexString(rgb); env.Output.Append(hex); } private List<int> ConvertToInt(IEnumerable<double> rgb) { return rgb.Select(d => (int) Math.Round(d, MidpointRounding.AwayFromZero)).ToList(); } private string GetHexString(IEnumerable<int> rgb) { return '#' + rgb.Select(i => i.ToString("x2")).JoinStrings(""); } public Node Operate(Operation op, Node other) { var color = other as Color; var operable = other as IOperable; if (color == null && operable == null) { var msg = string.Format("Unable to convert right hand side of {0} to a color", op.Operator); throw new ParsingException(msg, op.Location); } color = color ?? operable.ToColor(); var rgb = Enumerable.Range(0, 3) .Select(i => Operation.Operate(op.Operator, RGB[i], color.RGB[i])) .ToArray(); return new Color(rgb, 1.0).ReducedFrom<Node>(this, other); } public Color ToColor() { return this; } /// <summary> /// Returns in the IE ARGB format e.g ##FF001122 = rgba(0x00, 0x11, 0x22, 1) /// </summary> /// <returns></returns> public string ToArgb() { var values = new[] {Alpha*255}.Concat(RGB); var argb = ConvertToInt(values); return GetHexString(argb); } public int CompareTo(object obj) { var col = obj as Color; if (col == null) { return -1; } if (col.R == R && col.G == G && col.B == B && col.Alpha == Alpha) { return 0; } return (((256 * 3) - (col.R + col.G + col.B)) * col.Alpha) < (((256 * 3) - (R + G + B)) * Alpha) ? 1 : -1; } public static explicit operator System.Drawing.Color(Color color) { if (color == null) throw new ArgumentNullException("color"); return System.Drawing.Color.FromArgb((int) Math.Round(color.Alpha * 255d), (int) color.R, (int) color.G, (int) color.B); } } }
using System; using Csla; using Csla.Data; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; using DalEf; using System.Collections.Generic; namespace BusinessObjects.Documents { [Serializable] public partial class cDocuments_PaymentClosureG: CoreBusinessChildClass<cDocuments_PaymentClosureG> { public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo< System.Int32 > documents_PaymentItemsColIdProperty = RegisterProperty<System.Int32>(p => p.Documents_PaymentItemsColId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 Documents_PaymentItemsColId { get { return GetProperty(documents_PaymentItemsColIdProperty); } set { SetProperty(documents_PaymentItemsColIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > payedInvoiceDocumentIdProperty = RegisterProperty<System.Int32?>(p => p.PayedInvoiceDocumentId, string.Empty,(System.Int32?)null); public System.Int32? PayedInvoiceDocumentId { get { return GetProperty(payedInvoiceDocumentIdProperty); } set { SetProperty(payedInvoiceDocumentIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > payedQuoteDocumentIdProperty = RegisterProperty<System.Int32?>(p => p.PayedQuoteDocumentId, string.Empty,(System.Int32?)null); public System.Int32? PayedQuoteDocumentId { get { return GetProperty(payedQuoteDocumentIdProperty); } set { SetProperty(payedQuoteDocumentIdProperty, value); } } private static readonly PropertyInfo< System.Decimal > ammountProperty = RegisterProperty<System.Decimal>(p => p.Ammount, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Decimal Ammount { get { return GetProperty(ammountProperty); } set { SetProperty(ammountProperty, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; public static cDocuments_PaymentClosureG NewDocuments_PaymentClosureG() { return DataPortal.CreateChild<cDocuments_PaymentClosureG>(); } public static cDocuments_PaymentClosureG GetDocuments_PaymentClosureG(Documents_PaymentClosureGCol data) { return DataPortal.FetchChild<cDocuments_PaymentClosureG>(data); } #region Data Access [RunLocal] protected override void Child_Create() { BusinessRules.CheckRules(); } private void Child_Fetch(Documents_PaymentClosureGCol data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(documents_PaymentItemsColIdProperty, data.Documents_PaymentItemsColId); LoadProperty<int?>(payedInvoiceDocumentIdProperty, data.PayedInvoiceDocumentId); LoadProperty<int?>(payedQuoteDocumentIdProperty, data.PayedQuoteDocumentId); LoadProperty<decimal>(ammountProperty, data.Ammount); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } private void Child_Insert(Documents_PaymentItemsCol parent) { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_PaymentClosureGCol(); data.Documents_PaymentItemsCol = parent; data.PayedInvoiceDocumentId = ReadProperty<int?>(payedInvoiceDocumentIdProperty); data.PayedQuoteDocumentId = ReadProperty<int?>(payedQuoteDocumentIdProperty); data.Ammount = ReadProperty<decimal>(ammountProperty); ctx.ObjectContext.AddToDocuments_PaymentClosureGCol(data); data.PropertyChanged += (o, e) => { if (e.PropertyName == "Id") { LoadProperty<int>(IdProperty, data.Id); LoadProperty<int>(documents_PaymentItemsColIdProperty, data.Documents_PaymentItemsColId); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LastChanged = data.LastChanged; } }; ctx.ObjectContext.SaveChanges(); } } private void Child_Update() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_PaymentClosureGCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.PayedInvoiceDocumentId = ReadProperty<int?>(payedInvoiceDocumentIdProperty); data.PayedQuoteDocumentId = ReadProperty<int?>(payedQuoteDocumentIdProperty); data.Ammount = ReadProperty<decimal>(ammountProperty); data.PropertyChanged += (o, e) => { if (e.PropertyName == "LastChanged") LastChanged = data.LastChanged; }; ctx.ObjectContext.SaveChanges(); } } private void Child_DeleteSelf() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_PaymentClosureGCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; //data.SubjectId = parent.Id; ctx.ObjectContext.Attach(data); ctx.ObjectContext.DeleteObject(data); ctx.ObjectContext.SaveChanges(); } } #endregion } [Serializable] public partial class cDocuments_PaymentClosureGCol : BusinessListBase<cDocuments_PaymentClosureGCol, cDocuments_PaymentClosureG> { internal static cDocuments_PaymentClosureGCol NewDocuments_PaymentClosureGCol() { return DataPortal.CreateChild<cDocuments_PaymentClosureGCol>(); } public static cDocuments_PaymentClosureGCol GetDocuments_PaymentClosureGCol(IEnumerable<Documents_PaymentClosureGCol> dataSet) { var childList = new cDocuments_PaymentClosureGCol(); childList.Fetch(dataSet); return childList; } #region Data Access private void Fetch(IEnumerable<Documents_PaymentClosureGCol> dataSet) { RaiseListChangedEvents = false; foreach (var data in dataSet) this.Add(cDocuments_PaymentClosureG.GetDocuments_PaymentClosureG(data)); RaiseListChangedEvents = true; } #endregion //Data Access } }
using System; using System.Collections.Specialized; using System.IO; using System.Text.RegularExpressions; using System.Threading; using SIL.PlatformUtilities; using SIL.Reporting; namespace SIL.IO { /// <summary> /// Desktop-specific utility methods for processing files, e.g. methods that report to the user. /// </summary> public static class FileUtils { public static StringCollection TextFileExtensions { get { return Properties.Settings.Default.TextFileExtensions; } } public static StringCollection AudioFileExtensions { get { return Properties.Settings.Default.AudioFileExtensions; } } public static StringCollection VideoFileExtensions { get { return Properties.Settings.Default.VideoFileExtensions; } } public static StringCollection ImageFileExtensions { get { return Properties.Settings.Default.ImageFileExtensions; } } public static StringCollection DatasetFileExtensions { get { return Properties.Settings.Default.DatasetFileExtensions; } } public static StringCollection SoftwareAndFontFileExtensions { get { return Properties.Settings.Default.SoftwareAndFontFileExtensions; } } public static StringCollection PresentationFileExtensions { get { return Properties.Settings.Default.PresentationFileExtensions; } } public static StringCollection MusicalNotationFileExtensions { get { return Properties.Settings.Default.MusicalNotationFileExtensions; } } public static StringCollection ZipFileExtensions { get { return Properties.Settings.Default.ZipFileExtensions; } } public static bool GetIsZipFile(string path) { return GetIsSpecifiedFileType(ZipFileExtensions, path); } public static bool GetIsText(string path) { return GetIsSpecifiedFileType(TextFileExtensions, path); } public static bool GetIsAudio(string path) { return GetIsSpecifiedFileType(AudioFileExtensions, path); } public static bool GetIsVideo(string path) { return GetIsSpecifiedFileType(VideoFileExtensions, path); } public static bool GetIsMusicalNotation(string path) { return GetIsSpecifiedFileType(MusicalNotationFileExtensions, path); } public static bool GetIsDataset(string path) { return GetIsSpecifiedFileType(DatasetFileExtensions, path); } public static bool GetIsSoftwareOrFont(string path) { return GetIsSpecifiedFileType(SoftwareAndFontFileExtensions, path); } public static bool GetIsPresentation(string path) { return GetIsSpecifiedFileType(PresentationFileExtensions, path); } public static bool GetIsImage(string path) { return GetIsSpecifiedFileType(ImageFileExtensions, path); } private static bool GetIsSpecifiedFileType(StringCollection extensions, string path) { var extension = Path.GetExtension(path); return (extension != null) && extensions.Contains(extension.ToLower()); } /// <summary> /// NB: This will show a dialog if the file writing can't be done (subject to Palaso.Reporting settings). /// It will throw whatever exception was encountered, if the user can't resolve it. /// </summary> /// <param name="inputPath"></param> /// <param name="pattern"></param> /// <param name="replaceWith"></param> public static void GrepFile(string inputPath, string pattern, string replaceWith) { Regex regex = new Regex(pattern, RegexOptions.Compiled); string tempPath = inputPath + ".tmp"; using (StreamReader reader = File.OpenText(inputPath)) { using (StreamWriter writer = new StreamWriter(tempPath)) { while (!reader.EndOfStream) { writer.WriteLine(regex.Replace(reader.ReadLine(), replaceWith)); } writer.Close(); } reader.Close(); } //string backupPath = GetUniqueFileName(inputPath); string backupPath = inputPath + ".bak"; ReplaceFileWithUserInteractionIfNeeded(tempPath, inputPath, backupPath); } /// <summary> /// If there is a problem doing the replace, a dialog is shown which tells the user /// what happened, and lets them try to fix it. It also lets them "Give up", in /// which case this returns False. /// /// To help with situations where something may temporarily be holding on to the file, /// this will retry for up to 5 seconds. /// </summary> /// <param name="sourcePath"></param> /// <param name="destinationPath"></param> /// <param name="backupPath">can be null if you don't want a replacement</param> /// <returns>if the user gives up, throws whatever exception the file system gave</returns> public static void ReplaceFileWithUserInteractionIfNeeded(string sourcePath, string destinationPath, string backupPath) { bool succeeded = false; do { try { if (UnsafeForFileReplaceMethod(sourcePath) || UnsafeForFileReplaceMethod(destinationPath) || (!string.IsNullOrEmpty(backupPath) && !PathHelper.AreOnSameVolume(sourcePath,backupPath)) || !PathHelper.AreOnSameVolume(sourcePath, destinationPath) || !File.Exists(destinationPath) ) { //can't use File.Replace or File.Move across volumes (sigh) RobustFile.ReplaceByCopyDelete(sourcePath, destinationPath, backupPath); } else { var giveUpTime = DateTime.Now.AddSeconds(5); Exception theProblem; do { theProblem = null; try { File.Replace(sourcePath, destinationPath, backupPath); } catch (UnauthorizedAccessException uae) { // We were getting this while trying to Replace on a JAARS network drive. // The network drive is U:\ which maps to \\waxhaw\users\{username}, // so it doesn't get caught by the checks above. // Both files were in the same directory and there were no permissions issues, // but the Replace command was failing with "Access to the path is denied." anyway. // I never could figure out why. See http://issues.bloomlibrary.org/youtrack/issue/BL-4179 try { RobustFile.ReplaceByCopyDelete(sourcePath, destinationPath, backupPath); } catch { // Though it probably doesn't matter, report the original exception since we prefer Replace to CopyDelete. theProblem = uae; Thread.Sleep(100); } } catch (Exception e) { theProblem = e; Thread.Sleep(100); } } while (theProblem != null && DateTime.Now < giveUpTime); if (theProblem != null) throw theProblem; } succeeded = true; } catch (UnauthorizedAccessException error) { ReportFailedReplacement(destinationPath, error); } catch (IOException error) { ReportFailedReplacement(destinationPath, error); } } while (!succeeded); } // NB: I don't actually know for sure that we can't do the replace on these paths; this dev doesn't // have a network to test on. What I do know is that the code checking to see if they are on the // same drive fails for UNC paths, so this at least gets us past that problem private static bool UnsafeForFileReplaceMethod(string path) { if (Platform.IsWindows) return path.StartsWith("//") || path.StartsWith("\\\\"); return false; // we will soon be requesting some testing with networks on Linux; //as a result of that, we might need to do something here, too. Or maybe not. } private static void ReportFailedReplacement(string destinationPath, Exception error) { var message = string.Format("{0} was unable to update the file '{1}'.\n"+ "Possible causes:\n"+ "* Another copy of this program could be running, or some other program might have the file open or locked (including things like Dropbox and antivirus software).\n" + "* The file may be set to 'Read Only'\n"+ "* The security permissions of this file may be set to deny you access to it.\n\n" + "The error was: \n{2}", EntryAssembly.ProductName, destinationPath, error.Message); message = message.Replace("\n", Environment.NewLine); //enhance: this would be clearer if the "OK" button read "Retry", but that's not easily changable. var result = ErrorReport.NotifyUserOfProblem(new ShowAlwaysPolicy(), "Give Up", ErrorResult.No, message); if (result == ErrorResult.No) { throw error; // pass it up to the caller } } [Obsolete("Use FileHelper.IsLocked()")] public static bool IsFileLocked(string filePath) { return FileHelper.IsLocked(filePath); } [Obsolete("Use FileHelper.Grep()")] public static bool GrepFile(string inputPath, string pattern) { return FileHelper.Grep(inputPath, pattern); } /// <summary> /// Make sure the given <paramref name="pathToFile"/> file is 'valid'. /// /// Valid means that /// 1. <paramref name="pathToFile"/> must not be null or an empty string /// 2. <paramref name="pathToFile"/> must exist, and /// 3. The extension for <paramref name="pathToFile"/> must equal <paramref name="expectedExtension"/> /// (Or both must be null) /// </summary> [Obsolete("Use PathHelper.CheckValidPathname()")] public static bool CheckValidPathname(string pathToFile, string expectedExtension) { return PathHelper.CheckValidPathname(pathToFile, expectedExtension); } [Obsolete("Use RobustFile.ReplaceByCopyDelete()")] public static void ReplaceByCopyDelete(string sourcePath, string destinationPath, string backupPath) { RobustFile.ReplaceByCopyDelete(sourcePath, destinationPath, backupPath); } /// <summary> /// When calling external exe's on Windows any non-ascii characters can get converted to '?'. This /// will convert them to 8.3 format which is all ascii (and do nothing on Linux). /// </summary> [Obsolete("Use PathHelper.MakePathSafeFromEncodingProblems()")] public static string MakePathSafeFromEncodingProblems(string path) { return PathHelper.MakePathSafeFromEncodingProblems(path); } /// <summary> /// Normalize the path so that it uses forward slashes instead of backslashes. This is /// useful when a path gets read from a file that gets shared between Windows and Linux - /// if the path contains backslashes it can't be found on Linux. /// </summary> [Obsolete("Use PathHelper.NormalizePath()")] public static string NormalizePath(string path) { return PathHelper.NormalizePath(path); } /// <summary> /// Strips file URI prefix from the beginning of a file URI string, and keeps /// a beginning slash if in Linux. /// eg "file:///C:/Windows" becomes "C:/Windows" in Windows, and /// "file:///usr/bin" becomes "/usr/bin" in Linux. /// Returns the input unchanged if it does not begin with "file:". /// /// Does not convert the result into a valid path or a path using current platform /// path separators. /// /// See uri.LocalPath, http://en.wikipedia.org/wiki/File_URI , and /// http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx . /// </summary> [Obsolete("Use PathHelper.StripFilePrefix()")] public static string StripFilePrefix(string fileString) { return PathHelper.StripFilePrefix(fileString); } } }
using YAF.Lucene.Net.Support; namespace YAF.Lucene.Net.Search.Similarities { /* * 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 AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using FieldInvertState = YAF.Lucene.Net.Index.FieldInvertState; using NumericDocValues = YAF.Lucene.Net.Index.NumericDocValues; /// <summary> /// Implementation of <see cref="Similarity"/> with the Vector Space Model. /// <para/> /// Expert: Scoring API. /// <para/>TFIDFSimilarity defines the components of Lucene scoring. /// Overriding computation of these components is a convenient /// way to alter Lucene scoring. /// /// <para/>Suggested reading: /// <a href="http://nlp.stanford.edu/IR-book/html/htmledition/queries-as-vectors-1.html"> /// Introduction To Information Retrieval, Chapter 6</a>. /// /// <para/>The following describes how Lucene scoring evolves from /// underlying information retrieval models to (efficient) implementation. /// We first brief on <i>VSM Score</i>, /// then derive from it <i>Lucene's Conceptual Scoring Formula</i>, /// from which, finally, evolves <i>Lucene's Practical Scoring Function</i> /// (the latter is connected directly with Lucene classes and methods). /// /// <para/>Lucene combines /// <a href="http://en.wikipedia.org/wiki/Standard_Boolean_model"> /// Boolean model (BM) of Information Retrieval</a> /// with /// <a href="http://en.wikipedia.org/wiki/Vector_Space_Model"> /// Vector Space Model (VSM) of Information Retrieval</a> - /// documents "approved" by BM are scored by VSM. /// /// <para/>In VSM, documents and queries are represented as /// weighted vectors in a multi-dimensional space, /// where each distinct index term is a dimension, /// and weights are /// <a href="http://en.wikipedia.org/wiki/Tfidf">Tf-idf</a> values. /// /// <para/>VSM does not require weights to be <i>Tf-idf</i> values, /// but <i>Tf-idf</i> values are believed to produce search results of high quality, /// and so Lucene is using <i>Tf-idf</i>. /// <i>Tf</i> and <i>Idf</i> are described in more detail below, /// but for now, for completion, let's just say that /// for given term <i>t</i> and document (or query) <i>x</i>, /// <i>Tf(t,x)</i> varies with the number of occurrences of term <i>t</i> in <i>x</i> /// (when one increases so does the other) and /// <i>idf(t)</i> similarly varies with the inverse of the /// number of index documents containing term <i>t</i>. /// /// <para/><i>VSM score</i> of document <i>d</i> for query <i>q</i> is the /// <a href="http://en.wikipedia.org/wiki/Cosine_similarity"> /// Cosine Similarity</a> /// of the weighted query vectors <i>V(q)</i> and <i>V(d)</i>: /// <para/> /// <list type="table"> /// <item> /// <term> /// <list type="table"> /// <item> /// <term>cosine-similarity(q,d) &#160; = &#160;</term> /// <term> /// <table> /// <item><term><small>V(q)&#160;&#183;&#160;V(d)</small></term></item> /// <item><term>&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;</term></item> /// <item><term><small>|V(q)|&#160;|V(d)|</small></term></item> /// </table> /// </term> /// </item> /// </list> /// </term> /// </item> /// <item> /// <term>VSM Score</term> /// </item> /// </list> /// <para/> /// /// /// Where <i>V(q)</i> &#183; <i>V(d)</i> is the /// <a href="http://en.wikipedia.org/wiki/Dot_product">dot product</a> /// of the weighted vectors, /// and <i>|V(q)|</i> and <i>|V(d)|</i> are their /// <a href="http://en.wikipedia.org/wiki/Euclidean_norm#Euclidean_norm">Euclidean norms</a>. /// /// <para/>Note: the above equation can be viewed as the dot product of /// the normalized weighted vectors, in the sense that dividing /// <i>V(q)</i> by its euclidean norm is normalizing it to a unit vector. /// /// <para/>Lucene refines <i>VSM score</i> for both search quality and usability: /// <list type="bullet"> /// <item><description>Normalizing <i>V(d)</i> to the unit vector is known to be problematic in that /// it removes all document length information. /// For some documents removing this info is probably ok, /// e.g. a document made by duplicating a certain paragraph <i>10</i> times, /// especially if that paragraph is made of distinct terms. /// But for a document which contains no duplicated paragraphs, /// this might be wrong. /// To avoid this problem, a different document length normalization /// factor is used, which normalizes to a vector equal to or larger /// than the unit vector: <i>doc-len-norm(d)</i>. /// </description></item> /// /// <item><description>At indexing, users can specify that certain documents are more /// important than others, by assigning a document boost. /// For this, the score of each document is also multiplied by its boost value /// <i>doc-boost(d)</i>. /// </description></item> /// /// <item><description>Lucene is field based, hence each query term applies to a single /// field, document length normalization is by the length of the certain field, /// and in addition to document boost there are also document fields boosts. /// </description></item> /// /// <item><description>The same field can be added to a document during indexing several times, /// and so the boost of that field is the multiplication of the boosts of /// the separate additions (or parts) of that field within the document. /// </description></item> /// /// <item><description>At search time users can specify boosts to each query, sub-query, and /// each query term, hence the contribution of a query term to the score of /// a document is multiplied by the boost of that query term <i>query-boost(q)</i>. /// </description></item> /// /// <item><description>A document may match a multi term query without containing all /// the terms of that query (this is correct for some of the queries), /// and users can further reward documents matching more query terms /// through a coordination factor, which is usually larger when /// more terms are matched: <i>coord-factor(q,d)</i>. /// </description></item> /// </list> /// /// <para/>Under the simplifying assumption of a single field in the index, /// we get <i>Lucene's Conceptual scoring formula</i>: /// /// <para/> /// <list type="table"> /// <item> /// <term> /// <list type="table"> /// <item> /// <term> /// score(q,d) &#160; = &#160; /// <font color="#FF9933">coord-factor(q,d)</font> &#183; &#160; /// <font color="#CCCC00">query-boost(q)</font> &#183; &#160; /// </term> /// <term> /// <list type="table"> /// <item><term><small><font color="#993399">V(q)&#160;&#183;&#160;V(d)</font></small></term></item> /// <item><term>&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;</term></item> /// <item><term><small><font color="#FF33CC">|V(q)|</font></small></term></item> /// </list> /// </term> /// <term> /// &#160; &#183; &#160; <font color="#3399FF">doc-len-norm(d)</font> /// &#160; &#183; &#160; <font color="#3399FF">doc-boost(d)</font> /// </term> /// </item> /// </list> /// </term> /// </item> /// <item> /// <term>Lucene Conceptual Scoring Formula</term> /// </item> /// </list> /// <para/> /// /// /// <para/>The conceptual formula is a simplification in the sense that (1) terms and documents /// are fielded and (2) boosts are usually per query term rather than per query. /// /// <para/>We now describe how Lucene implements this conceptual scoring formula, and /// derive from it <i>Lucene's Practical Scoring Function</i>. /// /// <para/>For efficient score computation some scoring components /// are computed and aggregated in advance: /// /// <list type="bullet"> /// <item><description><i>Query-boost</i> for the query (actually for each query term) /// is known when search starts. /// </description></item> /// /// <item><description>Query Euclidean norm <i>|V(q)|</i> can be computed when search starts, /// as it is independent of the document being scored. /// From search optimization perspective, it is a valid question /// why bother to normalize the query at all, because all /// scored documents will be multiplied by the same <i>|V(q)|</i>, /// and hence documents ranks (their order by score) will not /// be affected by this normalization. /// There are two good reasons to keep this normalization: /// <list type="bullet"> /// <item><description>Recall that /// <a href="http://en.wikipedia.org/wiki/Cosine_similarity"> /// Cosine Similarity</a> can be used find how similar /// two documents are. One can use Lucene for e.g. /// clustering, and use a document as a query to compute /// its similarity to other documents. /// In this use case it is important that the score of document <i>d3</i> /// for query <i>d1</i> is comparable to the score of document <i>d3</i> /// for query <i>d2</i>. In other words, scores of a document for two /// distinct queries should be comparable. /// There are other applications that may require this. /// And this is exactly what normalizing the query vector <i>V(q)</i> /// provides: comparability (to a certain extent) of two or more queries. /// </description></item> /// /// <item><description>Applying query normalization on the scores helps to keep the /// scores around the unit vector, hence preventing loss of score data /// because of floating point precision limitations. /// </description></item> /// </list> /// </description></item> /// /// <item><description>Document length norm <i>doc-len-norm(d)</i> and document /// boost <i>doc-boost(d)</i> are known at indexing time. /// They are computed in advance and their multiplication /// is saved as a single value in the index: <i>norm(d)</i>. /// (In the equations below, <i>norm(t in d)</i> means <i>norm(field(t) in doc d)</i> /// where <i>field(t)</i> is the field associated with term <i>t</i>.) /// </description></item> /// </list> /// /// <para/><i>Lucene's Practical Scoring Function</i> is derived from the above. /// The color codes demonstrate how it relates /// to those of the <i>conceptual</i> formula: /// /// <para/> /// <list type="table"> /// <item> /// <term> /// <list type="table"> /// <item> /// <term> /// score(q,d) &#160; = &#160; /// <a href="#formula_coord"><font color="#FF9933">coord(q,d)</font></a> &#160; &#183; &#160; /// <a href="#formula_queryNorm"><font color="#FF33CC">queryNorm(q)</font></a> &#160; &#183; &#160; /// </term> /// <term><big><big><big>&#8721;</big></big></big></term> /// <term> /// <big><big>(</big></big> /// <a href="#formula_tf"><font color="#993399">tf(t in d)</font></a> &#160; &#183; &#160; /// <a href="#formula_idf"><font color="#993399">idf(t)</font></a><sup>2</sup> &#160; &#183; &#160; /// <a href="#formula_termBoost"><font color="#CCCC00">t.Boost</font></a> &#160; &#183; &#160; /// <a href="#formula_norm"><font color="#3399FF">norm(t,d)</font></a> /// <big><big>)</big></big> /// </term> /// </item> /// <item> /// <term></term> /// <term><small>t in q</small></term> /// <term></term> /// </item> /// </list> /// </term> /// </item> /// <item> /// <term>Lucene Practical Scoring Function</term> /// </item> /// </list> /// /// <para/> where /// <list type="number"> /// <item><description> /// <a name="formula_tf"></a> /// <b><i>tf(t in d)</i></b> /// correlates to the term's <i>frequency</i>, /// defined as the number of times term <i>t</i> appears in the currently scored document <i>d</i>. /// Documents that have more occurrences of a given term receive a higher score. /// Note that <i>tf(t in q)</i> is assumed to be <i>1</i> and therefore it does not appear in this equation, /// However if a query contains twice the same term, there will be /// two term-queries with that same term and hence the computation would still be correct (although /// not very efficient). /// The default computation for <i>tf(t in d)</i> in /// DefaultSimilarity (<see cref="Lucene.Net.Search.Similarities.DefaultSimilarity.Tf(float)"/>) is: /// /// <para/> /// <list type="table"> /// <item> /// <term> /// tf(t in d) &#160; = &#160; /// </term> /// <term> /// frequency<sup><big>&#189;</big></sup> /// </term> /// </item> /// </list> /// <para/> /// /// </description></item> /// /// <item><description> /// <a name="formula_idf"></a> /// <b><i>idf(t)</i></b> stands for Inverse Document Frequency. this value /// correlates to the inverse of <i>DocFreq</i> /// (the number of documents in which the term <i>t</i> appears). /// this means rarer terms give higher contribution to the total score. /// <i>idf(t)</i> appears for <i>t</i> in both the query and the document, /// hence it is squared in the equation. /// The default computation for <i>idf(t)</i> in /// DefaultSimilarity (<see cref="Lucene.Net.Search.Similarities.DefaultSimilarity.Idf(long, long)"/>) is: /// /// <para/> /// <list type="table"> /// <item> /// <term>idf(t) &#160; = &#160;</term> /// <term>1 + log <big>(</big></term> /// <term> /// <list type="table"> /// <item><term><small>NumDocs</small></term></item> /// <item><term>&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;</term></item> /// <item><term><small>DocFreq+1</small></term></item> /// </list> /// </term> /// <term><big>)</big></term> /// </item> /// </list> /// <para/> /// /// </description></item> /// /// <item><description> /// <a name="formula_coord"></a> /// <b><i>coord(q,d)</i></b> /// is a score factor based on how many of the query terms are found in the specified document. /// Typically, a document that contains more of the query's terms will receive a higher score /// than another document with fewer query terms. /// this is a search time factor computed in /// coord(q,d) (<see cref="Coord(int, int)"/>) /// by the Similarity in effect at search time. /// <para/> /// </description></item> /// /// <item><description><b> /// <a name="formula_queryNorm"></a> /// <i>queryNorm(q)</i> /// </b> /// is a normalizing factor used to make scores between queries comparable. /// this factor does not affect document ranking (since all ranked documents are multiplied by the same factor), /// but rather just attempts to make scores from different queries (or even different indexes) comparable. /// this is a search time factor computed by the Similarity in effect at search time. /// /// The default computation in /// DefaultSimilarity (<see cref="Lucene.Net.Search.Similarities.DefaultSimilarity.QueryNorm(float)"/>) /// produces a <a href="http://en.wikipedia.org/wiki/Euclidean_norm#Euclidean_norm">Euclidean norm</a>: /// /// <para/> /// <list type="table"> /// <item> /// <term> /// queryNorm(q) &#160; = &#160; /// queryNorm(sumOfSquaredWeights) /// &#160; = &#160; /// </term> /// <term> /// <list type="table"> /// <item><term><big>1</big></term></item> /// <item><term><big>&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;</big></term></item> /// <item><term>sumOfSquaredWeights<sup><big>&#189;</big></sup></term></item> /// </list> /// </term> /// </item> /// </list> /// <para/> /// /// The sum of squared weights (of the query terms) is /// computed by the query <see cref="Lucene.Net.Search.Weight"/> object. /// For example, a <see cref="Lucene.Net.Search.BooleanQuery"/> /// computes this value as: /// /// <para/> /// <list type="table"> /// <item> /// <term> /// sumOfSquaredWeights &#160; = &#160; /// q.Boost <sup><big>2</big></sup> /// &#160;&#183;&#160; /// </term> /// <term><big><big><big>&#8721;</big></big></big></term> /// <term> /// <big><big>(</big></big> /// <a href="#formula_idf">idf(t)</a> &#160;&#183;&#160; /// <a href="#formula_termBoost">t.Boost</a> /// <big><big>) <sup>2</sup> </big></big> /// </term> /// </item> /// <item> /// <term></term> /// <term><small>t in q</small></term> /// <term></term> /// </item> /// </list> /// where sumOfSquaredWeights is <see cref="Weight.GetValueForNormalization()"/> and /// q.Boost is <see cref="Query.Boost"/> /// <para/> /// </description></item> /// /// <item><description> /// <a name="formula_termBoost"></a> /// <b><i>t.Boost</i></b> /// is a search time boost of term <i>t</i> in the query <i>q</i> as /// specified in the query text /// (see <a href="{@docRoot}/../queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Boosting_a_Term">query syntax</a>), /// or as set by application calls to /// <see cref="Lucene.Net.Search.Query.Boost"/>. /// Notice that there is really no direct API for accessing a boost of one term in a multi term query, /// but rather multi terms are represented in a query as multi /// <see cref="Lucene.Net.Search.TermQuery"/> objects, /// and so the boost of a term in the query is accessible by calling the sub-query /// <see cref="Lucene.Net.Search.Query.Boost"/>. /// <para/> /// </description></item> /// /// <item><description> /// <a name="formula_norm"></a> /// <b><i>norm(t,d)</i></b> encapsulates a few (indexing time) boost and length factors: /// /// <list type="bullet"> /// <item><description><b>Field boost</b> - set /// <see cref="Documents.Field.Boost"/> /// before adding the field to a document. /// </description></item> /// <item><description><b>lengthNorm</b> - computed /// when the document is added to the index in accordance with the number of tokens /// of this field in the document, so that shorter fields contribute more to the score. /// LengthNorm is computed by the <see cref="Similarity"/> class in effect at indexing. /// </description></item> /// </list> /// The <see cref="ComputeNorm(FieldInvertState)"/> method is responsible for /// combining all of these factors into a single <see cref="float"/>. /// /// <para/> /// When a document is added to the index, all the above factors are multiplied. /// If the document has multiple fields with the same name, all their boosts are multiplied together: /// /// <para/> /// <list type="table"> /// <item> /// <term> /// norm(t,d) &#160; = &#160; /// lengthNorm /// &#160;&#183;&#160; /// </term> /// <term><big><big><big>&#8719;</big></big></big></term> /// <term><see cref="Index.IIndexableField.Boost"/></term> /// </item> /// <item> /// <term></term> /// <term><small>field <i><b>f</b></i> in <i>d</i> named as <i><b>t</b></i></small></term> /// <term></term> /// </item> /// </list> /// Note that search time is too late to modify this <i>norm</i> part of scoring, /// e.g. by using a different <see cref="Similarity"/> for search. /// </description></item> /// </list> /// </summary> /// <seealso cref="Lucene.Net.Index.IndexWriterConfig.Similarity"/> /// <seealso cref="IndexSearcher.Similarity"/> public abstract class TFIDFSimilarity : Similarity { /// <summary> /// Sole constructor. (For invocation by subclass /// constructors, typically implicit.) /// </summary> protected TFIDFSimilarity() // LUCENENET: CA1012: Abstract types should not have constructors (marked protected) { } /// <summary> /// Computes a score factor based on the fraction of all query terms that a /// document contains. this value is multiplied into scores. /// /// <para/>The presence of a large portion of the query terms indicates a better /// match with the query, so implementations of this method usually return /// larger values when the ratio between these parameters is large and smaller /// values when the ratio between them is small. /// </summary> /// <param name="overlap"> The number of query terms matched in the document </param> /// <param name="maxOverlap"> The total number of terms in the query </param> /// <returns> A score factor based on term overlap with the query </returns> public override abstract float Coord(int overlap, int maxOverlap); /// <summary> /// Computes the normalization value for a query given the sum of the squared /// weights of each of the query terms. this value is multiplied into the /// weight of each query term. While the classic query normalization factor is /// computed as 1/sqrt(sumOfSquaredWeights), other implementations might /// completely ignore sumOfSquaredWeights (ie return 1). /// /// <para/>This does not affect ranking, but the default implementation does make scores /// from different queries more comparable than they would be by eliminating the /// magnitude of the <see cref="Query"/> vector as a factor in the score. /// </summary> /// <param name="sumOfSquaredWeights"> The sum of the squares of query term weights </param> /// <returns> A normalization factor for query weights </returns> public override abstract float QueryNorm(float sumOfSquaredWeights); /// <summary> /// Computes a score factor based on a term or phrase's frequency in a /// document. This value is multiplied by the <see cref="Idf(long, long)"/> /// factor for each term in the query and these products are then summed to /// form the initial score for a document. /// /// <para/>Terms and phrases repeated in a document indicate the topic of the /// document, so implementations of this method usually return larger values /// when <paramref name="freq"/> is large, and smaller values when <paramref name="freq"/> /// is small. /// </summary> /// <param name="freq"> The frequency of a term within a document </param> /// <returns> A score factor based on a term's within-document frequency </returns> public abstract float Tf(float freq); /// <summary> /// Computes a score factor for a simple term and returns an explanation /// for that score factor. /// /// <para/> /// The default implementation uses: /// /// <code> /// Idf(docFreq, searcher.MaxDoc); /// </code> /// /// Note that <see cref="CollectionStatistics.MaxDoc"/> is used instead of /// <see cref="Lucene.Net.Index.IndexReader.NumDocs"/> because also /// <see cref="TermStatistics.DocFreq"/> is used, and when the latter /// is inaccurate, so is <see cref="CollectionStatistics.MaxDoc"/>, and in the same direction. /// In addition, <see cref="CollectionStatistics.MaxDoc"/> is more efficient to compute /// </summary> /// <param name="collectionStats"> Collection-level statistics </param> /// <param name="termStats"> Term-level statistics for the term </param> /// <returns> An Explain object that includes both an idf score factor /// and an explanation for the term. </returns> public virtual Explanation IdfExplain(CollectionStatistics collectionStats, TermStatistics termStats) { long df = termStats.DocFreq; long max = collectionStats.MaxDoc; float idf = Idf(df, max); return new Explanation(idf, "idf(docFreq=" + df + ", maxDocs=" + max + ")"); } /// <summary> /// Computes a score factor for a phrase. /// /// <para/> /// The default implementation sums the idf factor for /// each term in the phrase. /// </summary> /// <param name="collectionStats"> Collection-level statistics </param> /// <param name="termStats"> Term-level statistics for the terms in the phrase </param> /// <returns> An Explain object that includes both an idf /// score factor for the phrase and an explanation /// for each term. </returns> public virtual Explanation IdfExplain(CollectionStatistics collectionStats, TermStatistics[] termStats) { long max = collectionStats.MaxDoc; float idf = 0.0f; Explanation exp = new Explanation(); exp.Description = "idf(), sum of:"; foreach (TermStatistics stat in termStats) { long df = stat.DocFreq; float termIdf = Idf(df, max); exp.AddDetail(new Explanation(termIdf, "idf(docFreq=" + df + ", maxDocs=" + max + ")")); idf += termIdf; } exp.Value = idf; return exp; } /// <summary> /// Computes a score factor based on a term's document frequency (the number /// of documents which contain the term). This value is multiplied by the /// <see cref="Tf(float)"/> factor for each term in the query and these products are /// then summed to form the initial score for a document. /// /// <para/>Terms that occur in fewer documents are better indicators of topic, so /// implementations of this method usually return larger values for rare terms, /// and smaller values for common terms. /// </summary> /// <param name="docFreq"> The number of documents which contain the term </param> /// <param name="numDocs"> The total number of documents in the collection </param> /// <returns> A score factor based on the term's document frequency </returns> public abstract float Idf(long docFreq, long numDocs); /// <summary> /// Compute an index-time normalization value for this field instance. /// <para/> /// This value will be stored in a single byte lossy representation by /// <see cref="EncodeNormValue(float)"/>. /// </summary> /// <param name="state"> Statistics of the current field (such as length, boost, etc) </param> /// <returns> An index-time normalization value </returns> public abstract float LengthNorm(FieldInvertState state); public override sealed long ComputeNorm(FieldInvertState state) { float normValue = LengthNorm(state); return EncodeNormValue(normValue); } /// <summary> /// Decodes a normalization factor stored in an index. /// </summary> /// <see cref="EncodeNormValue(float)"/> public abstract float DecodeNormValue(long norm); /// <summary> /// Encodes a normalization factor for storage in an index. </summary> public abstract long EncodeNormValue(float f); /// <summary> /// Computes the amount of a sloppy phrase match, based on an edit distance. /// this value is summed for each sloppy phrase match in a document to form /// the frequency to be used in scoring instead of the exact term count. /// /// <para/>A phrase match with a small edit distance to a document passage more /// closely matches the document, so implementations of this method usually /// return larger values when the edit distance is small and smaller values /// when it is large. /// </summary> /// <seealso cref="PhraseQuery.Slop"/> /// <param name="distance"> The edit distance of this sloppy phrase match </param> /// <returns> The frequency increment for this match </returns> public abstract float SloppyFreq(int distance); /// <summary> /// Calculate a scoring factor based on the data in the payload. Implementations /// are responsible for interpreting what is in the payload. Lucene makes no assumptions about /// what is in the byte array. /// </summary> /// <param name="doc"> The docId currently being scored. </param> /// <param name="start"> The start position of the payload </param> /// <param name="end"> The end position of the payload </param> /// <param name="payload"> The payload byte array to be scored </param> /// <returns> An implementation dependent float to be used as a scoring factor </returns> public abstract float ScorePayload(int doc, int start, int end, BytesRef payload); public override sealed SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { Explanation idf = termStats.Length == 1 ? IdfExplain(collectionStats, termStats[0]) : IdfExplain(collectionStats, termStats); return new IDFStats(collectionStats.Field, idf, queryBoost); } public override sealed SimScorer GetSimScorer(SimWeight stats, AtomicReaderContext context) { IDFStats idfstats = (IDFStats)stats; return new TFIDFSimScorer(this, idfstats, context.AtomicReader.GetNormValues(idfstats.Field)); } private sealed class TFIDFSimScorer : SimScorer { private readonly TFIDFSimilarity outerInstance; private readonly IDFStats stats; private readonly float weightValue; private readonly NumericDocValues norms; internal TFIDFSimScorer(TFIDFSimilarity outerInstance, IDFStats stats, NumericDocValues norms) { this.outerInstance = outerInstance; this.stats = stats; this.weightValue = stats.Value; this.norms = norms; } public override float Score(int doc, float freq) { float raw = outerInstance.Tf(freq) * weightValue; // compute tf(f)*weight return norms is null ? raw : raw * outerInstance.DecodeNormValue(norms.Get(doc)); // normalize for field } public override float ComputeSlopFactor(int distance) { return outerInstance.SloppyFreq(distance); } public override float ComputePayloadFactor(int doc, int start, int end, BytesRef payload) { return outerInstance.ScorePayload(doc, start, end, payload); } public override Explanation Explain(int doc, Explanation freq) { return outerInstance.ExplainScore(doc, freq, stats, norms); } } /// <summary> /// Collection statistics for the TF-IDF model. The only statistic of interest /// to this model is idf. /// </summary> [ExceptionToClassNameConvention] private class IDFStats : SimWeight { internal string Field { get; private set; } /// <summary> /// The idf and its explanation </summary> internal Explanation Idf { get; private set; } internal float QueryNorm { get; set; } internal float QueryWeight { get; set; } internal float QueryBoost { get; private set; } internal float Value { get; set; } public IDFStats(string field, Explanation idf, float queryBoost) { // TODO: Validate? this.Field = field; this.Idf = idf; this.QueryBoost = queryBoost; this.QueryWeight = idf.Value * queryBoost; // compute query weight } public override float GetValueForNormalization() { // TODO: (sorta LUCENE-1907) make non-static class and expose this squaring via a nice method to subclasses? return QueryWeight * QueryWeight; // sum of squared weights } public override void Normalize(float queryNorm, float topLevelBoost) { this.QueryNorm = queryNorm * topLevelBoost; QueryWeight *= this.QueryNorm; // normalize query weight Value = QueryWeight * Idf.Value; // idf for document } } private Explanation ExplainScore(int doc, Explanation freq, IDFStats stats, NumericDocValues norms) { Explanation result = new Explanation(); // LUCENENET specific - using freq.Value is a change that was made in Lucene 5.0, but is included // in 4.8.0 to remove annoying newlines from the output. // See: https://github.com/apache/lucene-solr/commit/f0bfcbc7d8fbc5bb2791da60af559e8b0ad6eed6 result.Description = "score(doc=" + doc + ",freq=" + freq.Value + "), product of:"; // explain query weight Explanation queryExpl = new Explanation(); queryExpl.Description = "queryWeight, product of:"; Explanation boostExpl = new Explanation(stats.QueryBoost, "boost"); if (stats.QueryBoost != 1.0f) { queryExpl.AddDetail(boostExpl); } queryExpl.AddDetail(stats.Idf); Explanation queryNormExpl = new Explanation(stats.QueryNorm, "queryNorm"); queryExpl.AddDetail(queryNormExpl); queryExpl.Value = boostExpl.Value * stats.Idf.Value * queryNormExpl.Value; result.AddDetail(queryExpl); // explain field weight Explanation fieldExpl = new Explanation(); fieldExpl.Description = "fieldWeight in " + doc + ", product of:"; Explanation tfExplanation = new Explanation(); tfExplanation.Value = Tf(freq.Value); tfExplanation.Description = "tf(freq=" + freq.Value + "), with freq of:"; tfExplanation.AddDetail(freq); fieldExpl.AddDetail(tfExplanation); fieldExpl.AddDetail(stats.Idf); Explanation fieldNormExpl = new Explanation(); float fieldNorm = norms != null ? DecodeNormValue(norms.Get(doc)) : 1.0f; fieldNormExpl.Value = fieldNorm; fieldNormExpl.Description = "fieldNorm(doc=" + doc + ")"; fieldExpl.AddDetail(fieldNormExpl); fieldExpl.Value = tfExplanation.Value * stats.Idf.Value * fieldNormExpl.Value; result.AddDetail(fieldExpl); // combine them result.Value = queryExpl.Value * fieldExpl.Value; if (queryExpl.Value == 1.0f) { return fieldExpl; } return result; } } }
using System; using System.Collections.Generic; using System.Net; using System.Text; using Htc.Vita.Core.Json; namespace Htc.Vita.Core.Util { /// <summary> /// Class DictionaryExtension. /// </summary> public static class DictionaryExtension { /// <summary> /// Applies the value if it is not null. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>Dictionary&lt;System.String, System.Object&gt;.</returns> public static Dictionary<string, object> ApplyIfNotNull( this Dictionary<string, object> data, string key, object value) { if (data == null) { return null; } if (value != null) { data[key] = value; } return data; } /// <summary> /// Applies the value if it is not null and not white space. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>Dictionary&lt;System.String, System.Object&gt;.</returns> public static Dictionary<string, object> ApplyIfNotNullAndNotWhiteSpace( this Dictionary<string, object> data, string key, string value) { if (data == null) { return null; } if (string.IsNullOrWhiteSpace(value)) { return data; } data[key] = value; return data; } /// <summary> /// Applies the value if it is not null and not white space. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>Dictionary&lt;System.String, System.String&gt;.</returns> public static Dictionary<string, string> ApplyIfNotNullAndNotWhiteSpace( this Dictionary<string, string> data, string key, string value) { if (data == null) { return null; } if (string.IsNullOrWhiteSpace(value)) { return data; } data[key] = value; return data; } /// <summary> /// Parses the data. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <returns>System.Object.</returns> public static object ParseData( this Dictionary<string, object> data, string key) { return ParseData( data, key, null ); } /// <summary> /// Parses the data. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>System.Object.</returns> public static object ParseData( this Dictionary<string, object> data, string key, object defaultValue) { if (data == null) { return defaultValue; } if (!data.ContainsKey(key)) { return defaultValue; } return data[key]; } /// <summary> /// Parses the value to string. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <returns>System.String.</returns> public static string ParseString( this Dictionary<string, string> data, string key) { return ParseString( data, key, null ); } /// <summary> /// Parses the value to string. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>System.String.</returns> public static string ParseString( this Dictionary<string, string> data, string key, string defaultValue) { if (data == null) { return defaultValue; } if (!data.ContainsKey(key)) { return defaultValue; } return data[key]; } /// <summary> /// Parses the value to URI. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <returns>Uri.</returns> public static Uri ParseUri( this Dictionary<string, object> data, string key) { return ParseUri( data, key, null ); } /// <summary> /// Parses the value to URI. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>Uri.</returns> public static Uri ParseUri( this Dictionary<string, object> data, string key, Uri defaultValue) { if (data == null) { return defaultValue; } if (!data.ContainsKey(key)) { return defaultValue; } var result = data[key] as Uri; if (result != null) { return result; } var item = data[key] as string; return item.ToUri() ?? defaultValue; } /// <summary> /// Parses the value to URI. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <returns>Uri.</returns> public static Uri ParseUri( this Dictionary<string, string> data, string key) { return ParseUri( data, key, null ); } /// <summary> /// Parses the value to URI. /// </summary> /// <param name="data">The data.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns>Uri.</returns> public static Uri ParseUri( this Dictionary<string, string> data, string key, Uri defaultValue) { if (data == null) { return defaultValue; } if (!data.ContainsKey(key)) { return defaultValue; } return data[key].ToUri(); } /// <summary> /// Converts to encoded URI query parameters. /// </summary> /// <param name="queryParams">The query parameters.</param> /// <returns>System.String.</returns> public static string ToEncodedUriQueryParameters(this Dictionary<string, string> queryParams) { if (queryParams == null) { return null; } var stringBuilder = new StringBuilder(); var isFirst = true; foreach (var key in queryParams.Keys) { var param = queryParams[key]; if (string.IsNullOrEmpty(param)) { continue; } if (!isFirst) { stringBuilder.Append('&'); } stringBuilder.Append(WebUtility.UrlEncode(key)) .Append('=') .Append(WebUtility.UrlEncode(param)); isFirst = false; } return stringBuilder.ToString(); } /// <summary> /// Converts to JsonObject with bool properties. /// </summary> /// <param name="data">The data.</param> /// <returns>JsonObject.</returns> public static JsonObject ToJsonObject(this Dictionary<string, bool> data) { if (data == null) { return null; } var result = JsonFactory.GetInstance().CreateJsonObject(); foreach (var key in data.Keys) { if (string.IsNullOrWhiteSpace(key)) { continue; } result.Put(key, data[key]); } return result; } /// <summary> /// Converts to JsonObject with double properties. /// </summary> /// <param name="data">The data.</param> /// <returns>JsonObject.</returns> public static JsonObject ToJsonObject(this Dictionary<string, double> data) { if (data == null) { return null; } var result = JsonFactory.GetInstance().CreateJsonObject(); foreach (var key in data.Keys) { if (string.IsNullOrWhiteSpace(key)) { continue; } result.Put(key, data[key]); } return result; } /// <summary> /// Converts to JsonObject with float properties. /// </summary> /// <param name="data">The data.</param> /// <returns>JsonObject.</returns> public static JsonObject ToJsonObject(this Dictionary<string, float> data) { if (data == null) { return null; } var result = JsonFactory.GetInstance().CreateJsonObject(); foreach (var key in data.Keys) { if (string.IsNullOrWhiteSpace(key)) { continue; } result.Put(key, data[key]); } return result; } /// <summary> /// Converts to JsonObject with int properties. /// </summary> /// <param name="data">The data.</param> /// <returns>JsonObject.</returns> public static JsonObject ToJsonObject(this Dictionary<string, int> data) { if (data == null) { return null; } var result = JsonFactory.GetInstance().CreateJsonObject(); foreach (var key in data.Keys) { if (string.IsNullOrWhiteSpace(key)) { continue; } result.Put(key, data[key]); } return result; } /// <summary> /// Converts to JsonObject with long properties. /// </summary> /// <param name="data">The data.</param> /// <returns>JsonObject.</returns> public static JsonObject ToJsonObject(this Dictionary<string, long> data) { if (data == null) { return null; } var result = JsonFactory.GetInstance().CreateJsonObject(); foreach (var key in data.Keys) { if (string.IsNullOrWhiteSpace(key)) { continue; } result.Put(key, data[key]); } return result; } /// <summary> /// Converts to JsonObject with string properties. /// </summary> /// <param name="data">The data.</param> /// <returns>JsonObject.</returns> public static JsonObject ToJsonObject(this Dictionary<string, string> data) { if (data == null) { return null; } var result = JsonFactory.GetInstance().CreateJsonObject(); foreach (var key in data.Keys) { if (string.IsNullOrWhiteSpace(key)) { continue; } result.Put(key, data[key]); } return result; } /// <summary> /// Converts to JsonObject with JsonArray properties. /// </summary> /// <param name="data">The data.</param> /// <returns>JsonObject.</returns> public static JsonObject ToJsonObject(this Dictionary<string, JsonArray> data) { if (data == null) { return null; } var result = JsonFactory.GetInstance().CreateJsonObject(); foreach (var key in data.Keys) { if (string.IsNullOrWhiteSpace(key)) { continue; } result.Put(key, data[key]); } return result; } /// <summary> /// Converts to JsonObject with JsonObject properties. /// </summary> /// <param name="data">The data.</param> /// <returns>JsonObject.</returns> public static JsonObject ToJsonObject(this Dictionary<string, JsonObject> data) { if (data == null) { return null; } var result = JsonFactory.GetInstance().CreateJsonObject(); foreach (var key in data.Keys) { if (string.IsNullOrWhiteSpace(key)) { continue; } result.Put(key, data[key]); } return result; } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System.Collections; using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { /// <summary> /// Delegate used to delay evaluation of the actual value /// to be used in evaluating a constraint /// </summary> #if CLR_2_0 || CLR_4_0 public delegate T ActualValueDelegate<T>(); #else public delegate object ActualValueDelegate(); #endif /// <summary> /// The Constraint class is the base of all built-in constraints /// within NUnit. It provides the operator overloads used to combine /// constraints. /// </summary> public abstract class Constraint : IResolveConstraint { #region UnsetObject Class /// <summary> /// Class used to detect any derived constraints /// that fail to set the actual value in their /// Matches override. /// </summary> private class UnsetObject { public override string ToString() { return "UNSET"; } } #endregion #region Static and Instance Fields /// <summary> /// Static UnsetObject used to detect derived constraints /// failing to set the actual value. /// </summary> protected static object UNSET = new UnsetObject(); /// <summary> /// The actual value being tested against a constraint /// </summary> protected object actual = UNSET; /// <summary> /// The display name of this Constraint for use by ToString() /// </summary> private string displayName; /// <summary> /// Argument fields used by ToString(); /// </summary> private readonly int argcnt; private readonly object arg1; private readonly object arg2; /// <summary> /// The builder holding this constraint /// </summary> private ConstraintBuilder builder; #endregion #region Constructors /// <summary> /// Construct a constraint with no arguments /// </summary> protected Constraint() { argcnt = 0; } /// <summary> /// Construct a constraint with one argument /// </summary> protected Constraint(object arg) { argcnt = 1; this.arg1 = arg; } /// <summary> /// Construct a constraint with two arguments /// </summary> protected Constraint(object arg1, object arg2) { argcnt = 2; this.arg1 = arg1; this.arg2 = arg2; } #endregion #region Set Containing ConstraintBuilder /// <summary> /// Sets the ConstraintBuilder holding this constraint /// </summary> internal void SetBuilder(ConstraintBuilder builder) { this.builder = builder; } #endregion #region Properties /// <summary> /// The display name of this Constraint for use by ToString(). /// The default value is the name of the constraint with /// trailing "Constraint" removed. Derived classes may set /// this to another name in their constructors. /// </summary> protected string DisplayName { get { if (displayName == null) { displayName = this.GetType().Name.ToLower(); if (displayName.EndsWith("`1") || displayName.EndsWith("`2")) displayName = displayName.Substring(0, displayName.Length - 2); if (displayName.EndsWith("constraint")) displayName = displayName.Substring(0, displayName.Length - 10); } return displayName; } set { displayName = value; } } #endregion #region Abstract and Virtual Methods /// <summary> /// Write the failure message to the MessageWriter provided /// as an argument. The default implementation simply passes /// the constraint and the actual value to the writer, which /// then displays the constraint description and the value. /// /// Constraints that need to provide additional details, /// such as where the error occured can override this. /// </summary> /// <param name="writer">The MessageWriter on which to display the message</param> public virtual void WriteMessageTo(MessageWriter writer) { writer.DisplayDifferences(this); } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public abstract bool Matches(object actual); #if CLR_2_0 || CLR_4_0 /// <summary> /// Test whether the constraint is satisfied by an /// ActualValueDelegate that returns the value to be tested. /// The default implementation simply evaluates the delegate /// but derived classes may override it to provide for delayed /// processing. /// </summary> /// <param name="del">An <see cref="ActualValueDelegate{T}" /></param> /// <returns>True for success, false for failure</returns> public virtual bool Matches<T>(ActualValueDelegate<T> del) { #if NET_4_5 && !PORTABLE if (AsyncInvocationRegion.IsAsyncOperation(del)) using (var region = AsyncInvocationRegion.Create(del)) return Matches(region.WaitForPendingOperationsToComplete(del())); #endif return Matches(del()); } #else /// <summary> /// Test whether the constraint is satisfied by an /// ActualValueDelegate that returns the value to be tested. /// The default implementation simply evaluates the delegate /// but derived classes may override it to provide for delayed /// processing. /// </summary> /// <param name="del">An <see cref="ActualValueDelegate" /></param> /// <returns>True for success, false for failure</returns> public virtual bool Matches(ActualValueDelegate del) { return Matches(del()); } #endif /// <summary> /// Test whether the constraint is satisfied by a given reference. /// The default implementation simply dereferences the value but /// derived classes may override it to provide for delayed processing. /// </summary> /// <param name="actual">A reference to the value to be tested</param> /// <returns>True for success, false for failure</returns> #if CLR_2_0 || CLR_4_0 public virtual bool Matches<T>(ref T actual) #else public virtual bool Matches(ref bool actual) #endif { return Matches(actual); } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public abstract void WriteDescriptionTo(MessageWriter writer); /// <summary> /// Write the actual value for a failing constraint test to a /// MessageWriter. The default implementation simply writes /// the raw value of actual, leaving it to the writer to /// perform any formatting. /// </summary> /// <param name="writer">The writer on which the actual value is displayed</param> public virtual void WriteActualValueTo(MessageWriter writer) { writer.WriteActualValue(actual); } #endregion #region ToString Override /// <summary> /// Default override of ToString returns the constraint DisplayName /// followed by any arguments within angle brackets. /// </summary> /// <returns></returns> public override string ToString() { string rep = GetStringRepresentation(); return this.builder == null ? rep : string.Format("<unresolved {0}>", rep); } /// <summary> /// Returns the string representation of this constraint /// </summary> protected virtual string GetStringRepresentation() { switch (argcnt) { default: case 0: return string.Format("<{0}>", DisplayName); case 1: return string.Format("<{0} {1}>", DisplayName, _displayable(arg1)); case 2: return string.Format("<{0} {1} {2}>", DisplayName, _displayable(arg1), _displayable(arg2)); } } private static string _displayable(object o) { if (o == null) return "null"; string fmt = o is string ? "\"{0}\"" : "{0}"; return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o); } #endregion #region Operator Overloads /// <summary> /// This operator creates a constraint that is satisfied only if both /// argument constraints are satisfied. /// </summary> public static Constraint operator &(Constraint left, Constraint right) { IResolveConstraint l = (IResolveConstraint)left; IResolveConstraint r = (IResolveConstraint)right; return new AndConstraint(l.Resolve(), r.Resolve()); } /// <summary> /// This operator creates a constraint that is satisfied if either /// of the argument constraints is satisfied. /// </summary> public static Constraint operator |(Constraint left, Constraint right) { IResolveConstraint l = (IResolveConstraint)left; IResolveConstraint r = (IResolveConstraint)right; return new OrConstraint(l.Resolve(), r.Resolve()); } /// <summary> /// This operator creates a constraint that is satisfied if the /// argument constraint is not satisfied. /// </summary> public static Constraint operator !(Constraint constraint) { IResolveConstraint r = constraint as IResolveConstraint; return new NotConstraint(r == null ? new NullConstraint() : r.Resolve()); } #endregion #region Binary Operators /// <summary> /// Returns a ConstraintExpression by appending And /// to the current constraint. /// </summary> public ConstraintExpression And { get { ConstraintBuilder builder = this.builder; if (builder == null) { builder = new ConstraintBuilder(); builder.Append(this); } builder.Append(new AndOperator()); return new ConstraintExpression(builder); } } /// <summary> /// Returns a ConstraintExpression by appending And /// to the current constraint. /// </summary> public ConstraintExpression With { get { return this.And; } } /// <summary> /// Returns a ConstraintExpression by appending Or /// to the current constraint. /// </summary> public ConstraintExpression Or { get { ConstraintBuilder builder = this.builder; if (builder == null) { builder = new ConstraintBuilder(); builder.Append(this); } builder.Append(new OrOperator()); return new ConstraintExpression(builder); } } #endregion #region After Modifier #if !NETCF && !SILVERLIGHT && !PORTABLE /// <summary> /// Returns a DelayedConstraint with the specified delay time. /// </summary> /// <param name="delayInMilliseconds">The delay in milliseconds.</param> /// <returns></returns> public DelayedConstraint After(int delayInMilliseconds) { return new DelayedConstraint( builder == null ? this : builder.Resolve(), delayInMilliseconds); } /// <summary> /// Returns a DelayedConstraint with the specified delay time /// and polling interval. /// </summary> /// <param name="delayInMilliseconds">The delay in milliseconds.</param> /// <param name="pollingInterval">The interval at which to test the constraint.</param> /// <returns></returns> public DelayedConstraint After(int delayInMilliseconds, int pollingInterval) { return new DelayedConstraint( builder == null ? this : builder.Resolve(), delayInMilliseconds, pollingInterval); } #endif #endregion #region IResolveConstraint Members Constraint IResolveConstraint.Resolve() { return builder == null ? this : builder.Resolve(); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection.Internal; using System.Text; using TestUtilities; using Xunit; namespace System.Reflection.Metadata.Tests { public class BlobReaderTests { [Fact] public unsafe void PublicBlobReaderCtorValidatesArgs() { byte* bufferPtrForLambda; byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed (byte* bufferPtr = buffer) { bufferPtrForLambda = bufferPtr; Assert.Throws<ArgumentOutOfRangeException>(() => new BlobReader(bufferPtrForLambda, -1)); } Assert.Throws<ArgumentNullException>(() => new BlobReader(null, 1)); Assert.Equal(0, new BlobReader(null, 0).Length); // this is valid Assert.Throws<BadImageFormatException>(() => new BlobReader(null, 0).ReadByte()); // but can't read anything non-empty from it... Assert.Same(String.Empty, new BlobReader(null, 0).ReadUtf8NullTerminated()); // can read empty string. } [Fact] public unsafe void ReadFromMemoryReader() { byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed (byte* bufferPtr = buffer) { var reader = new BlobReader(new MemoryBlock(bufferPtr, buffer.Length)); Assert.False(reader.SeekOffset(-1)); Assert.False(reader.SeekOffset(Int32.MaxValue)); Assert.False(reader.SeekOffset(Int32.MinValue)); Assert.False(reader.SeekOffset(buffer.Length)); Assert.True(reader.SeekOffset(buffer.Length - 1)); Assert.True(reader.SeekOffset(0)); Assert.Equal(0, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64()); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(1)); Assert.Equal(1, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadDouble()); Assert.Equal(1, reader.Offset); Assert.True(reader.SeekOffset(2)); Assert.Equal(2, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32()); Assert.Equal((ushort)0x0200, reader.ReadUInt16()); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(2)); Assert.Equal(2, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadSingle()); Assert.Equal(2, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Equal(9.404242E-38F, reader.ReadSingle()); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(3)); Assert.Equal(3, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt16()); Assert.Equal((byte)0x02, reader.ReadByte()); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Equal("\u0000\u0001\u0000\u0002", reader.ReadUTF8(4)); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(5)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF8(-1)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Equal("\u0100\u0200", reader.ReadUTF16(4)); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(5)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(-1)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadUTF16(6)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); AssertEx.Equal(buffer, reader.ReadBytes(4)); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Same(String.Empty, reader.ReadUtf8NullTerminated()); Assert.Equal(1, reader.Offset); Assert.True(reader.SeekOffset(1)); Assert.Equal("\u0001", reader.ReadUtf8NullTerminated()); Assert.Equal(3, reader.Offset); Assert.True(reader.SeekOffset(3)); Assert.Equal("\u0002", reader.ReadUtf8NullTerminated()); Assert.Equal(4, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Same(String.Empty, reader.ReadUtf8NullTerminated()); Assert.Equal(1, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(5)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.ReadBytes(Int32.MinValue)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(-1, 1)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Throws<BadImageFormatException>(() => reader.GetMemoryBlockAt(1, -1)); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(0)); Assert.Equal(3, reader.GetMemoryBlockAt(1, 3).Length); Assert.Equal(0, reader.Offset); Assert.True(reader.SeekOffset(3)); reader.ReadByte(); Assert.Equal(4, reader.Offset); Assert.Equal(4, reader.Offset); Assert.Equal(0, reader.ReadBytes(0).Length); Assert.Equal(4, reader.Offset); int value; Assert.False(reader.TryReadCompressedInteger(out value)); Assert.Equal(BlobReader.InvalidCompressedInteger, value); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadCompressedInteger()); Assert.Equal(4, reader.Offset); Assert.Equal(SerializationTypeCode.Invalid, reader.ReadSerializationTypeCode()); Assert.Equal(4, reader.Offset); Assert.Equal(SignatureTypeCode.Invalid, reader.ReadSignatureTypeCode()); Assert.Equal(4, reader.Offset); Assert.Equal(default(Handle), reader.ReadTypeHandle()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadBoolean()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadByte()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadSByte()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt32()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadInt32()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadUInt64()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadInt64()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadSingle()); Assert.Equal(4, reader.Offset); Assert.Throws<BadImageFormatException>(() => reader.ReadDouble()); Assert.Equal(4, reader.Offset); } byte[] buffer2 = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; fixed (byte* bufferPtr2 = buffer2) { var reader = new BlobReader(new MemoryBlock(bufferPtr2, buffer2.Length)); Assert.Equal(reader.Offset, 0); Assert.Equal(0x0807060504030201UL, reader.ReadUInt64()); Assert.Equal(reader.Offset, 8); reader.Reset(); Assert.Equal(reader.Offset, 0); Assert.Equal(0x0807060504030201L, reader.ReadInt64()); reader.Reset(); Assert.Equal(reader.Offset, 0); Assert.Equal(BitConverter.ToDouble(buffer2, 0), reader.ReadDouble()); } } [Fact] public unsafe void ValidatePeekReferenceSize() { byte[] buffer = new byte[8] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; fixed (byte* bufferPtr = buffer) { var block = new MemoryBlock(bufferPtr, buffer.Length); // small ref size always fits in 16 bits Assert.Equal(0xFFFFU, block.PeekReference(0, smallRefSize: true)); Assert.Equal(0xFFFFU, block.PeekReference(4, smallRefSize: true)); Assert.Equal(0xFFFFU, block.PeekTaggedReference(0, smallRefSize: true)); Assert.Equal(0xFFFFU, block.PeekTaggedReference(4, smallRefSize: true)); Assert.Equal(0x01FFU, block.PeekTaggedReference(6, smallRefSize: true)); // large ref size throws on > RIDMask when tagged variant is not used. AssertEx.Throws<BadImageFormatException>(() => block.PeekReference(0, smallRefSize: false), MetadataResources.RowIdOrHeapOffsetTooLarge); AssertEx.Throws<BadImageFormatException>(() => block.PeekReference(4, smallRefSize: false), MetadataResources.RowIdOrHeapOffsetTooLarge); // large ref size does not throw when Tagged variant is used. Assert.Equal(0xFFFFFFFFU, block.PeekTaggedReference(0, smallRefSize: false)); Assert.Equal(0x01FFFFFFU, block.PeekTaggedReference(4, smallRefSize: false)); // bounds check applies in all cases AssertEx.Throws<BadImageFormatException>(() => block.PeekReference(7, smallRefSize: true), MetadataResources.OutOfBoundsRead); AssertEx.Throws<BadImageFormatException>(() => block.PeekReference(5, smallRefSize: false), MetadataResources.OutOfBoundsRead); } } [Fact] public unsafe void ReadFromMemoryBlock() { byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed (byte* bufferPtr = buffer) { var block = new MemoryBlock(bufferPtr, buffer.Length); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(-1)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(Int32.MinValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(4)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt32(1)); Assert.Equal(0x02000100U, block.PeekUInt32(0)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(-1)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(Int32.MinValue)); Assert.Throws<BadImageFormatException>(() => block.PeekUInt16(4)); Assert.Equal(0x0200, block.PeekUInt16(2)); int bytesRead; MetadataStringDecoder stringDecoder = MetadataStringDecoder.DefaultUTF8; Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MaxValue, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(-1, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MinValue, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.PeekUtf8NullTerminated(5, null, stringDecoder, out bytesRead)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(1, -1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(0, -1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 0)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-Int32.MaxValue, Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, -Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, Int32.MaxValue)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(block.Length, -1)); Assert.Throws<BadImageFormatException>(() => block.GetMemoryBlockAt(-1, block.Length)); Assert.Equal("\u0001", block.PeekUtf8NullTerminated(1, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 2); Assert.Equal("\u0002", block.PeekUtf8NullTerminated(3, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 1); Assert.Equal("", block.PeekUtf8NullTerminated(4, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 0); byte[] helloPrefix = Encoding.UTF8.GetBytes("Hello"); Assert.Equal("Hello\u0001", block.PeekUtf8NullTerminated(1, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 2); Assert.Equal("Hello\u0002", block.PeekUtf8NullTerminated(3, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 1); Assert.Equal("Hello", block.PeekUtf8NullTerminated(4, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 0); } } } }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEditor.FacebookEditor; using UnityEngine; [CustomEditor(typeof(FacebookSettings))] public class FacebookSettingsEditor : UnityEditor.Editor { private bool showFacebookInitSettings = false; private bool showAndroidUtils = EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android; private bool showIOSSettings = EditorUserBuildSettings.activeBuildTarget.ToString() == "iOS"; private bool showAppLinksSettings = false; private bool showAboutSection = false; private GUIContent appNameLabel = new GUIContent("App Name [?]:", "For your own use and organization.\n(ex. 'dev', 'qa', 'prod')"); private GUIContent appIdLabel = new GUIContent("App Id [?]:", "Facebook App Ids can be found at https://developers.facebook.com/apps"); private GUIContent urlSuffixLabel = new GUIContent("URL Scheme Suffix [?]", "Use this to share Facebook APP ID's across multiple iOS apps. https://developers.facebook.com/docs/ios/share-appid-across-multiple-apps-ios-sdk/"); private GUIContent cookieLabel = new GUIContent("Cookie [?]", "Sets a cookie which your server-side code can use to validate a user's Facebook session"); private GUIContent loggingLabel = new GUIContent("Logging [?]", "(Web Player only) If true, outputs a verbose log to the Javascript console to facilitate debugging."); private GUIContent statusLabel = new GUIContent("Status [?]", "If 'true', attempts to initialize the Facebook object with valid session data."); private GUIContent xfbmlLabel = new GUIContent("Xfbml [?]", "(Web Player only If true) Facebook will immediately parse any XFBML elements on the Facebook Canvas page hosting the app"); private GUIContent frictionlessLabel = new GUIContent("Frictionless Requests [?]", "Use frictionless app requests, as described in their own documentation."); private GUIContent packageNameLabel = new GUIContent("Package Name [?]", "aka: the bundle identifier"); private GUIContent classNameLabel = new GUIContent("Class Name [?]", "aka: the activity name"); private GUIContent debugAndroidKeyLabel = new GUIContent("Debug Android Key Hash [?]", "Copy this key to the Facebook Settings in order to test a Facebook Android app"); private GUIContent sdkVersion = new GUIContent("SDK Version [?]", "This Unity Facebook SDK version. If you have problems or compliments please include this so we know exactly what version to look out for."); public override void OnInspectorGUI() { EditorGUILayout.Separator(); this.AppIdGUI(); EditorGUILayout.Separator(); this.FBParamsInitGUI(); EditorGUILayout.Separator(); this.AndroidUtilGUI(); EditorGUILayout.Separator(); this.IOSUtilGUI(); EditorGUILayout.Separator(); this.AppLinksUtilGUI(); EditorGUILayout.Separator(); this.AboutGUI(); EditorGUILayout.Separator(); this.BuildGUI(); } private void AppIdGUI() { EditorGUILayout.LabelField("Add the Facebook App Id(s) associated with this game"); if (FacebookSettings.AppIds.Count == 0 || FacebookSettings.AppId == "0") { EditorGUILayout.HelpBox("Invalid App Id", MessageType.Error); } EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.appNameLabel); EditorGUILayout.LabelField(this.appIdLabel); EditorGUILayout.EndHorizontal(); for (int i = 0; i < FacebookSettings.AppIds.Count; ++i) { EditorGUILayout.BeginHorizontal(); FacebookSettings.AppLabels[i] = EditorGUILayout.TextField(FacebookSettings.AppLabels[i]); GUI.changed = false; FacebookSettings.AppIds[i] = EditorGUILayout.TextField(FacebookSettings.AppIds[i]); if (GUI.changed) { FacebookSettings.SettingsChanged(); ManifestMod.GenerateManifest(); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add Another App Id")) { FacebookSettings.AppLabels.Add("New App"); FacebookSettings.AppIds.Add("0"); FacebookSettings.AppLinkSchemes.Add(new FacebookSettings.UrlSchemes()); FacebookSettings.SettingsChanged(); } if (FacebookSettings.AppLabels.Count > 1) { if (GUILayout.Button("Remove Last App Id")) { FacebookSettings.AppLabels.Pop(); FacebookSettings.AppIds.Pop(); FacebookSettings.AppLinkSchemes.Pop(); FacebookSettings.SettingsChanged(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); if (FacebookSettings.AppIds.Count > 1) { EditorGUILayout.HelpBox("2) Select Facebook App Id to be compiled with this game", MessageType.None); GUI.changed = false; FacebookSettings.SelectedAppIndex = EditorGUILayout.Popup( "Selected App Id", FacebookSettings.SelectedAppIndex, FacebookSettings.AppIds.ToArray()); if (GUI.changed) { ManifestMod.GenerateManifest(); } EditorGUILayout.Space(); } else { FacebookSettings.SelectedAppIndex = 0; } } private void FBParamsInitGUI() { this.showFacebookInitSettings = EditorGUILayout.Foldout(this.showFacebookInitSettings, "FB.Init() Parameters"); if (this.showFacebookInitSettings) { FacebookSettings.Cookie = EditorGUILayout.Toggle(this.cookieLabel, FacebookSettings.Cookie); FacebookSettings.Logging = EditorGUILayout.Toggle(this.loggingLabel, FacebookSettings.Logging); FacebookSettings.Status = EditorGUILayout.Toggle(this.statusLabel, FacebookSettings.Status); FacebookSettings.Xfbml = EditorGUILayout.Toggle(this.xfbmlLabel, FacebookSettings.Xfbml); FacebookSettings.FrictionlessRequests = EditorGUILayout.Toggle(this.frictionlessLabel, FacebookSettings.FrictionlessRequests); } EditorGUILayout.Space(); } private void IOSUtilGUI() { this.showIOSSettings = EditorGUILayout.Foldout(this.showIOSSettings, "iOS Build Settings"); if (this.showIOSSettings) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.urlSuffixLabel, GUILayout.Width(135), GUILayout.Height(16)); FacebookSettings.IosURLSuffix = EditorGUILayout.TextField(FacebookSettings.IosURLSuffix); EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(); } private void AndroidUtilGUI() { this.showAndroidUtils = EditorGUILayout.Foldout(this.showAndroidUtils, "Android Build Facebook Settings"); if (this.showAndroidUtils) { if (!FacebookAndroidUtil.SetupProperly) { var msg = "Your Android setup is not right. Check the documentation."; switch (FacebookAndroidUtil.SetupError) { case FacebookAndroidUtil.ErrorNoSDK: msg = "You don't have the Android SDK setup! Go to " + (Application.platform == RuntimePlatform.OSXEditor ? "Unity" : "Edit") + "->Preferences... and set your Android SDK Location under External Tools"; break; case FacebookAndroidUtil.ErrorNoKeystore: msg = "Your android debug keystore file is missing! You can create new one by creating and building empty Android project in Ecplise."; break; case FacebookAndroidUtil.ErrorNoKeytool: msg = "Keytool not found. Make sure that Java is installed, and that Java tools are in your path."; break; case FacebookAndroidUtil.ErrorNoOpenSSL: msg = "OpenSSL not found. Make sure that OpenSSL is installed, and that it is in your path."; break; case FacebookAndroidUtil.ErrorKeytoolError: msg = "Unkown error while getting Debug Android Key Hash."; break; } EditorGUILayout.HelpBox(msg, MessageType.Warning); } EditorGUILayout.LabelField( "Copy and Paste these into your \"Native Android App\" Settings on developers.facebook.com/apps"); this.SelectableLabelField(this.packageNameLabel, PlayerSettings.bundleIdentifier); this.SelectableLabelField(this.classNameLabel, ManifestMod.DeepLinkingActivityName); this.SelectableLabelField(this.debugAndroidKeyLabel, FacebookAndroidUtil.DebugKeyHash); if (GUILayout.Button("Regenerate Android Manifest")) { ManifestMod.GenerateManifest(); } } EditorGUILayout.Space(); } private void AppLinksUtilGUI() { this.showAppLinksSettings = EditorGUILayout.Foldout(this.showAppLinksSettings, "App Links Settings"); if (this.showAppLinksSettings) { for (int i = 0; i < FacebookSettings.AppLinkSchemes.Count; ++i) { EditorGUILayout.LabelField(string.Format("App Link Schemes for '{0}'", FacebookSettings.AppLabels[i])); List<string> currentAppLinkSchemes = FacebookSettings.AppLinkSchemes[i].Schemes; for (int j = 0; j < currentAppLinkSchemes.Count; ++j) { GUI.changed = false; string scheme = EditorGUILayout.TextField(currentAppLinkSchemes[j]); if (scheme != currentAppLinkSchemes[j]) { currentAppLinkSchemes[j] = scheme; FacebookSettings.SettingsChanged(); } if (GUI.changed) { ManifestMod.GenerateManifest(); } } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add a Scheme")) { FacebookSettings.AppLinkSchemes[i].Schemes.Add(string.Empty); FacebookSettings.SettingsChanged(); } if (currentAppLinkSchemes.Count > 0) { if (GUILayout.Button("Remove Last Scheme")) { FacebookSettings.AppLinkSchemes[i].Schemes.Pop(); } } EditorGUILayout.EndHorizontal(); } } } private void AboutGUI() { this.showAboutSection = EditorGUILayout.Foldout(this.showAboutSection, "About the Facebook SDK"); if (this.showAboutSection) { this.SelectableLabelField(this.sdkVersion, FacebookSdkVersion.Build); EditorGUILayout.Space(); } } private void SelectableLabelField(GUIContent label, string value) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(label, GUILayout.Width(180), GUILayout.Height(16)); EditorGUILayout.SelectableLabel(value, GUILayout.Height(16)); EditorGUILayout.EndHorizontal(); } private void BuildGUI() { if (GUILayout.Button("Build SDK Package")) { try { FacebookBuild.ExportPackage(); } catch (System.Exception e) { EditorUtility.DisplayDialog("Error Exporting unityPackage", e.Message, "Okay"); } EditorUtility.DisplayDialog("Finished Exporting unityPackage", "Exported to CUI/SDKPackage", "Okay"); } } } }
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 #define UNITY_LE_4_3 #endif #if !UNITY_3_5 && !UNITY_3_4 && !UNITY_3_3 #define UNITY_4 #endif using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using Pathfinding; [CustomEditor(typeof(GraphUpdateScene))] /** Editor for GraphUpdateScene */ public class GraphUpdateSceneEditor : Editor { int selectedPoint = -1; #if !UNITY_LE_4_3 int lastUndoGroup = 0; #endif const float pointGizmosRadius = 0.09F; static Color PointColor = new Color (1,0.36F,0,0.6F); static Color PointSelectedColor = new Color (1,0.24F,0,1.0F); public override void OnInspectorGUI () { GraphUpdateScene script = target as GraphUpdateScene; #if !UNITY_LE_4_3 Undo.RecordObject (script, "modify settings on GraphUpdateObject"); #endif if (script.points == null) script.points = new Vector3[0]; if (script.points == null || script.points.Length == 0) { if (script.GetComponent<Collider>() != null) { EditorGUILayout.HelpBox ("No points, using collider.bounds", MessageType.Info); } else if (script.GetComponent<Renderer>() != null) { EditorGUILayout.HelpBox ("No points, using renderer.bounds", MessageType.Info); } else { EditorGUILayout.HelpBox ("No points and no collider or renderer attached, will not affect anything\nPoints can be added using the transform tool and holding shift", MessageType.Warning); } } Vector3[] prePoints = script.points; #if UNITY_4 EditorGUILayout.PropertyField (serializedObject.FindProperty("points"), true ); if (GUI.changed) { serializedObject.ApplyModifiedProperties (); } #else DrawDefaultInspector (); #endif #if UNITY_LE_4_3 EditorGUI.indentLevel = 1; #else EditorGUI.indentLevel = 0; #endif script.updatePhysics = EditorGUILayout.Toggle (new GUIContent ("Update Physics", "Perform similar calculations on the nodes as during scan.\n" + "Grid Graphs will update the position of the nodes and also check walkability using collision.\nSee online documentation for more info."), script.updatePhysics ); if ( script.updatePhysics ) { EditorGUI.indentLevel++; script.resetPenaltyOnPhysics = EditorGUILayout.Toggle ( new GUIContent ("Reset Penalty On Physics", "Will reset the penalty to the default value during the update."), script.resetPenaltyOnPhysics ); EditorGUI.indentLevel--; } script.updateErosion = EditorGUILayout.Toggle (new GUIContent ("Update Erosion", "Recalculate erosion for grid graphs.\nSee online documentation for more info"), script.updateErosion ); if (prePoints != script.points) { script.RecalcConvex (); HandleUtility.Repaint (); } bool preConvex = script.convex; script.convex = EditorGUILayout.Toggle (new GUIContent ("Convex","Sets if only the convex hull of the points should be used or the whole polygon"),script.convex); if (script.convex != preConvex) { script.RecalcConvex (); HandleUtility.Repaint (); } script.minBoundsHeight = EditorGUILayout.FloatField (new GUIContent ("Min Bounds Height","Defines a minimum height to be used for the bounds of the GUO.\nUseful if you define points in 2D (which would give height 0)"), script.minBoundsHeight); script.applyOnStart = EditorGUILayout.Toggle ("Apply On Start",script.applyOnStart); script.applyOnScan = EditorGUILayout.Toggle ("Apply On Scan",script.applyOnScan); script.modifyWalkability = EditorGUILayout.Toggle (new GUIContent ("Modify walkability","If true, walkability of all nodes will be modified"),script.modifyWalkability); if (script.modifyWalkability) { EditorGUI.indentLevel++; script.setWalkability = EditorGUILayout.Toggle (new GUIContent ("Walkability","Nodes' walkability will be set to this value"),script.setWalkability); EditorGUI.indentLevel--; } script.penaltyDelta = EditorGUILayout.IntField (new GUIContent ("Penalty Delta", "A penalty will be added to the nodes, usually you need very large values, at least 1000-10000.\n" + "A higher penalty will mean that agents will try to avoid those nodes."),script.penaltyDelta); if (script.penaltyDelta < 0) { EditorGUILayout.HelpBox ("Be careful when lowering the penalty. Negative penalties are not supported and will instead underflow and get really high.\n" + "You can set an initial penalty on graphs (see their settings) and then lower them like this to get regions which are easier to traverse.", MessageType.Warning); } script.modifyTag = EditorGUILayout.Toggle (new GUIContent ("Modify Tags","Should the tags of the nodes be modified"),script.modifyTag); if (script.modifyTag) { EditorGUI.indentLevel++; script.setTag = EditorGUILayout.Popup ("Set Tag",script.setTag,AstarPath.FindTagNames ()); EditorGUI.indentLevel--; } if (GUILayout.Button ("Tags can be used to restrict which units can walk on what ground. Click here for more info","HelpBox")) { Application.OpenURL (AstarPathEditor.GetURL ("tags")); } EditorGUILayout.Separator (); bool worldSpace = EditorGUILayout.Toggle (new GUIContent ("Use World Space","Specify coordinates in world space or local space. When using local space you can move the GameObject " + "around and the points will follow.\n" + "Some operations, like calculating the convex hull, and snapping to Y will change axis depending on how the object is rotated if world space is not used." ), script.useWorldSpace); if (worldSpace != script.useWorldSpace) { #if !UNITY_LE_4_3 Undo.RecordObject (script, "switch use-world-space"); #endif script.ToggleUseWorldSpace (); } #if UNITY_4 EditorGUI.BeginChangeCheck (); #endif script.lockToY = EditorGUILayout.Toggle ("Lock to Y",script.lockToY); if (script.lockToY) { EditorGUI.indentLevel++; script.lockToYValue = EditorGUILayout.FloatField ("Lock to Y value",script.lockToYValue); EditorGUI.indentLevel--; #if !UNITY_LE_4_3 if ( EditorGUI.EndChangeCheck () ) { Undo.RecordObject (script, "change Y locking"); } #endif script.LockToY (); } EditorGUILayout.Separator (); if (GUILayout.Button ("Clear all points")) { #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Removed All Points"); #endif script.points = new Vector3[0]; EditorUtility.SetDirty (target); script.RecalcConvex (); } if (GUI.changed) { #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Modify Settings on GraphUpdateObject"); #endif EditorUtility.SetDirty (target); } } public void OnSceneGUI () { GraphUpdateScene script = target as GraphUpdateScene; if (script.points == null) script.points = new Vector3[0]; List<Vector3> points = Pathfinding.Util.ListPool<Vector3>.Claim (); points.AddRange (script.points); Matrix4x4 invMatrix = script.useWorldSpace ? Matrix4x4.identity : script.transform.worldToLocalMatrix; if (!script.useWorldSpace) { Matrix4x4 matrix = script.transform.localToWorldMatrix; for (int i=0;i<points.Count;i++) points[i] = matrix.MultiplyPoint3x4(points[i]); } if (Tools.current != Tool.View && Event.current.type == EventType.Layout) { for (int i=0;i<script.points.Length;i++) { HandleUtility.AddControl (-i - 1,HandleUtility.DistanceToLine (points[i],points[i])); } } if (Tools.current != Tool.View) HandleUtility.AddDefaultControl (0); for (int i=0;i<points.Count;i++) { if (i == selectedPoint && Tools.current == Tool.Move) { Handles.color = PointSelectedColor; #if UNITY_LE_4_3 Undo.SetSnapshotTarget(script, "Moved Point"); #else Undo.RecordObject(script, "Moved Point"); #endif Handles.SphereCap (-i-1,points[i],Quaternion.identity,HandleUtility.GetHandleSize (points[i])*pointGizmosRadius*2); Vector3 pre = points[i]; Vector3 post = Handles.PositionHandle (points[i],Quaternion.identity); if (pre != post) { script.points[i] = invMatrix.MultiplyPoint3x4(post); } } else { Handles.color = PointColor; Handles.SphereCap (-i-1,points[i],Quaternion.identity,HandleUtility.GetHandleSize (points[i])*pointGizmosRadius); } } #if UNITY_LE_4_3 if(Input.GetMouseButtonDown(0)) { // Register the undos when we press the Mouse button. Undo.CreateSnapshot(); Undo.RegisterSnapshot(); } #endif if (Event.current.type == EventType.MouseDown) { int pre = selectedPoint; selectedPoint = -(HandleUtility.nearestControl+1); if (pre != selectedPoint) GUI.changed = true; } if (Event.current.type == EventType.MouseDown && Event.current.shift && Tools.current == Tool.Move) { if (((int)Event.current.modifiers & (int)EventModifiers.Alt) != 0) { //int nearestControl = -(HandleUtility.nearestControl+1); if (selectedPoint >= 0 && selectedPoint < points.Count) { #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Removed Point"); #else Undo.RecordObject (script,"Removed Point"); #endif List<Vector3> arr = new List<Vector3>(script.points); arr.RemoveAt (selectedPoint); points.RemoveAt (selectedPoint); script.points = arr.ToArray (); script.RecalcConvex (); GUI.changed = true; } } else if (((int)Event.current.modifiers & (int)EventModifiers.Control) != 0 && points.Count > 1) { int minSeg = 0; float minDist = float.PositiveInfinity; for (int i=0;i<points.Count;i++) { float dist = HandleUtility.DistanceToLine (points[i],points[(i+1)%points.Count]); if (dist < minDist) { minSeg = i; minDist = dist; } } System.Object hit = HandleUtility.RaySnap (HandleUtility.GUIPointToWorldRay(Event.current.mousePosition)); if (hit != null) { RaycastHit rayhit = (RaycastHit)hit; #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Added Point"); #else Undo.RecordObject (script,"Added Point"); #endif List<Vector3> arr = Pathfinding.Util.ListPool<Vector3>.Claim (); arr.AddRange (script.points); points.Insert (minSeg+1,rayhit.point); if (!script.useWorldSpace) rayhit.point = invMatrix.MultiplyPoint3x4 (rayhit.point); arr.Insert (minSeg+1,rayhit.point); script.points = arr.ToArray (); script.RecalcConvex (); Pathfinding.Util.ListPool<Vector3>.Release (arr); GUI.changed = true; } } else { System.Object hit = HandleUtility.RaySnap (HandleUtility.GUIPointToWorldRay(Event.current.mousePosition)); if (hit != null) { RaycastHit rayhit = (RaycastHit)hit; #if UNITY_LE_4_3 Undo.RegisterUndo (script,"Added Point"); #else Undo.RecordObject (script,"Added Point"); #endif Vector3[] arr = new Vector3[script.points.Length+1]; for (int i=0;i<script.points.Length;i++) { arr[i] = script.points[i]; } points.Add (rayhit.point); if (!script.useWorldSpace) rayhit.point = invMatrix.MultiplyPoint3x4 (rayhit.point); arr[script.points.Length] = rayhit.point; script.points = arr; script.RecalcConvex (); GUI.changed = true; } } Event.current.Use (); } if (Event.current.shift && Event.current.type == EventType.MouseDrag) { //Event.current.Use (); } #if !UNITY_LE_4_3 if ( lastUndoGroup != Undo.GetCurrentGroup () ) { script.RecalcConvex (); } #endif Pathfinding.Util.ListPool<Vector3>.Release (points); if (GUI.changed) { HandleUtility.Repaint (); EditorUtility.SetDirty (target); } } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime.Tree { using System.Linq; using ArgumentNullException = System.ArgumentNullException; using CLSCompliant = System.CLSCompliantAttribute; /** <summary> * A tree node that is wrapper for a Token object. After 3.0 release * while building tree rewrite stuff, it became clear that computing * parent and child index is very difficult and cumbersome. Better to * spend the space in every tree node. If you don't want these extra * fields, it's easy to cut them out in your own BaseTree subclass. * </summary> */ [System.Serializable] public class CommonTree : BaseTree { /** <summary>A single token is the payload</summary> */ private IToken _token; /** <summary> * What token indexes bracket all tokens associated with this node * and below? * </summary> */ protected int startIndex = -1; protected int stopIndex = -1; /** <summary>Who is the parent node of this node; if null, implies node is root</summary> */ CommonTree parent; /** <summary>What index is this node in the child list? Range: 0..n-1</summary> */ int childIndex = -1; public CommonTree() { } public CommonTree( CommonTree node ) : base( node ) { if (node == null) throw new ArgumentNullException("node"); this.Token = node.Token; this.startIndex = node.startIndex; this.stopIndex = node.stopIndex; } public CommonTree( IToken t ) { this.Token = t; } #region Properties public override int CharPositionInLine { get { if ( Token == null || Token.CharPositionInLine == -1 ) { if ( ChildCount > 0 ) return Children[0].CharPositionInLine; return 0; } return Token.CharPositionInLine; } set { base.CharPositionInLine = value; } } public override int ChildIndex { get { return childIndex; } set { childIndex = value; } } public override bool IsNil { get { return Token == null; } } public override int Line { get { if ( Token == null || Token.Line == 0 ) { if ( ChildCount > 0 ) return Children[0].Line; return 0; } return Token.Line; } set { base.Line = value; } } public override ITree Parent { get { return parent; } set { parent = (CommonTree)value; } } public override string Text { get { if ( Token == null ) return null; return Token.Text; } set { } } public IToken Token { get { return _token; } set { _token = value; } } public override int TokenStartIndex { get { if ( startIndex == -1 && Token != null ) return Token.TokenIndex; return startIndex; } set { startIndex = value; } } public override int TokenStopIndex { get { if ( stopIndex == -1 && Token != null ) { return Token.TokenIndex; } return stopIndex; } set { stopIndex = value; } } public override int Type { get { if ( Token == null ) return TokenTypes.Invalid; return Token.Type; } set { } } #endregion public override ITree DupNode() { return new CommonTree( this ); } /** <summary> * For every node in this subtree, make sure it's start/stop token's * are set. Walk depth first, visit bottom up. Only updates nodes * with at least one token index &lt; 0. * </summary> */ public virtual void SetUnknownTokenBoundaries() { if ( Children == null ) { if ( startIndex < 0 || stopIndex < 0 ) startIndex = stopIndex = Token.TokenIndex; return; } foreach (var child in Children.OfType<CommonTree>()) child.SetUnknownTokenBoundaries(); if ( startIndex >= 0 && stopIndex >= 0 ) return; // already set if ( Children.Count > 0 ) { ITree firstChild = Children[0]; ITree lastChild = Children[Children.Count - 1]; startIndex = firstChild.TokenStartIndex; stopIndex = lastChild.TokenStopIndex; } } public override string ToString() { if (IsNil) return "nil"; if (Type == TokenTypes.Invalid) return "<errornode>"; if (Token == null) return string.Empty; return Token.Text; } } }
// Copyright (c) Aspose 2002-2014. All Rights Reserved. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Text; using System.Threading; using System.Windows.Forms; using System.IO; using System.Security; using Aspose.CreateProjectWizard.Library; using System.Net; using Aspose.CreateProjectWizard.com.aspose.community; namespace Aspose.CreateProjectWizard { public partial class InstallProcessControl : InstallerControl { public InstallProcessControl() { InitializeComponent(); this.Load += new EventHandler(InstallProcessControl_Load); descriptionLabel.Text = string.Empty; //NoOfTasksCompletedLabel.Text = string.Empty; } private void InstallProcessControl_Load(object sender, EventArgs e) { Form.SetTitle("Aspose DNN Project"); Form.SetSubTitle(ApplicationSettings.FormatString("Thank you for your patience while we configure your preferences")); Form.PrevButton.Enabled = false; Form.NextButton.Enabled = false; } protected internal override void RequestCancel() { Form.AbortButton.Enabled = false; } protected internal override void Open() { if (GlobalData.SelectedProductsList.Count > 0) { if (CheckConnectivity()) { GlobalData.backgroundWorker = new BackgroundWorker(); GlobalData.backgroundWorker.WorkerReportsProgress = true; GlobalData.backgroundWorker.WorkerSupportsCancellation = true; GlobalData.backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork); GlobalData.backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged); GlobalData.backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted); GlobalData.backgroundWorker.RunWorkerAsync(); return; } } UpdateProgress(0, ProgressBarType.CurrentTaskProgress); UpdateProgress(0, ProgressBarType.OverAllProgress); UpdateText("All operations completed", LabelType.TaskDescription); Form.Dispose(); } private DialogResult ShowNotConnectedAlert() { DialogResult result = MessageBox.Show("It seems there is an error with your internet connection. This might be due to various reasons. Please check your cables, internet and router settings and retry. If this does not help please check your proxy settings.", "Connection Problem", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); return result; } private bool CheckConnectivity() { if (!AsposeManager.IsInternetConnected) { DialogResult result = ShowNotConnectedAlert(); if (result == DialogResult.Cancel) return false; while (result == DialogResult.Retry) { if (!AsposeManager.IsInternetConnected) { result = ShowNotConnectedAlert(); if (result == DialogResult.Cancel) return false; } else { return true; } } } return true; } private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { try { if (GlobalData.backgroundWorker.CancellationPending) { e.Cancel = true; return; } UpdateProgress(1, ProgressBarType.CurrentTaskProgress); UpdateProgress(1, ProgressBarType.OverAllProgress); int total = GlobalData.SelectedProductsList.Count; string taskCompletedText = "{0} of {1} Completed"; UpdateText(string.Format(taskCompletedText, 0, total), LabelType.NoOfTasksCompleted); for (int index = 0; index < GlobalData.SelectedProductsList.Count; index++) { UpdateText("Downloading " + GlobalData.SelectedProductsList[index], LabelType.TaskDescription); DownloadFileFromWeb(GlobalData.SelectedProductsList[index]); decimal percentage = ((decimal)(index + 1) / (decimal)GlobalData.SelectedProductsList.Count) * 100; UpdateProgress(Convert.ToInt32(percentage), ProgressBarType.OverAllProgress); UpdateText(string.Format(taskCompletedText, index + 1, total), LabelType.NoOfTasksCompleted); } UpdateProgress(100, ProgressBarType.CurrentTaskProgress); UpdateProgress(100, ProgressBarType.OverAllProgress); UpdateText(string.Format(taskCompletedText, total, total), LabelType.NoOfTasksCompleted); UpdateText("All operations completed", LabelType.TaskDescription); } catch (Exception) { } } private void DownloadFileFromWeb(string productName) { try { ProductRelease productRelease = AsposeManager.GetProductReleaseInformation(productName); if (productRelease == null) { return; } string downloadURL = productRelease.DownloadLink; string downloadFolderRoot = AsposeManager.GetAsposeDownloadFolder(productName); GlobalData.backgroundWorker.ReportProgress(1); if (AsposeManager.IsReleaseExists(productName, downloadFolderRoot, productRelease.VersionNumber)) { GlobalData.backgroundWorker.ReportProgress(100); return; } string downloadedReleasePath = downloadFolderRoot + "\\" + productName.ToLower() + ".zip"; GlobalData.backgroundWorker.ReportProgress(1); Uri url = new Uri(downloadURL); string sFileName = Path.GetFileName(url.LocalPath); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); // gets the size of the file in bytes long iSize = response.ContentLength; // keeps track of the total bytes downloaded so we can update the progress bar long iRunningByteTotal = 0; WebClient client = new WebClient(); Stream strRemote = client.OpenRead(url); FileStream strLocal = new FileStream(downloadedReleasePath, FileMode.Create, FileAccess.Write, FileShare.None); int iByteSize = 0; byte[] byteBuffer = new byte[1024]; while ((iByteSize = strRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { // write the bytes to the file system at the file path specified strLocal.Write(byteBuffer, 0, iByteSize); iRunningByteTotal += iByteSize; // calculate the progress out of a base "100" double dIndex = (double)(iRunningByteTotal); double dTotal = (double)iSize; double dProgressPercentage = (dIndex / dTotal); int iProgressPercentage = (int)(dProgressPercentage * 98); GlobalData.backgroundWorker.ReportProgress(iProgressPercentage); } strLocal.Close(); strRemote.Close(); AsposeManager.ExtractZipFile(downloadedReleasePath, downloadFolderRoot); AsposeManager.SaveReleaseInfo(productName, downloadFolderRoot, productRelease.VersionNumber); GlobalData.backgroundWorker.ReportProgress(100); } catch (Exception) { MessageBox.Show("An error occurred while downloading Aspose components. Your module will be created but may not contain all the components you have selected. Please make sure you have an active internet connection and then try creating the project again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); if (Form != null) Form.Dispose(); } GlobalData.backgroundWorker.ReportProgress(100); } private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (e.ProgressPercentage == 0) currentTaskProgressBar.Value = 1; else currentTaskProgressBar.Value = e.ProgressPercentage; } private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (Form != null) Form.Dispose(); } #region Delegates private enum LabelType { NoOfTasksCompleted = 1, CurrentlyInstalling = 2, OverAllProgress = 3, TaskDescription = 4 } private enum ProgressBarType { CurrentTaskProgress = 1, OverAllProgress = 2 } private void UpdateText(string textToUpdate, LabelType labelType) { if (GlobalData.backgroundWorker != null) { if (labelType == LabelType.NoOfTasksCompleted) { NoOfTasksCompletedLabel.BeginInvoke(new UpdateNoOfTasksCompletedCallback(this.UpdateNoOfTasksCompletedLabel), new object[] { textToUpdate }); } else if (labelType == LabelType.CurrentlyInstalling) { currentlyInstallingLabel.BeginInvoke(new UpdateCurrentTaskLabelCallback(this.UpdateCurrentTaskLabel), new object[] { textToUpdate }); } else if (labelType == LabelType.OverAllProgress) { overAllProgressLabel.BeginInvoke(new UpdateTotalLabelCallback(this.UpdateTotalLabel), new object[] { textToUpdate }); } else if (labelType == LabelType.TaskDescription) { descriptionLabel.BeginInvoke(new TaskDescriptionCallback(this.TaskDescriptionLabel), new object[] { textToUpdate }); } } } private void UpdateProgress(int progressValue, ProgressBarType progressBarType) { if (GlobalData.backgroundWorker != null) { if (progressBarType == ProgressBarType.CurrentTaskProgress) { currentTaskProgressBar.BeginInvoke(new UpdateCurrentProgressBarCallback(this.UpdateCurrentProgressBar), new object[] { progressValue }); } else if (progressBarType == ProgressBarType.OverAllProgress) { totalProgressBar.BeginInvoke(new UpdateTotalProgressBarCallback(this.UpdateTotalProgressBar), new object[] { progressValue }); } } } public delegate void TaskDescriptionCallback(string value); private void TaskDescriptionLabel(string value) { descriptionLabel.Text = value; } public delegate void UpdateNoOfTasksCompletedCallback(string value); private void UpdateNoOfTasksCompletedLabel(string value) { NoOfTasksCompletedLabel.Text = value; } public delegate void UpdateCurrentTaskLabelCallback(string value); private void UpdateCurrentTaskLabel(string value) { currentlyInstallingLabel.Text = value; } public delegate void UpdateCurrentProgressBarCallback(int value); private void UpdateCurrentProgressBar(int value) { if (value < 0) value = 0; if (value > 100) value = 100; currentTaskProgressBar.Value = value; } public delegate void UpdateTotalLabelCallback(string value); private void UpdateTotalLabel(string value) { overAllProgressLabel.Text = value; } public delegate void UpdateTotalProgressBarCallback(int value); private void UpdateTotalProgressBar(int value) { if (value < 0) value = 0; if (value > 100) value = 100; totalProgressBar.Value = value; } #endregion Delegates } }
using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Util; using Lucene.Net.Util.Fst; using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Codecs.BlockTerms { /* * 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. */ /// <summary> /// See <see cref="VariableGapTermsIndexWriter"/>. /// <para/> /// @lucene.experimental /// </summary> public class VariableGapTermsIndexReader : TermsIndexReaderBase { private readonly PositiveInt32Outputs fstOutputs = PositiveInt32Outputs.Singleton; private int indexDivisor; // Closed if indexLoaded is true: private IndexInput input; private volatile bool indexLoaded; private readonly IDictionary<FieldInfo, FieldIndexData> fields = new Dictionary<FieldInfo, FieldIndexData>(); // start of the field info data private long dirOffset; private readonly int version; private readonly string segment; public VariableGapTermsIndexReader(Directory dir, FieldInfos fieldInfos, string segment, int indexDivisor, string segmentSuffix, IOContext context) { input = dir.OpenInput(IndexFileNames.SegmentFileName(segment, segmentSuffix, VariableGapTermsIndexWriter.TERMS_INDEX_EXTENSION), new IOContext(context, true)); this.segment = segment; bool success = false; Debug.Assert(indexDivisor == -1 || indexDivisor > 0); try { version = ReadHeader(input); this.indexDivisor = indexDivisor; if (version >= VariableGapTermsIndexWriter.VERSION_CHECKSUM) { CodecUtil.ChecksumEntireFile(input); } SeekDir(input, dirOffset); // Read directory int numFields = input.ReadVInt32(); if (numFields < 0) { throw new CorruptIndexException("invalid numFields: " + numFields + " (resource=" + input + ")"); } for (int i = 0; i < numFields; i++) { int field = input.ReadVInt32(); long indexStart = input.ReadVInt64(); FieldInfo fieldInfo = fieldInfos.FieldInfo(field); FieldIndexData previous = fields.Put(fieldInfo, new FieldIndexData(this, fieldInfo, indexStart)); if (previous != null) { throw new CorruptIndexException("duplicate field: " + fieldInfo.Name + " (resource=" + input + ")"); } } success = true; } finally { if (indexDivisor > 0) { input.Dispose(); input = null; if (success) { indexLoaded = true; } } } } public override int Divisor => indexDivisor; private int ReadHeader(IndexInput input) { int version = CodecUtil.CheckHeader(input, VariableGapTermsIndexWriter.CODEC_NAME, VariableGapTermsIndexWriter.VERSION_START, VariableGapTermsIndexWriter.VERSION_CURRENT); if (version < VariableGapTermsIndexWriter.VERSION_APPEND_ONLY) { dirOffset = input.ReadInt64(); } return version; } private class IndexEnum : FieldIndexEnum { private readonly BytesRefFSTEnum<long?> fstEnum; private BytesRefFSTEnum.InputOutput<long?> current; public IndexEnum(FST<long?> fst) { fstEnum = new BytesRefFSTEnum<long?>(fst); } public override BytesRef Term { get { if (current == null) { return null; } else { return current.Input; } } } public override long Seek(BytesRef target) { //System.out.println("VGR: seek field=" + fieldInfo.name + " target=" + target); current = fstEnum.SeekFloor(target); //System.out.println(" got input=" + current.input + " output=" + current.output); if (current.Output.HasValue) { return current.Output.Value; } else { throw new NullReferenceException("_current.Output is null"); // LUCENENET NOTE: NullReferenceException would be thrown in Java, so doing it here } } public override long Next() { //System.out.println("VGR: next field=" + fieldInfo.name); current = fstEnum.Next(); if (current == null) { //System.out.println(" eof"); return -1; } else { if (current.Output.HasValue) { return current.Output.Value; } else { throw new NullReferenceException("_current.Output is null"); // LUCENENET NOTE: NullReferenceException would be thrown in Java, so doing it here } } } public override long Ord => throw new NotSupportedException(); public override long Seek(long ord) { throw new NotSupportedException(); } } public override bool SupportsOrd => false; private class FieldIndexData { private readonly VariableGapTermsIndexReader outerInstance; private readonly long indexStart; // Set only if terms index is loaded: internal volatile FST<long?> fst; public FieldIndexData(VariableGapTermsIndexReader outerInstance, FieldInfo fieldInfo, long indexStart) { this.outerInstance = outerInstance; this.indexStart = indexStart; if (outerInstance.indexDivisor > 0) { LoadTermsIndex(); } } private void LoadTermsIndex() { if (fst == null) { using (IndexInput clone = (IndexInput)outerInstance.input.Clone()) { clone.Seek(indexStart); fst = new FST<long?>(clone, outerInstance.fstOutputs); } // clone.Dispose(); /* final String dotFileName = segment + "_" + fieldInfo.name + ".dot"; Writer w = new OutputStreamWriter(new FileOutputStream(dotFileName)); Util.toDot(fst, w, false, false); System.out.println("FST INDEX: SAVED to " + dotFileName); w.close(); */ if (outerInstance.indexDivisor > 1) { // subsample Int32sRef scratchIntsRef = new Int32sRef(); PositiveInt32Outputs outputs = PositiveInt32Outputs.Singleton; Builder<long?> builder = new Builder<long?>(FST.INPUT_TYPE.BYTE1, outputs); BytesRefFSTEnum<long?> fstEnum = new BytesRefFSTEnum<long?>(fst); BytesRefFSTEnum.InputOutput<long?> result; int count = outerInstance.indexDivisor; while ((result = fstEnum.Next()) != null) { if (count == outerInstance.indexDivisor) { builder.Add(Util.Fst.Util.ToInt32sRef(result.Input, scratchIntsRef), result.Output); count = 0; } count++; } fst = builder.Finish(); } } } /// <summary>Returns approximate RAM bytes used.</summary> public virtual long RamBytesUsed() { return fst == null ? 0 : fst.GetSizeInBytes(); } } public override FieldIndexEnum GetFieldEnum(FieldInfo fieldInfo) { FieldIndexData fieldData; if (!fields.TryGetValue(fieldInfo, out fieldData) || fieldData == null || fieldData.fst == null) { return null; } else { return new IndexEnum(fieldData.fst); } } protected override void Dispose(bool disposing) { if (disposing) { if (input != null && !indexLoaded) { input.Dispose(); } } } private void SeekDir(IndexInput input, long dirOffset) { if (version >= VariableGapTermsIndexWriter.VERSION_CHECKSUM) { input.Seek(input.Length - CodecUtil.FooterLength() - 8); dirOffset = input.ReadInt64(); } else if (version >= VariableGapTermsIndexWriter.VERSION_APPEND_ONLY) { input.Seek(input.Length - 8); dirOffset = input.ReadInt64(); } input.Seek(dirOffset); } public override long RamBytesUsed() { long sizeInBytes = 0; foreach (FieldIndexData entry in fields.Values) { sizeInBytes += entry.RamBytesUsed(); } return sizeInBytes; } } }
// 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 OLEDB.Test.ModuleCore; using System.IO; using System.Text; using XmlCoreTest.Common; namespace System.Xml.Tests { /// <summary> /// Summary description for WriterFactory. /// </summary> public class CWriterFactory : CFactory { protected enum WriterType { UTF8Writer, UnicodeWriter }; protected enum WriteThru { Stream, StringBuilder, TextWriter, XmlWriter }; protected enum WriterOverload { StringBuilder, StringWriter, StreamWriter, MemoryStream, TextWriter, UTF8Writer, UnicodeWriter }; private XmlWriter _factoryWriter = null; private XmlWriter _underlyingWriter = null; private Stream _stream = null; private StringBuilder _stringBuilder = null; private TextWriter _textWriter = null; private XmlWriterSettings _settings = new XmlWriterSettings(); private XmlWriterSettings _underlyingSettings = new XmlWriterSettings(); private WriterOverload _overload; protected override void PreTest() { Log("In Pretest..."); SetupSettings(); Log("SetupSettings Done"); SetupWriterOverload(); Log("SetupWriterOverload Done"); pstate = TestState.PreTest; } protected override void Test() { Log("Testing : " + TestFileName); Log("Overload : " + _overload); switch (_overload) { case WriterOverload.MemoryStream: _stream = new MemoryStream(); CreateWriter(WriteThru.Stream); break; case WriterOverload.StreamWriter: _textWriter = new StreamWriter(new MemoryStream()); CreateWriter(WriteThru.TextWriter); break; case WriterOverload.StringBuilder: _stringBuilder = new StringBuilder(); CreateWriter(WriteThru.StringBuilder); break; case WriterOverload.StringWriter: _textWriter = new StringWriter(); CreateWriter(WriteThru.TextWriter); break; case WriterOverload.UnicodeWriter: _underlyingSettings = new XmlWriterSettings(); _underlyingSettings.Encoding = Encoding.Unicode; _underlyingWriter = WriterHelper.Create(TestFileName, _underlyingSettings); CreateWriter(WriteThru.XmlWriter); break; case WriterOverload.UTF8Writer: _underlyingSettings = new XmlWriterSettings(); _underlyingSettings.Encoding = Encoding.UTF8; _underlyingWriter = WriterHelper.Create(TestFileName, _underlyingSettings); CreateWriter(WriteThru.XmlWriter); break; default: throw new CTestFailedException("Unknown WriterOverload: " + _overload); } if (pstate == TestState.Pass) return; CError.Compare(pstate, TestState.CreateSuccess, "Invalid State after Create: " + pstate); //By this time the factory Reader is already set up correctly. So we must go Consume it now. CError.Compare(pstate != TestState.Pass && pstate == TestState.CreateSuccess, "Invalid state before Consuming Reader: " + pstate); //Call TestWriter to Consume Reader; TestWriter(); if (pstate == TestState.Pass) return; CError.Compare(pstate != TestState.Pass && pstate == TestState.Consume, "Invalid state after Consuming Reader: " + pstate); } protected void TestWriter() { pstate = TestState.Consume; try { WriteNodes(); if (!IsVariationValid) { //Invalid Case didn't throw exception. pstate = TestState.Error; DumpVariationInfo(); throw new CTestFailedException("Invalid Variation didn't throw exception"); } else { pstate = TestState.Pass; } } catch (XmlException writerException) { Log(writerException.Message); Log(writerException.StackTrace); if (!IsVariationValid) { if (!CheckException(writerException)) { pstate = TestState.Error; DumpVariationInfo(); throw new CTestFailedException("Invalid Exception Type thrown"); } else { pstate = TestState.Pass; } } else //Variation was valid { pstate = TestState.Error; DumpVariationInfo(); throw new CTestFailedException("Valid Variation throws Unspecified Exception"); } } finally { if (_factoryWriter != null && _factoryWriter.WriteState != WriteState.Closed && _factoryWriter.WriteState != WriteState.Error) { if (_textWriter == null) { CError.WriteLineIgnore(_factoryWriter.WriteState.ToString()); _factoryWriter.Flush(); _factoryWriter.Dispose(); } else { _textWriter.Flush(); _textWriter.Dispose(); } } if (_underlyingWriter != null && _underlyingWriter.WriteState != WriteState.Closed && _underlyingWriter.WriteState != WriteState.Error) { _underlyingWriter.Flush(); _underlyingWriter.Dispose(); } } //If you are not in PASS state at this point you are in Error. if (pstate != TestState.Pass) pstate = TestState.Error; } protected void CompareSettings() { XmlWriterSettings actual = _factoryWriter.Settings; CError.Compare(actual.CheckCharacters, _settings.CheckCharacters, "CheckCharacters"); //This actually checks Conformance Level DCR to some extent. if (_settings.ConformanceLevel != ConformanceLevel.Auto) CError.Compare(actual.ConformanceLevel, _settings.ConformanceLevel, "ConformanceLevel"); CError.Compare(actual.Encoding, _settings.Encoding, "Encoding"); CError.Compare(actual.Indent, _settings.Indent, "Indent"); CError.Compare(actual.IndentChars, _settings.IndentChars, "IndentChars"); CError.Compare(actual.NewLineChars, _settings.NewLineChars, "NewLineChars"); CError.Compare(actual.NewLineOnAttributes, _settings.NewLineOnAttributes, "NewLineOnAttributes"); CError.Compare(actual.NewLineHandling, _settings.NewLineHandling, "NormalizeNewLines"); CError.Compare(actual.OmitXmlDeclaration, _settings.OmitXmlDeclaration, "OmitXmlDeclaration"); } protected void CreateWriter(WriteThru writeThru) { // Assumption is that the Create method doesn't throw NullReferenceException and // it is not the goal of this framework to test if they are thrown anywhere. // but if they are thrown that's a problem and they shouldn't be caught but exposed. Log("Writing thru : " + writeThru); try { switch (writeThru) { case WriteThru.Stream: _factoryWriter = WriterHelper.Create(_stream, _settings); break; case WriteThru.StringBuilder: _factoryWriter = WriterHelper.Create(_stringBuilder, _settings); break; case WriteThru.TextWriter: _factoryWriter = WriterHelper.Create(_textWriter, _settings); break; case WriteThru.XmlWriter: _factoryWriter = WriterHelper.Create(_underlyingWriter, _settings); break; } pstate = TestState.CreateSuccess; } catch (Exception ane) { Log(ane.ToString()); if (!IsVariationValid) { if (!CheckException(ane)) { pstate = TestState.Error; DumpVariationInfo(); throw new CTestFailedException( "Exception Thrown in CreateMethod, is your variation data correct?"); } else { //This means that the Exception was checked and everything is fine. pstate = TestState.Pass; } }//Else valid variation threw exception else { pstate = TestState.Error; DumpVariationInfo(); throw new CTestFailedException( "Exception Thrown in CreateMethod, is your variation data correct?"); } } } protected override void PostTest() { pstate = TestState.Complete; } protected void SetupSettings() { _settings.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), ReadFilterCriteria("ConformanceLevel", true)); _settings.CheckCharacters = bool.Parse(ReadFilterCriteria("CheckCharacters", true)); _settings.CloseOutput = false; _settings.Indent = bool.Parse(ReadFilterCriteria("Indent", true)); _settings.IndentChars = new string(Convert.ToChar(int.Parse(ReadFilterCriteria("IndentChars", true))), 1); _settings.NewLineChars = new string(Convert.ToChar(int.Parse(ReadFilterCriteria("NewLineChars", true))), 1); _settings.NewLineOnAttributes = bool.Parse(ReadFilterCriteria("NewLineOnAttributes", true)); if (bool.Parse(ReadFilterCriteria("NormalizeNewlines", true))) _settings.NewLineHandling = NewLineHandling.Replace; else _settings.NewLineHandling = NewLineHandling.None; _settings.OmitXmlDeclaration = bool.Parse(ReadFilterCriteria("OmitXmlDeclaration", true)); //Reading Writer Type to determine encoding and if the writer type is binary writer. string wt = ReadFilterCriteria("WriterType", true); if (wt == "TextWriter" || wt == "XmlDocumentWriter") { throw new CTestSkippedException("Skipped: WriterType " + wt); } WriterType writerType = (WriterType)Enum.Parse(typeof(WriterType), wt); switch (writerType) { case WriterType.UnicodeWriter: _settings.Encoding = Encoding.Unicode; break; default: break; } } protected void SetupWriterOverload() { string ol = ReadFilterCriteria("Load", true); if (ol == "FileName" || ol == "XmlDocumentWriter" || ol == "InvalidUri") { throw new CTestSkippedException("Skipped: OverLoad " + ol); } _overload = (WriterOverload)Enum.Parse(typeof(WriterOverload), ol); //ReadFilterCriteria("Load", true)); } /// <summary> /// This function writes the test nodes on the factoryWriter. /// This will be called from Test(). If successful it will just return, /// else it will throw an appropriate XmlException. This function can use /// the knowledge of the current writertype to write appropriate data if /// really needed. /// </summary> protected void WriteNodes() { _factoryWriter.WriteStartElement("a", "b", "c"); _factoryWriter.WriteStartElement("d", "e"); _factoryWriter.WriteStartElement("f"); _factoryWriter.WriteStartAttribute("g", "h", "i"); _factoryWriter.WriteStartAttribute("j", "k"); _factoryWriter.WriteStartAttribute("l"); _factoryWriter.WriteString("Some String"); _factoryWriter.WriteEndElement(); _factoryWriter.WriteRaw("<thisisraw/>"); _factoryWriter.WriteProcessingInstruction("somepiname", "somepitext"); _factoryWriter.WriteValue(1000); _factoryWriter.WriteComment("SomeComment"); _factoryWriter.WriteEndElement(); _factoryWriter.WriteCData("< is not a valid thing"); _factoryWriter.WriteCharEntity('a'); _factoryWriter.WriteWhitespace(" "); _factoryWriter.WriteEndElement(); } } }
using System; using System.Net.Http; using System.Threading.Tasks; using Flurl; using Microsoft.Extensions.Logging; using RapidCore.Network; using Skarp.HubSpotClient.Contact.Dto; using Skarp.HubSpotClient.Core; using Skarp.HubSpotClient.Core.Interfaces; using Skarp.HubSpotClient.Core.Requests; using Skarp.HubSpotClient.ListOfContacts.Dto; using Skarp.HubSpotClient.ListOfContacts.Interfaces; namespace Skarp.HubSpotClient.ListOfContacts { public class HubSpotListOfContactsClient : HubSpotBaseClient, IHubSpotListOfContactsClient { /// <summary> /// Mockable and container ready constructor /// </summary> /// <param name="httpClient"></param> /// <param name="logger"></param> /// <param name="serializer"></param> /// <param name="hubSpotBaseUrl"></param> /// <param name="apiKey"></param> public HubSpotListOfContactsClient( IRapidHttpClient httpClient, ILogger<HubSpotListOfContactsClient> logger, RequestSerializer serializer, string hubSpotBaseUrl, string apiKey) : base(httpClient, logger, serializer, hubSpotBaseUrl, apiKey) { } /// <summary> /// Create a new instance of the HubSpotListOfContactsClient with default dependencies /// </summary> /// <remarks> /// This constructor creates a HubSpotListOfContactsClient using "real" dependencies that will send requests /// via the network - if you wish to have support for functional tests and mocking use the "eager" constructor /// that takes in all underlying dependecies /// </remarks> /// <param name="apiKey">Your API key</param> public HubSpotListOfContactsClient(string apiKey) : base( new RealRapidHttpClient(new HttpClient()), NoopLoggerFactory.Get(), new RequestSerializer(new RequestDataConverter(NoopLoggerFactory.Get<RequestDataConverter>())), "https://api.hubapi.com", apiKey) { } /// <summary> /// Creates the a new contact list entity asynchronously. /// https://legacydocs.hubspot.com/docs/methods/lists/create_list /// </summary> /// <param name="entity">The entity.</param> /// <returns></returns> /// <exception cref="NotImplementedException"></exception> public async Task<T> CreateAsync<T>(CreateContactListRequestHubSpotEntity payload) where T : IHubSpotEntity, new() { Logger.LogDebug("ContactList CreateAsync"); var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.Lists); var data = await PutOrPostGeneric<T>(path, payload, true, false); return data; } private async Task<T> PutOrPostGeneric<T>(string absoluteUriPath, ICreateContactListRequestHubSpotEntity entity, bool usePost, bool convertEntity) where T : IHubSpotEntity, new() { string json = null; try { json = _serializer.SerializeEntity(entity, convertEntity); } catch (Exception ex) { Logger.LogDebug("PutOrPostGeneric failed with exception: " + ex.ToString()); throw; } return await SendRequestAsync<T>( absoluteUriPath, usePost ? HttpMethod.Post : HttpMethod.Put, json, responseData => (T)_serializer.DeserializeGenericEntity<T>(responseData)); } /// <summary> /// Delete a list of contact by contact list id from hubspot /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public Task DeleteAsync(long listId) { if (listId < 1) { throw new ArgumentException("listId must be set!"); } var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.Delete) .Replace(":listId:", listId.ToString()); return DeleteAsync<ContactHubSpotEntity>(path); } /// <summary> /// Return a list of contacts for a contact list by id from hubspot /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public async Task<T> GetListByIdAsync<T>(long listId, ListOfContactsRequestOptions opts = null) { Logger.LogDebug("Get contacts for list with id"); if (opts == null) { opts = new ListOfContactsRequestOptions(); } var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.Get) .Replace(":listId:", listId.ToString()) .SetQueryParam("count", opts.NumberOfContactsToReturn); if (opts.ContactOffset.HasValue) { path = path.SetQueryParam("vidOffset", opts.ContactOffset); } var data = await GetGenericAsync<T>(path); return data; } /// <summary> /// Return a list of contact lists from hubspot /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public async Task<T> GetListAsync<T>(ListOfContactListsRequestOptions opts = null) { Logger.LogDebug("Get list of contact lists"); if (opts == null) { opts = new ListOfContactListsRequestOptions(); } var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.Lists) .SetQueryParam("count", opts.NumberOfContactListsToReturn); if (opts.ContactListOffset.HasValue) { path = path.SetQueryParam("vidOffset", opts.ContactListOffset); } var data = await GetGenericAsync<T>(path); return data; } /// <summary> /// Add list of contacts based on list id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public async Task<bool> AddBatchAsync(HubSpotListOfContactsEntity contacts, long listId) { Logger.LogDebug("Add batch of contacts to list of contacts with specified id"); var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.CreateBatch) .Replace(":listId:", listId.ToString()); var data = await PutOrPostGeneric(path, contacts, true); return data; } /// <summary> /// Remove list of contacts based on list id /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public async Task<bool> RemoveBatchAsync(HubSpotListOfContactsEntity contacts, long listId) { Logger.LogDebug("Remove batch of contacts to list of contacts with specified id"); var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.DeleteBatch) .Replace(":listId:", listId.ToString()); var data = await PutOrPostGeneric(path, contacts, true); return data; } /// <summary> /// Resolve a hubspot API path based off the entity and operation that is about to happen /// </summary> /// <param name="entity"></param> /// <param name="action"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public string PathResolver(Contact.Interfaces.IContactHubSpotEntity entity, HubSpotAction action) { switch (action) { case HubSpotAction.Get: return $"{entity.RouteBasePath}/lists/:listId:/contacts/all"; case HubSpotAction.Lists: return $"{entity.RouteBasePath}/lists"; case HubSpotAction.CreateBatch: return $"{entity.RouteBasePath}/lists/:listId:/add"; case HubSpotAction.Delete: return $"{entity.RouteBasePath}/lists/:listId:"; case HubSpotAction.DeleteBatch: return $"{entity.RouteBasePath}/lists/:listId:/remove"; default: throw new ArgumentOutOfRangeException(nameof(action), action, null); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.ObjectModel; using System.Management.Automation.Provider; using Dbg = System.Management.Automation; namespace System.Management.Automation { /// <summary> /// Exposes the Content nouns to the Cmdlet Providers to the Cmdlet base class. The methods of this class /// use the providers to perform operations. /// </summary> public sealed class ContentCmdletProviderIntrinsics { #region Constructors /// <summary> /// Hide the default constructor since we always require an instance of SessionState /// </summary> private ContentCmdletProviderIntrinsics() { Dbg.Diagnostics.Assert( false, "This constructor should never be called. Only the constructor that takes an instance of SessionState should be called."); } // CmdletProviderIntrinsics private /// <summary> /// Constructs a facade over the "real" session state API /// </summary> /// /// <param name="cmdlet"> /// An instance of the cmdlet. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="cmdlet"/> is null. /// </exception> /// internal ContentCmdletProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } _cmdlet = cmdlet; _sessionState = cmdlet.Context.EngineSessionState; } // ContentCmdletProviderIntrinsics internal /// <summary> /// Constructs a facade over the "real" session state API /// </summary> /// /// <param name="sessionState"> /// An instance of the sessionState. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="sessionState"/> is null. /// </exception> /// internal ContentCmdletProviderIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { throw PSTraceSource.NewArgumentNullException("sessionState"); } _sessionState = sessionState; } // ContentCmdletProviderIntrinsics internal #endregion Constructors #region Public methods #region GetContentReader /// <summary> /// Gets the content reader for the item at the specified path /// </summary> /// /// <param name="path"> /// The path to the item to get the content reader for. /// </param> /// /// <returns> /// The IContentReader for the item(s) at the specified path. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> public Collection<IContentReader> GetReader(string path) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return _sessionState.GetContentReader(new string[] { path }, false, false); } // GetContentReader /// <summary> /// Gets the content reader for the item at the specified path /// </summary> /// /// <param name="path"> /// The path(s) to the item(s) to get the content reader for. /// </param> /// /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <returns> /// The IContentReader for the item(s) at the specified path. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> public Collection<IContentReader> GetReader(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return _sessionState.GetContentReader(path, force, literalPath); } /// <summary> /// </summary> /// /// <param name="path"> /// </param> /// /// <param name="context"> /// </param> /// /// <returns> /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> internal Collection<IContentReader> GetReader( string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return _sessionState.GetContentReader(new string[] { path }, context); } // GetContentReader /// <summary> /// Gets the dynamic parameters for the get-content cmdlet. /// </summary> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> internal object GetContentReaderDynamicParameters( string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return _sessionState.GetContentReaderDynamicParameters(path, context); } // GetContentReaderDynamicParameters #endregion GetContentReader #region GetContentWriter /// <summary> /// Gets the content writer for the item(s) at the specified path. /// </summary> /// /// <param name="path"> /// The path to the item(s) to get the content writer for. /// </param> /// /// <returns> /// The IContentWriter for the item(s) at the specified path. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> public Collection<IContentWriter> GetWriter(string path) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return _sessionState.GetContentWriter(new string[] { path }, false, false); } // GetContentWriter /// <summary> /// Gets the content writer for the item(s) at the specified path. /// </summary> /// /// <param name="path"> /// The path(s) to the item(s) to get the content writer for. /// </param> /// /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <returns> /// The IContentWriter for the item(s) at the specified path. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> public Collection<IContentWriter> GetWriter(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return _sessionState.GetContentWriter(path, force, literalPath); } // GetContentWriter /// <summary> /// </summary> /// /// <param name="path"> /// </param> /// /// <param name="context"> /// </param> /// /// <returns> /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> internal Collection<IContentWriter> GetWriter( string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return _sessionState.GetContentWriter(new string[] { path }, context); } // GetContentWriter /// <summary> /// Gets the dynamic parameters for the set-content and add-content cmdlet. /// </summary> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> internal object GetContentWriterDynamicParameters( string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return _sessionState.GetContentWriterDynamicParameters(path, context); } // GetContentWriterDynamicParameters #endregion GetContentWriter #region ClearContent /// <summary> /// Clears the content from the item(s) specified by the path /// </summary> /// /// <param name="path"> /// The path to the item(s) to clear the content from. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> public void Clear(string path) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object _sessionState.ClearContent(new string[] { path }, false, false); } // ClearContent /// <summary> /// Clears the content from the item(s) specified by the path /// </summary> /// /// <param name="path"> /// The path(s) to the item(s) to clear the content from. /// </param> /// /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> public void Clear(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object _sessionState.ClearContent(path, force, literalPath); } /// <summary> /// Clears the content from the specified item(s) /// </summary> /// /// <param name="path"> /// The path to the item(s) to clear the content from. /// </param> /// /// <param name="context"> /// The context under which the command is running. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> internal void Clear(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object _sessionState.ClearContent(new string[] { path }, context); } // ClearContent /// <summary> /// Gets the dynamic parameters for the clear-content cmdlet. /// </summary> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> internal object ClearContentDynamicParameters(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return _sessionState.ClearContentDynamicParameters(path, context); } // ClearContentDynamicParameters #endregion ClearContent #endregion Public methods #region private data private Cmdlet _cmdlet; private SessionStateInternal _sessionState; #endregion private data } // ContentCmdletProviderIntrinsics }
// 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; using System.Collections.Specialized; using System.DirectoryServices.Interop; using System.ComponentModel; using INTPTR_INTPTRCAST = System.IntPtr; namespace System.DirectoryServices { /// <devdoc> /// Performs queries against the Active Directory hierarchy. /// </devdoc> public class DirectorySearcher : Component { private DirectoryEntry _searchRoot; private string _filter = defaultFilter; private StringCollection _propertiesToLoad; private bool _disposed = false; private static readonly TimeSpan s_minusOneSecond = new TimeSpan(0, 0, -1); // search preference variables private SearchScope _scope = System.DirectoryServices.SearchScope.Subtree; private bool _scopeSpecified = false; private int _sizeLimit = 0; private TimeSpan _serverTimeLimit = s_minusOneSecond; private TimeSpan _clientTimeout = s_minusOneSecond; private int _pageSize = 0; private TimeSpan _serverPageTimeLimit = s_minusOneSecond; private ReferralChasingOption _referralChasing = ReferralChasingOption.External; private SortOption _sort = new SortOption(); private bool _cacheResults = true; private bool _cacheResultsSpecified = false; private bool _rootEntryAllocated = false; // true: if a temporary entry inside Searcher has been created private string _assertDefaultNamingContext = null; private string _attributeScopeQuery = ""; private bool _attributeScopeQuerySpecified = false; private DereferenceAlias _derefAlias = DereferenceAlias.Never; private SecurityMasks _securityMask = SecurityMasks.None; private ExtendedDN _extendedDN = ExtendedDN.None; private DirectorySynchronization _sync = null; internal bool directorySynchronizationSpecified = false; private DirectoryVirtualListView _vlv = null; internal bool directoryVirtualListViewSpecified = false; internal SearchResultCollection searchResult = null; private const string defaultFilter = "(objectClass=*)"; /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, /// <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default values. /// </devdoc> public DirectorySearcher() : this(null, defaultFilter, null, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with /// <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default /// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to the given value. /// </devdoc> public DirectorySearcher(DirectoryEntry searchRoot) : this(searchRoot, defaultFilter, null, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with /// <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default /// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the respective given values. /// </devdoc> public DirectorySearcher(DirectoryEntry searchRoot, string filter) : this(searchRoot, filter, null, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with /// <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to its default /// value, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values. /// </devdoc> public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad) : this(searchRoot, filter, propertiesToLoad, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, /// <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default /// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the given value. /// </devdoc> public DirectorySearcher(string filter) : this(null, filter, null, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> /// and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default /// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values. /// </devdoc> public DirectorySearcher(string filter, string[] propertiesToLoad) : this(null, filter, propertiesToLoad, System.DirectoryServices.SearchScope.Subtree) { _scopeSpecified = false; } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to its default /// value, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to the respective given values. /// </devdoc> public DirectorySearcher(string filter, string[] propertiesToLoad, SearchScope scope) : this(null, filter, propertiesToLoad, scope) { } /// <devdoc> /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with the <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> properties set to the given /// values. /// </devdoc> public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope) { _searchRoot = searchRoot; _filter = filter; if (propertiesToLoad != null) PropertiesToLoad.AddRange(propertiesToLoad); this.SearchScope = scope; } protected override void Dispose(bool disposing) { // safe to call while finalizing or disposing // if (!_disposed && disposing) { if (_rootEntryAllocated) _searchRoot.Dispose(); _rootEntryAllocated = false; _disposed = true; } base.Dispose(disposing); } /// <devdoc> /// Gets or sets a value indicating whether the result should be cached on the /// client machine. /// </devdoc> [DefaultValue(true)] public bool CacheResults { get => _cacheResults; set { // user explicitly set CacheResults to true and also want VLV if (directoryVirtualListViewSpecified == true && value == true) throw new ArgumentException(SR.DSBadCacheResultsVLV); _cacheResults = value; _cacheResultsSpecified = true; } } /// <devdoc> /// Gets or sets the maximum amount of time that the client waits for /// the server to return results. If the server does not respond within this time, /// the search is aborted, and no results are returned. /// </devdoc> public TimeSpan ClientTimeout { get => _clientTimeout; set { // prevent integer overflow if (value.TotalSeconds > int.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, nameof(value)); } _clientTimeout = value; } } /// <devdoc> /// Gets or sets a value indicating whether the search should retrieve only the names of requested /// properties or the names and values of requested properties. /// </devdoc> [DefaultValue(false)] public bool PropertyNamesOnly { get; set; } /// <devdoc> /// Gets or sets the Lightweight Directory Access Protocol (LDAP) filter string format. /// </devdoc> [ DefaultValue(defaultFilter), // CoreFXPort - Remove design support // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign) ] public string Filter { get => _filter; set { if (value == null || value.Length == 0) value = defaultFilter; _filter = value; } } /// <devdoc> /// Gets or sets the page size in a paged search. /// </devdoc> [DefaultValue(0)] public int PageSize { get => _pageSize; set { if (value < 0) throw new ArgumentException(SR.DSBadPageSize); // specify non-zero pagesize explicitly and also want dirsync if (directorySynchronizationSpecified == true && value != 0) throw new ArgumentException(SR.DSBadPageSizeDirsync); _pageSize = value; } } /// <devdoc> /// Gets the set of properties retrieved during the search. By default, the <see cref='System.DirectoryServices.DirectoryEntry.Path'/> /// and <see cref='System.DirectoryServices.DirectoryEntry.Name'/> properties are retrieved. /// </devdoc> public StringCollection PropertiesToLoad { get { if (_propertiesToLoad == null) { _propertiesToLoad = new StringCollection(); } return _propertiesToLoad; } } /// <devdoc> /// Gets or sets how referrals are chased. /// </devdoc> [DefaultValue(ReferralChasingOption.External)] public ReferralChasingOption ReferralChasing { get => _referralChasing; set { if (value != ReferralChasingOption.None && value != ReferralChasingOption.Subordinate && value != ReferralChasingOption.External && value != ReferralChasingOption.All) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ReferralChasingOption)); _referralChasing = value; } } /// <devdoc> /// Gets or sets the scope of the search that should be observed by the server. /// </devdoc> [DefaultValue(SearchScope.Subtree)] public SearchScope SearchScope { get => _scope; set { if (value < SearchScope.Base || value > SearchScope.Subtree) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SearchScope)); // user explicitly set SearchScope to something other than Base and also want to do ASQ, it is not supported if (_attributeScopeQuerySpecified == true && value != SearchScope.Base) { throw new ArgumentException(SR.DSBadASQSearchScope); } _scope = value; _scopeSpecified = true; } } /// <devdoc> /// Gets or sets the time limit that the server should observe to search a page of results (as /// opposed to the time limit for the entire search). /// </devdoc> public TimeSpan ServerPageTimeLimit { get => _serverPageTimeLimit; set { // prevent integer overflow if (value.TotalSeconds > int.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, nameof(value)); } _serverPageTimeLimit = value; } } /// <devdoc> /// Gets or sets the maximum amount of time the server spends searching. If the /// time limit is reached, only entries found up to that point will be returned. /// </devdoc> public TimeSpan ServerTimeLimit { get => _serverTimeLimit; set { // prevent integer overflow if (value.TotalSeconds > int.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, nameof(value)); } _serverTimeLimit = value; } } /// <devdoc> /// Gets or sets the maximum number of objects that the /// server should return in a search. /// </devdoc> [DefaultValue(0)] public int SizeLimit { get => _sizeLimit; set { if (value < 0) throw new ArgumentException(SR.DSBadSizeLimit); _sizeLimit = value; } } /// <devdoc> /// Gets or sets the node in the Active Directory hierarchy /// at which the search will start. /// </devdoc> [DefaultValue(null)] public DirectoryEntry SearchRoot { get { if (_searchRoot == null && !DesignMode) { // get the default naming context. This should be the default root for the search. DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE", true, null, null, AuthenticationTypes.Secure); //SECREVIEW: Searching the root of the DS will demand browse permissions // on "*" or "LDAP://RootDSE". string defaultNamingContext = (string)rootDSE.Properties["defaultNamingContext"][0]; rootDSE.Dispose(); _searchRoot = new DirectoryEntry("LDAP://" + defaultNamingContext, true, null, null, AuthenticationTypes.Secure); _rootEntryAllocated = true; _assertDefaultNamingContext = "LDAP://" + defaultNamingContext; } return _searchRoot; } set { if (_rootEntryAllocated) _searchRoot.Dispose(); _rootEntryAllocated = false; _assertDefaultNamingContext = null; _searchRoot = value; } } /// <devdoc> /// Gets the property on which the results should be sorted. /// </devdoc> [TypeConverter(typeof(ExpandableObjectConverter))] public SortOption Sort { get => _sort; set => _sort = value ?? throw new ArgumentNullException(nameof(value)); } /// <devdoc> /// Gets or sets a value indicating whether searches should be carried out in an asynchronous /// way. /// </devdoc> [DefaultValue(false)] public bool Asynchronous { get; set; } /// <devdoc> /// Gets or sets a value indicating whether the search should also return deleted objects that match the search /// filter. /// </devdoc> [DefaultValue(false)] public bool Tombstone { get; set; } /// <devdoc> /// Gets or sets an attribute name to indicate that an attribute-scoped query search should be /// performed. /// </devdoc> [ DefaultValue(""), // CoreFXPort - Remove design support // TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign) ] public string AttributeScopeQuery { get => _attributeScopeQuery; set { if (value == null) value = ""; // user explicitly set AttributeScopeQuery and value is not null or empty string if (value.Length != 0) { if (_scopeSpecified == true && SearchScope != SearchScope.Base) { throw new ArgumentException(SR.DSBadASQSearchScope); } // if user did not explicitly set search scope _scope = SearchScope.Base; _attributeScopeQuerySpecified = true; } else // user explicitly sets the value to default one and doesn't want to do asq { _attributeScopeQuerySpecified = false; } _attributeScopeQuery = value; } } /// <devdoc> /// Gets or sets a value to indicate how the aliases of found objects are to be /// resolved. /// </devdoc> [DefaultValue(DereferenceAlias.Never)] public DereferenceAlias DerefAlias { get => _derefAlias; set { if (value < DereferenceAlias.Never || value > DereferenceAlias.Always) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DereferenceAlias)); _derefAlias = value; } } /// <devdoc> /// Gets or sets a value to indicate the search should return security access information for the specified /// attributes. /// </devdoc> [DefaultValue(SecurityMasks.None)] public SecurityMasks SecurityMasks { get => _securityMask; set { // make sure the behavior is consistent with native ADSI if (value > (SecurityMasks.None | SecurityMasks.Owner | SecurityMasks.Group | SecurityMasks.Dacl | SecurityMasks.Sacl)) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SecurityMasks)); _securityMask = value; } } /// <devdoc> /// Gets or sets a value to return extended DNs according to the requested /// format. /// </devdoc> [DefaultValue(ExtendedDN.None)] public ExtendedDN ExtendedDN { get => _extendedDN; set { if (value < ExtendedDN.None || value > ExtendedDN.Standard) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ExtendedDN)); _extendedDN = value; } } /// <devdoc> /// Gets or sets a value to indicate a directory synchronization search, which returns all changes since a specified /// state. /// </devdoc> [DefaultValue(null)] public DirectorySynchronization DirectorySynchronization { get { // if user specifies dirsync search preference and search is executed if (directorySynchronizationSpecified && searchResult != null) { _sync.ResetDirectorySynchronizationCookie(searchResult.DirsyncCookie); } return _sync; } set { // specify non-zero pagesize explicitly and also want dirsync if (value != null) { if (PageSize != 0) throw new ArgumentException(SR.DSBadPageSizeDirsync); directorySynchronizationSpecified = true; } else // user explicitly sets the value to default one and doesn't want to do dirsync { directorySynchronizationSpecified = false; } _sync = value; } } /// <devdoc> /// Gets or sets a value to indicate the search should use the LDAP virtual list view (VLV) /// control. /// </devdoc> [DefaultValue(null)] public DirectoryVirtualListView VirtualListView { get { // if user specifies dirsync search preference and search is executed if (directoryVirtualListViewSpecified && searchResult != null) { DirectoryVirtualListView tempval = searchResult.VLVResponse; _vlv.Offset = tempval.Offset; _vlv.ApproximateTotal = tempval.ApproximateTotal; _vlv.DirectoryVirtualListViewContext = tempval.DirectoryVirtualListViewContext; if (_vlv.ApproximateTotal != 0) _vlv.TargetPercentage = (int)((double)_vlv.Offset / _vlv.ApproximateTotal * 100); else _vlv.TargetPercentage = 0; } return _vlv; } set { // if user explicitly set CacheResults to true and also want to set VLV if (value != null) { if (_cacheResultsSpecified == true && CacheResults == true) throw new ArgumentException(SR.DSBadCacheResultsVLV); directoryVirtualListViewSpecified = true; // if user does not explicit specify cache results to true and also do vlv, then cache results is default to false _cacheResults = false; } else // user explicitly sets the value to default one and doesn't want to do vlv { directoryVirtualListViewSpecified = false; } _vlv = value; } } /// <devdoc> /// Executes the search and returns only the first entry that is found. /// </devdoc> public SearchResult FindOne() { DirectorySynchronization tempsync = null; DirectoryVirtualListView tempvlv = null; SearchResult resultEntry = null; SearchResultCollection results = FindAll(false); try { foreach (SearchResult entry in results) { // need to get the dirsync cookie if (directorySynchronizationSpecified) tempsync = DirectorySynchronization; // need to get the vlv response if (directoryVirtualListViewSpecified) tempvlv = VirtualListView; resultEntry = entry; break; } } finally { searchResult = null; // still need to properly release the resource results.Dispose(); } return resultEntry; } /// <devdoc> /// Executes the search and returns a collection of the entries that are found. /// </devdoc> public SearchResultCollection FindAll() => FindAll(true); private SearchResultCollection FindAll(bool findMoreThanOne) { DirectoryEntry clonedRoot = SearchRoot.CloneBrowsable(); UnsafeNativeMethods.IAds adsObject = clonedRoot.AdsObject; if (!(adsObject is UnsafeNativeMethods.IDirectorySearch)) throw new NotSupportedException(SR.Format(SR.DSSearchUnsupported, SearchRoot.Path)); // this is a little bit hacky, but we need to perform a bind here, so we make sure the LDAP connection that we hold has more than // one reference count, one by SearchResultCollection object, one by DirectorySearcher object. In this way, when user calls // Dispose on SearchResultCollection, the connection is still there instead of reference count dropping to zero and being closed. // It is especially important for virtuallistview case, in order to reuse the vlv response, the search must be performed on the same ldap connection // only do it when vlv is used if (directoryVirtualListViewSpecified) { SearchRoot.Bind(true); } UnsafeNativeMethods.IDirectorySearch adsSearch = (UnsafeNativeMethods.IDirectorySearch)adsObject; SetSearchPreferences(adsSearch, findMoreThanOne); string[] properties = null; if (PropertiesToLoad.Count > 0) { if (!PropertiesToLoad.Contains("ADsPath")) { // if we don't get this property, we won't be able to return a list of DirectoryEntry objects! PropertiesToLoad.Add("ADsPath"); } properties = new string[PropertiesToLoad.Count]; PropertiesToLoad.CopyTo(properties, 0); } IntPtr resultsHandle; if (properties != null) { adsSearch.ExecuteSearch(Filter, properties, properties.Length, out resultsHandle); } else { adsSearch.ExecuteSearch(Filter, null, -1, out resultsHandle); properties = Array.Empty<string>(); } return new SearchResultCollection(clonedRoot, resultsHandle, properties, this); } private unsafe void SetSearchPreferences(UnsafeNativeMethods.IDirectorySearch adsSearch, bool findMoreThanOne) { ArrayList prefList = new ArrayList(); AdsSearchPreferenceInfo info; // search scope info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.SEARCH_SCOPE; info.vValue = new AdsValueHelper((int)SearchScope).GetStruct(); prefList.Add(info); // size limit if (_sizeLimit != 0 || !findMoreThanOne) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.SIZE_LIMIT; info.vValue = new AdsValueHelper(findMoreThanOne ? SizeLimit : 1).GetStruct(); prefList.Add(info); } // time limit if (ServerTimeLimit >= new TimeSpan(0)) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.TIME_LIMIT; info.vValue = new AdsValueHelper((int)ServerTimeLimit.TotalSeconds).GetStruct(); prefList.Add(info); } // propertyNamesOnly info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.ATTRIBTYPES_ONLY; info.vValue = new AdsValueHelper(PropertyNamesOnly).GetStruct(); prefList.Add(info); // Timeout if (ClientTimeout >= new TimeSpan(0)) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.TIMEOUT; info.vValue = new AdsValueHelper((int)ClientTimeout.TotalSeconds).GetStruct(); prefList.Add(info); } // page size if (PageSize != 0) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.PAGESIZE; info.vValue = new AdsValueHelper(PageSize).GetStruct(); prefList.Add(info); } // page time limit if (ServerPageTimeLimit >= new TimeSpan(0)) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.PAGED_TIME_LIMIT; info.vValue = new AdsValueHelper((int)ServerPageTimeLimit.TotalSeconds).GetStruct(); prefList.Add(info); } // chase referrals info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.CHASE_REFERRALS; info.vValue = new AdsValueHelper((int)ReferralChasing).GetStruct(); prefList.Add(info); // asynchronous if (Asynchronous == true) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.ASYNCHRONOUS; info.vValue = new AdsValueHelper(Asynchronous).GetStruct(); prefList.Add(info); } // tombstone if (Tombstone == true) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.TOMBSTONE; info.vValue = new AdsValueHelper(Tombstone).GetStruct(); prefList.Add(info); } // attributescopequery if (_attributeScopeQuerySpecified) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.ATTRIBUTE_QUERY; info.vValue = new AdsValueHelper(AttributeScopeQuery, AdsType.ADSTYPE_CASE_IGNORE_STRING).GetStruct(); prefList.Add(info); } // derefalias if (DerefAlias != DereferenceAlias.Never) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.DEREF_ALIASES; info.vValue = new AdsValueHelper((int)DerefAlias).GetStruct(); prefList.Add(info); } // securitymask if (SecurityMasks != SecurityMasks.None) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.SECURITY_MASK; info.vValue = new AdsValueHelper((int)SecurityMasks).GetStruct(); prefList.Add(info); } // extendeddn if (ExtendedDN != ExtendedDN.None) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.EXTENDED_DN; info.vValue = new AdsValueHelper((int)ExtendedDN).GetStruct(); prefList.Add(info); } // dirsync if (directorySynchronizationSpecified) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.DIRSYNC; info.vValue = new AdsValueHelper(DirectorySynchronization.GetDirectorySynchronizationCookie(), AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct(); prefList.Add(info); if (DirectorySynchronization.Option != DirectorySynchronizationOptions.None) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.DIRSYNC_FLAG; info.vValue = new AdsValueHelper((int)DirectorySynchronization.Option).GetStruct(); prefList.Add(info); } } IntPtr ptrToFree = (IntPtr)0; IntPtr ptrVLVToFree = (IntPtr)0; IntPtr ptrVLVContexToFree = (IntPtr)0; try { // sort if (Sort.PropertyName != null && Sort.PropertyName.Length > 0) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.SORT_ON; AdsSortKey sortKey = new AdsSortKey(); sortKey.pszAttrType = Marshal.StringToCoTaskMemUni(Sort.PropertyName); ptrToFree = sortKey.pszAttrType; // so we can free it later. sortKey.pszReserved = (IntPtr)0; sortKey.fReverseOrder = (Sort.Direction == SortDirection.Descending) ? -1 : 0; byte[] sortKeyBytes = new byte[Marshal.SizeOf(sortKey)]; Marshal.Copy((INTPTR_INTPTRCAST)(&sortKey), sortKeyBytes, 0, sortKeyBytes.Length); info.vValue = new AdsValueHelper(sortKeyBytes, AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct(); prefList.Add(info); } // vlv if (directoryVirtualListViewSpecified) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.VLV; AdsVLV vlvValue = new AdsVLV(); vlvValue.beforeCount = _vlv.BeforeCount; vlvValue.afterCount = _vlv.AfterCount; vlvValue.offset = _vlv.Offset; //we need to treat the empty string as null here if (_vlv.Target.Length != 0) vlvValue.target = Marshal.StringToCoTaskMemUni(_vlv.Target); else vlvValue.target = IntPtr.Zero; ptrVLVToFree = vlvValue.target; if (_vlv.DirectoryVirtualListViewContext == null) { vlvValue.contextIDlength = 0; vlvValue.contextID = (IntPtr)0; } else { vlvValue.contextIDlength = _vlv.DirectoryVirtualListViewContext._context.Length; vlvValue.contextID = Marshal.AllocCoTaskMem(vlvValue.contextIDlength); ptrVLVContexToFree = vlvValue.contextID; Marshal.Copy(_vlv.DirectoryVirtualListViewContext._context, 0, vlvValue.contextID, vlvValue.contextIDlength); } IntPtr vlvPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(AdsVLV))); byte[] vlvBytes = new byte[Marshal.SizeOf(vlvValue)]; try { Marshal.StructureToPtr(vlvValue, vlvPtr, false); Marshal.Copy(vlvPtr, vlvBytes, 0, vlvBytes.Length); } finally { Marshal.FreeHGlobal(vlvPtr); } info.vValue = new AdsValueHelper(vlvBytes, AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct(); prefList.Add(info); } // cacheResults if (_cacheResultsSpecified) { info = new AdsSearchPreferenceInfo(); info.dwSearchPref = (int)AdsSearchPreferences.CACHE_RESULTS; info.vValue = new AdsValueHelper(CacheResults).GetStruct(); prefList.Add(info); } // // now make the call // AdsSearchPreferenceInfo[] prefs = new AdsSearchPreferenceInfo[prefList.Count]; for (int i = 0; i < prefList.Count; i++) { prefs[i] = (AdsSearchPreferenceInfo)prefList[i]; } DoSetSearchPrefs(adsSearch, prefs); } finally { if (ptrToFree != (IntPtr)0) Marshal.FreeCoTaskMem(ptrToFree); if (ptrVLVToFree != (IntPtr)0) Marshal.FreeCoTaskMem(ptrVLVToFree); if (ptrVLVContexToFree != (IntPtr)0) Marshal.FreeCoTaskMem(ptrVLVContexToFree); } } private static void DoSetSearchPrefs(UnsafeNativeMethods.IDirectorySearch adsSearch, AdsSearchPreferenceInfo[] prefs) { int structSize = Marshal.SizeOf(typeof(AdsSearchPreferenceInfo)); IntPtr ptr = Marshal.AllocHGlobal((IntPtr)(structSize * prefs.Length)); try { IntPtr tempPtr = ptr; for (int i = 0; i < prefs.Length; i++) { Marshal.StructureToPtr(prefs[i], tempPtr, false); tempPtr = IntPtr.Add(tempPtr, structSize); } adsSearch.SetSearchPreference(ptr, prefs.Length); // Check for the result status for all preferences tempPtr = ptr; for (int i = 0; i < prefs.Length; i++) { int status = Marshal.ReadInt32(tempPtr, 32); if (status != 0) { string property = prefs[i].dwSearchPref switch { (int)AdsSearchPreferences.SEARCH_SCOPE => "SearchScope", (int)AdsSearchPreferences.SIZE_LIMIT => "SizeLimit", (int)AdsSearchPreferences.TIME_LIMIT => "ServerTimeLimit", (int)AdsSearchPreferences.ATTRIBTYPES_ONLY => "PropertyNamesOnly", (int)AdsSearchPreferences.TIMEOUT => "ClientTimeout", (int)AdsSearchPreferences.PAGESIZE => "PageSize", (int)AdsSearchPreferences.PAGED_TIME_LIMIT => "ServerPageTimeLimit", (int)AdsSearchPreferences.CHASE_REFERRALS => "ReferralChasing", (int)AdsSearchPreferences.SORT_ON => "Sort", (int)AdsSearchPreferences.CACHE_RESULTS => "CacheResults", (int)AdsSearchPreferences.ASYNCHRONOUS => "Asynchronous", (int)AdsSearchPreferences.TOMBSTONE => "Tombstone", (int)AdsSearchPreferences.ATTRIBUTE_QUERY => "AttributeScopeQuery", (int)AdsSearchPreferences.DEREF_ALIASES => "DerefAlias", (int)AdsSearchPreferences.SECURITY_MASK => "SecurityMasks", (int)AdsSearchPreferences.EXTENDED_DN => "ExtendedDn", (int)AdsSearchPreferences.DIRSYNC => "DirectorySynchronization", (int)AdsSearchPreferences.DIRSYNC_FLAG => "DirectorySynchronizationFlag", (int)AdsSearchPreferences.VLV => "VirtualListView", _ => "", }; throw new InvalidOperationException(SR.Format(SR.DSSearchPreferencesNotAccepted, property)); } tempPtr = IntPtr.Add(tempPtr, structSize); } } finally { Marshal.FreeHGlobal(ptr); } } } }
// 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.Net.Http.Headers; using Xunit; namespace System.Net.Http.Tests { public class ContentRangeHeaderValueTest { [Fact] public void Ctor_LengthOnlyOverloadUseInvalidValues_Throw() { Assert.Throws<ArgumentOutOfRangeException>(() => { ContentRangeHeaderValue v = new ContentRangeHeaderValue(-1); }); } [Fact] public void Ctor_LengthOnlyOverloadValidValues_ValuesCorrectlySet() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(5); Assert.False(range.HasRange); Assert.True(range.HasLength); Assert.Equal("bytes", range.Unit); Assert.Null(range.From); Assert.Null(range.To); Assert.Equal(5, range.Length); } [Fact] public void Ctor_FromAndToOverloadUseInvalidValues_Throw() { Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(-1, 1); }); // "Negative 'from'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(0, -1); }); // "Negative 'to'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(2, 1); }); // "'from' > 'to'" } [Fact] public void Ctor_FromAndToOverloadValidValues_ValuesCorrectlySet() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(0, 1); Assert.True(range.HasRange); Assert.False(range.HasLength); Assert.Equal("bytes", range.Unit); Assert.Equal(0, range.From); Assert.Equal(1, range.To); Assert.Null(range.Length); } [Fact] public void Ctor_FromToAndLengthOverloadUseInvalidValues_Throw() { Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(-1, 1, 2); }); // "Negative 'from'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(0, -1, 2); }); // "Negative 'to'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(0, 1, -1); }); // "Negative 'length'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(2, 1, 3); }); // "'from' > 'to'" Assert.Throws<ArgumentOutOfRangeException>(() => { new ContentRangeHeaderValue(1, 2, 1); }); // "'to' > 'length'" } [Fact] public void Ctor_FromToAndLengthOverloadValidValues_ValuesCorrectlySet() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(0, 1, 2); Assert.True(range.HasRange); Assert.True(range.HasLength); Assert.Equal("bytes", range.Unit); Assert.Equal(0, range.From); Assert.Equal(1, range.To); Assert.Equal(2, range.Length); } [Fact] public void Unit_GetAndSetValidAndInvalidValues_MatchExpectation() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(0); range.Unit = "myunit"; Assert.Equal("myunit", range.Unit); // "Unit (custom value)" Assert.Throws<ArgumentException>(() => { range.Unit = null; }); // "<null>" Assert.Throws<ArgumentException>(() => { range.Unit = ""; }); // "empty string" Assert.Throws<FormatException>(() => { range.Unit = " x"; }); // "leading space" Assert.Throws<FormatException>(() => { range.Unit = "x "; }); // "trailing space" Assert.Throws<FormatException>(() => { range.Unit = "x y"; }); // "invalid token" } [Fact] public void ToString_UseDifferentRanges_AllSerializedCorrectly() { ContentRangeHeaderValue range = new ContentRangeHeaderValue(1, 2, 3); range.Unit = "myunit"; Assert.Equal("myunit 1-2/3", range.ToString()); // "Range with all fields set" range = new ContentRangeHeaderValue(123456789012345678, 123456789012345679); Assert.Equal("bytes 123456789012345678-123456789012345679/*", range.ToString()); // "Only range, no length" range = new ContentRangeHeaderValue(150); Assert.Equal("bytes */150", range.ToString()); // "Only length, no range" } [Fact] public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes() { ContentRangeHeaderValue range1 = new ContentRangeHeaderValue(1, 2, 5); ContentRangeHeaderValue range2 = new ContentRangeHeaderValue(1, 2); ContentRangeHeaderValue range3 = new ContentRangeHeaderValue(5); ContentRangeHeaderValue range4 = new ContentRangeHeaderValue(1, 2, 5); range4.Unit = "BYTES"; ContentRangeHeaderValue range5 = new ContentRangeHeaderValue(1, 2, 5); range5.Unit = "myunit"; Assert.NotEqual(range1.GetHashCode(), range2.GetHashCode()); // "bytes 1-2/5 vs. bytes 1-2/*" Assert.NotEqual(range1.GetHashCode(), range3.GetHashCode()); // "bytes 1-2/5 vs. bytes */5" Assert.NotEqual(range2.GetHashCode(), range3.GetHashCode()); // "bytes 1-2/* vs. bytes */5" Assert.Equal(range1.GetHashCode(), range4.GetHashCode()); // "bytes 1-2/5 vs. BYTES 1-2/5" Assert.NotEqual(range1.GetHashCode(), range5.GetHashCode()); // "bytes 1-2/5 vs. myunit 1-2/5" } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { ContentRangeHeaderValue range1 = new ContentRangeHeaderValue(1, 2, 5); ContentRangeHeaderValue range2 = new ContentRangeHeaderValue(1, 2); ContentRangeHeaderValue range3 = new ContentRangeHeaderValue(5); ContentRangeHeaderValue range4 = new ContentRangeHeaderValue(1, 2, 5); range4.Unit = "BYTES"; ContentRangeHeaderValue range5 = new ContentRangeHeaderValue(1, 2, 5); range5.Unit = "myunit"; ContentRangeHeaderValue range6 = new ContentRangeHeaderValue(1, 3, 5); ContentRangeHeaderValue range7 = new ContentRangeHeaderValue(2, 2, 5); ContentRangeHeaderValue range8 = new ContentRangeHeaderValue(1, 2, 6); Assert.False(range1.Equals(null)); // "bytes 1-2/5 vs. <null>" Assert.False(range1.Equals(range2)); // "bytes 1-2/5 vs. bytes 1-2/*" Assert.False(range1.Equals(range3)); // "bytes 1-2/5 vs. bytes */5" Assert.False(range2.Equals(range3)); // "bytes 1-2/* vs. bytes */5" Assert.True(range1.Equals(range4)); // "bytes 1-2/5 vs. BYTES 1-2/5" Assert.True(range4.Equals(range1)); // "BYTES 1-2/5 vs. bytes 1-2/5" Assert.False(range1.Equals(range5)); // "bytes 1-2/5 vs. myunit 1-2/5" Assert.False(range1.Equals(range6)); // "bytes 1-2/5 vs. bytes 1-3/5" Assert.False(range1.Equals(range7)); // "bytes 1-2/5 vs. bytes 2-2/5" Assert.False(range1.Equals(range8)); // "bytes 1-2/5 vs. bytes 1-2/6" } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { ContentRangeHeaderValue source = new ContentRangeHeaderValue(1, 2, 5); source.Unit = "custom"; ContentRangeHeaderValue clone = (ContentRangeHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Unit, clone.Unit); Assert.Equal(source.From, clone.From); Assert.Equal(source.To, clone.To); Assert.Equal(source.Length, clone.Length); } [Fact] public void GetContentRangeLength_DifferentValidScenarios_AllReturnNonZero() { ContentRangeHeaderValue result = null; CallGetContentRangeLength("bytes 1-2/3", 0, 11, out result); Assert.Equal("bytes", result.Unit); Assert.Equal(1, result.From); Assert.Equal(2, result.To); Assert.Equal(3, result.Length); Assert.True(result.HasRange); Assert.True(result.HasLength); CallGetContentRangeLength(" custom 1234567890123456789-1234567890123456799/*", 1, 48, out result); Assert.Equal("custom", result.Unit); Assert.Equal(1234567890123456789, result.From); Assert.Equal(1234567890123456799, result.To); Assert.Null(result.Length); Assert.True(result.HasRange); Assert.False(result.HasLength); // Note that the final space should be skipped by GetContentRangeLength() and be considered by the returned // value. CallGetContentRangeLength(" custom * / 123 ", 1, 15, out result); Assert.Equal("custom", result.Unit); Assert.Null(result.From); Assert.Null(result.To); Assert.Equal(123, result.Length); Assert.False(result.HasRange); Assert.True(result.HasLength); // Note that we don't have a public constructor for value 'bytes */*' since the RFC doesn't mention a // scenario for it. However, if a server returns this value, we're flexible and accept it. CallGetContentRangeLength("bytes */*", 0, 9, out result); Assert.Equal("bytes", result.Unit); Assert.Null(result.From); Assert.Null(result.To); Assert.Null(result.Length); Assert.False(result.HasRange); Assert.False(result.HasLength); } [Fact] public void GetContentRangeLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetContentRangeLength(" bytes 1-2/3", 0); CheckInvalidGetContentRangeLength("bytes 3-2/5", 0); CheckInvalidGetContentRangeLength("bytes 6-6/5", 0); CheckInvalidGetContentRangeLength("bytes 1-6/5", 0); CheckInvalidGetContentRangeLength("bytes 1-2/", 0); CheckInvalidGetContentRangeLength("bytes 1-2", 0); CheckInvalidGetContentRangeLength("bytes 1-/", 0); CheckInvalidGetContentRangeLength("bytes 1-", 0); CheckInvalidGetContentRangeLength("bytes 1", 0); CheckInvalidGetContentRangeLength("bytes ", 0); CheckInvalidGetContentRangeLength("bytes a-2/3", 0); CheckInvalidGetContentRangeLength("bytes 1-b/3", 0); CheckInvalidGetContentRangeLength("bytes 1-2/c", 0); CheckInvalidGetContentRangeLength("bytes1-2/3", 0); // More than 19 digits >>Int64.MaxValue CheckInvalidGetContentRangeLength("bytes 1-12345678901234567890/3", 0); CheckInvalidGetContentRangeLength("bytes 12345678901234567890-3/3", 0); CheckInvalidGetContentRangeLength("bytes 1-2/12345678901234567890", 0); // Exceed Int64.MaxValue, but use 19 digits CheckInvalidGetContentRangeLength("bytes 1-9999999999999999999/3", 0); CheckInvalidGetContentRangeLength("bytes 9999999999999999999-3/3", 0); CheckInvalidGetContentRangeLength("bytes 1-2/9999999999999999999", 0); CheckInvalidGetContentRangeLength(string.Empty, 0); CheckInvalidGetContentRangeLength(null, 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { // Only verify parser functionality (i.e. ContentRangeHeaderParser.TryParse()). We don't need to validate // all possible range values (verification done by tests for ContentRangeHeaderValue.GetContentRangeLength()). CheckValidParse(" bytes 1-2/3 ", new ContentRangeHeaderValue(1, 2, 3)); CheckValidParse("bytes * / 3", new ContentRangeHeaderValue(3)); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("bytes 1-2/3,"); // no character after 'length' allowed CheckInvalidParse("x bytes 1-2/3"); CheckInvalidParse("bytes 1-2/3.4"); CheckInvalidParse(null); CheckInvalidParse(string.Empty); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { // Only verify parser functionality (i.e. ContentRangeHeaderParser.TryParse()). We don't need to validate // all possible range values (verification done by tests for ContentRangeHeaderValue.GetContentRangeLength()). CheckValidTryParse(" bytes 1-2/3 ", new ContentRangeHeaderValue(1, 2, 3)); CheckValidTryParse("bytes * / 3", new ContentRangeHeaderValue(3)); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("bytes 1-2/3,"); // no character after 'length' allowed CheckInvalidTryParse("x bytes 1-2/3"); CheckInvalidTryParse("bytes 1-2/3.4"); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); } #region Helper methods private void CheckValidParse(string input, ContentRangeHeaderValue expectedResult) { ContentRangeHeaderValue result = ContentRangeHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { ContentRangeHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, ContentRangeHeaderValue expectedResult) { ContentRangeHeaderValue result = null; Assert.True(ContentRangeHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { ContentRangeHeaderValue result = null; Assert.False(ContentRangeHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CallGetContentRangeLength(string input, int startIndex, int expectedLength, out ContentRangeHeaderValue result) { object temp = null; Assert.Equal(expectedLength, ContentRangeHeaderValue.GetContentRangeLength(input, startIndex, out temp)); result = temp as ContentRangeHeaderValue; } private static void CheckInvalidGetContentRangeLength(string input, int startIndex) { object result = null; Assert.Equal(0, ContentRangeHeaderValue.GetContentRangeLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.LeaseProviders; using Orleans.Runtime; using Orleans.Configuration; using Orleans.Timers; namespace Orleans.Streams { /// <summary> /// IResourceSelector selects a certain amount of resource from a resource list /// </summary> /// <typeparam name="T"></typeparam> internal interface IResourceSelector<T> { /// <summary> /// Try to select certain count of resources from resource list, which doesn't overlap with existing selection /// </summary> /// <param name="newSelectionCount"></param> /// <param name="existingSelection"></param> /// <returns></returns> List<T> NextSelection(int newSelectionCount, List<T> existingSelection); } /// <summary> /// Selector using round robin algorithm /// </summary> /// <typeparam name="T"></typeparam> internal class RoundRobinSelector<T> : IResourceSelector<T> { private ReadOnlyCollection<T> resources; private int lastSelection; public RoundRobinSelector(IEnumerable<T> resources) { this.resources = new ReadOnlyCollection<T>(resources.Distinct().ToList()); this.lastSelection = new Random().Next(this.resources.Count); } /// <summary> /// Try to select certain count of resources from resource list, which doesn't overlap with existing resources /// </summary> /// <param name="newSelectionCount"></param> /// <param name="existingSelection"></param> /// <returns></returns> public List<T> NextSelection(int newSelectionCount, List<T> existingSelection) { var selection = new List<T>(Math.Min(newSelectionCount, this.resources.Count)); int tries = 0; while (selection.Count < newSelectionCount && tries++ < this.resources.Count) { this.lastSelection = (++this.lastSelection) % (this.resources.Count); if(!existingSelection.Contains(this.resources[this.lastSelection])) selection.Add(this.resources[this.lastSelection]); } return selection; } } /// <summary> /// LeaseBasedQueueBalancer. This balancer supports queue balancing in cluster auto-scale scenario, unexpected server failure scenario, and try to support ideal distribution /// as much as possible. /// </summary> public class LeaseBasedQueueBalancer : QueueBalancerBase, IStreamQueueBalancer, IDisposable { /// <summary> /// Lease category for LeaseBasedQueueBalancer /// </summary> public const string LeaseCategory = "QueueBalancer"; private class AcquiredQueue { public QueueId QueueId { get; set; } public AcquiredLease AcquiredLease { get; set; } public AcquiredQueue(QueueId queueId, AcquiredLease lease) { this.QueueId = queueId; this.AcquiredLease = lease; } } private ILeaseProvider leaseProvider; private IDeploymentConfiguration deploymentConfig; private readonly ISiloStatusOracle siloStatusOracle; private ReadOnlyCollection<QueueId> allQueues; private List<AcquiredQueue> myQueues; private bool isStarting; private IDisposable renewLeaseTimer; private IDisposable tryAcquireMaximumLeaseTimer; private IResourceSelector<QueueId> queueSelector; private int minimumResponsibility; private int maximumResponsibility; private IServiceProvider serviceProvider; private ILogger logger; private ILoggerFactory loggerFactory; private readonly LeaseBasedQueueBalancerOptions options; /// <summary> /// Constructor /// </summary> public LeaseBasedQueueBalancer(string name, LeaseBasedQueueBalancerOptions options, IServiceProvider serviceProvider, ISiloStatusOracle siloStatusOracle, IDeploymentConfiguration deploymentConfig, ILoggerFactory loggerFactory) { this.serviceProvider = serviceProvider; this.deploymentConfig = deploymentConfig; this.siloStatusOracle = siloStatusOracle; this.myQueues = new List<AcquiredQueue>(); this.isStarting = true; this.loggerFactory = loggerFactory; this.options = options; this.logger = loggerFactory.CreateLogger($"{typeof(LeaseBasedQueueBalancer).FullName}-{name}"); } public static IStreamQueueBalancer Create(IServiceProvider services, string name, IDeploymentConfiguration deploymentConfiguration) { var options = services.GetRequiredService<IOptionsMonitor<LeaseBasedQueueBalancerOptions>>().Get(name); return ActivatorUtilities.CreateInstance<LeaseBasedQueueBalancer>(services, name, options, deploymentConfiguration); } /// <inheritdoc/> public override Task Initialize(IStreamQueueMapper queueMapper) { if (queueMapper == null) { throw new ArgumentNullException("queueMapper"); } this.allQueues = new ReadOnlyCollection<QueueId>(queueMapper.GetAllQueues().ToList()); if (this.allQueues.Count == 0) return Task.CompletedTask; this.leaseProvider = this.serviceProvider.GetRequiredService(options.LeaseProviderType) as ILeaseProvider; NotifyAfterStart().Ignore(); //make lease renew frequency to be every half of lease time, to avoid renew failing due to timing issues, race condition or clock difference. ITimerRegistry timerRegistry = this.serviceProvider.GetRequiredService<ITimerRegistry>(); this.renewLeaseTimer = timerRegistry.RegisterTimer(null, this.MaintainAndBalanceQueues, null, this.options.SiloMaturityPeriod, this.options.LeaseLength.Divide(2)); //try to acquire maximum leases every leaseLength this.tryAcquireMaximumLeaseTimer = timerRegistry.RegisterTimer(null, this.AcquireLeaseToMeetMaxResponsibility, null, this.options.SiloMaturityPeriod, this.options.SiloMaturityPeriod); //Selector default to round robin selector now, but we can make a further change to make selector configurable if needed. Selector algorithm could //be affecting queue balancing stablization time in cluster initializing and auto-scaling this.queueSelector = new RoundRobinSelector<QueueId>(this.allQueues); return MaintainAndBalanceQueues(null); } /// <inheritdoc/> public override IEnumerable<QueueId> GetMyQueues() { return this.myQueues.Select(queue => queue.QueueId); } private async Task MaintainAndBalanceQueues(object state) { CalculateResponsibility(); var oldQueues = new HashSet<QueueId>(this.myQueues.Select(queue => queue.QueueId)); // step 1: renew existing leases await this.RenewLeases(); // step 2: if after renewing leases, myQueues count doesn't fall in [minimumResponsibility, maximumResponsibility] range, act accordingly if (this.myQueues.Count < this.minimumResponsibility) { await this.AcquireLeasesToMeetMinResponsibility(); } else if (this.myQueues.Count > this.maximumResponsibility) { await this.ReleaseLeasesToMeetResponsibility(); } var newQueues = new HashSet<QueueId>(this.myQueues.Select(queue=> queue.QueueId)); //if queue changed, notify listeners if (!oldQueues.SetEquals(newQueues)) await NotifyListeners(); } private async Task ReleaseLeasesToMeetResponsibility() { var queueCountToRelease = this.myQueues.Count - this.maximumResponsibility; if (queueCountToRelease <= 0) return; var queuesToGiveUp = this.myQueues.GetRange(0, queueCountToRelease); await this.leaseProvider.Release(LeaseCategory, queuesToGiveUp.Select(queue => queue.AcquiredLease).ToArray()); //remove queuesToGiveUp from myQueue list after the balancer released the leases on them this.myQueues.RemoveRange(0, queueCountToRelease); this.logger.Info($"Released leases for {queueCountToRelease} queues"); this.logger.LogInformation($"I now own leases for {this.myQueues.Count} of an expected {this.minimumResponsibility} to {this.maximumResponsibility} queues."); } private Task AcquireLeaseToMeetMaxResponsibility(object state) { return AcquireLeasesToMeetExpectation(this.maximumResponsibility); } private Task AcquireLeasesToMeetMinResponsibility() { return AcquireLeasesToMeetExpectation(this.minimumResponsibility); } private async Task AcquireLeasesToMeetExpectation(int expectedTotalLeaseCount) { int maxAttempts = 5; int attempts = 0; int leasesToAquire = expectedTotalLeaseCount - this.myQueues.Count; if (leasesToAquire <= 0) return; while (attempts ++ < maxAttempts && leasesToAquire > 0) { this.logger.LogDebug($"I have {this.myQueues.Count} queues. Trying to acquire {leasesToAquire} queues to reach {expectedTotalLeaseCount}"); leasesToAquire = expectedTotalLeaseCount - this.myQueues.Count; //select new queues to acquire List<QueueId> expectedQueues = this.queueSelector.NextSelection(leasesToAquire, this.myQueues.Select(queue=>queue.QueueId).ToList()).ToList(); IEnumerable<LeaseRequest> leaseRequests = expectedQueues.Select(queue => new LeaseRequest() { ResourceKey = queue.ToString(), Duration = this.options.LeaseLength }); AcquireLeaseResult[] results = await this.leaseProvider.Acquire(LeaseCategory, leaseRequests.ToArray()); //add successfully acquired queue to myQueues list for (int i = 0; i < results.Length; i++) { if (results[i].StatusCode == ResponseCode.OK) { this.myQueues.Add(new AcquiredQueue(expectedQueues[i], results[i].AcquiredLease)); } } //if reached expectedTotalLeaseCount if (this.myQueues.Count >= expectedTotalLeaseCount) { break; } } this.logger.LogInformation($"I now own leases for {this.myQueues.Count} of an expected {this.minimumResponsibility} to {this.maximumResponsibility} queues"); } private async Task RenewLeases() { if (this.myQueues.Count <= 0) return; var results = await this.leaseProvider.Renew(LeaseCategory, this.myQueues.Select(queue => queue.AcquiredLease).ToArray()); var updatedQueues = new List<AcquiredQueue>(); //update myQueues list with successfully renewed leases for (int i = 0; i < results.Count(); i++) { var result = results[i]; if (result.StatusCode == ResponseCode.OK) { updatedQueues.Add(new AcquiredQueue(this.myQueues[i].QueueId, result.AcquiredLease)); } } this.myQueues.Clear(); this.myQueues = updatedQueues; this.logger.LogInformation($"Renewed leases for {this.myQueues.Count} queues."); } private void CalculateResponsibility() { int activeBuckets = 0; if (isStarting) { activeBuckets = this.deploymentConfig.GetAllSiloNames().Count; } else { activeBuckets = GetActiveSiloCount(this.siloStatusOracle); } activeBuckets = Math.Max(1, activeBuckets); this.minimumResponsibility = this.allQueues.Count / activeBuckets; //if allQueues count is divisible by active bukets, then every bucket should take the same count of queues, otherwise, there should be one bucket take 1 more queue if (this.allQueues.Count % activeBuckets == 0) this.maximumResponsibility = this.minimumResponsibility; else this.maximumResponsibility = this.minimumResponsibility + 1; } private static int GetActiveSiloCount(ISiloStatusOracle siloStatusOracle) { return siloStatusOracle.GetApproximateSiloStatuses(true).Count; } private async Task NotifyAfterStart() { await Task.Delay(this.options.SiloMaturityPeriod); this.isStarting = false; await NotifyListeners(); } private Task NotifyListeners() { List<IStreamQueueBalanceListener> queueBalanceListenersCopy; lock (queueBalanceListeners) { queueBalanceListenersCopy = queueBalanceListeners.ToList(); // make copy } var notificatioTasks = new List<Task>(queueBalanceListenersCopy.Count); foreach (IStreamQueueBalanceListener listener in queueBalanceListenersCopy) { notificatioTasks.Add(listener.QueueDistributionChangeNotification()); } return Task.WhenAll(notificatioTasks); } /// <inheritdoc/> public void Dispose() { this.renewLeaseTimer?.Dispose(); this.renewLeaseTimer = null; this.tryAcquireMaximumLeaseTimer?.Dispose(); this.tryAcquireMaximumLeaseTimer = null; //release all owned leases this.maximumResponsibility = 0; this.minimumResponsibility = 0; this.ReleaseLeasesToMeetResponsibility().Ignore(); } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; namespace BooksOnline.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rc2-20901"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("WebApplication.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
using System; using System.Data; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Infrastructure.Persistence; using CoreDebugSettings = Umbraco.Cms.Core.Configuration.Models.CoreDebugSettings; using Umbraco.Extensions; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; #if DEBUG_SCOPES using System.Linq; using System.Text; #endif namespace Umbraco.Cms.Core.Scoping { /// <summary> /// Implements <see cref="IScopeProvider"/>. /// </summary> internal class ScopeProvider : IScopeProvider, IScopeAccessor { private readonly ILogger<ScopeProvider> _logger; private readonly ILoggerFactory _loggerFactory; private readonly IRequestCache _requestCache; private readonly FileSystems _fileSystems; private readonly CoreDebugSettings _coreDebugSettings; private readonly MediaFileManager _mediaFileManager; private static readonly AsyncLocal<ConcurrentStack<IScope>> s_scopeStack = new AsyncLocal<ConcurrentStack<IScope>>(); private static readonly AsyncLocal<ConcurrentStack<IScopeContext>> s_scopeContextStack = new AsyncLocal<ConcurrentStack<IScopeContext>>(); private static readonly string s_scopeItemKey = typeof(Scope).FullName; private static readonly string s_contextItemKey = typeof(ScopeProvider).FullName; private readonly IEventAggregator _eventAggregator; public ScopeProvider(IUmbracoDatabaseFactory databaseFactory, FileSystems fileSystems, IOptions<CoreDebugSettings> coreDebugSettings, MediaFileManager mediaFileManager, ILogger<ScopeProvider> logger, ILoggerFactory loggerFactory, IRequestCache requestCache, IEventAggregator eventAggregator) { DatabaseFactory = databaseFactory; _fileSystems = fileSystems; _coreDebugSettings = coreDebugSettings.Value; _mediaFileManager = mediaFileManager; _logger = logger; _loggerFactory = loggerFactory; _requestCache = requestCache; _eventAggregator = eventAggregator; // take control of the FileSystems _fileSystems.IsScoped = () => AmbientScope != null && AmbientScope.ScopedFileSystems; } public IUmbracoDatabaseFactory DatabaseFactory { get; } public ISqlContext SqlContext => DatabaseFactory.SqlContext; #region Context private void MoveHttpContextScopeToCallContext() { var source = (ConcurrentStack<IScope>)_requestCache.Get(s_scopeItemKey); ConcurrentStack<IScope> stack = s_scopeStack.Value; MoveContexts(s_scopeItemKey, source, stack, (_, v) => s_scopeStack.Value = v); } private void MoveHttpContextScopeContextToCallContext() { var source = (ConcurrentStack<IScopeContext>)_requestCache.Get(s_contextItemKey); ConcurrentStack<IScopeContext> stack = s_scopeContextStack.Value; MoveContexts(s_contextItemKey, source, stack, (_, v) => s_scopeContextStack.Value = v); } private void MoveCallContextScopeToHttpContext() { ConcurrentStack<IScope> source = s_scopeStack.Value; var stack = (ConcurrentStack<IScope>)_requestCache.Get(s_scopeItemKey); MoveContexts(s_scopeItemKey, source, stack, (k, v) => _requestCache.Set(k, v)); } private void MoveCallContextScopeContextToHttpContext() { ConcurrentStack<IScopeContext> source = s_scopeContextStack.Value; var stack = (ConcurrentStack<IScopeContext>)_requestCache.Get(s_contextItemKey); MoveContexts(s_contextItemKey, source, stack, (k, v) => _requestCache.Set(k, v)); } private void MoveContexts<T>(string key, ConcurrentStack<T> source, ConcurrentStack<T> stack, Action<string, ConcurrentStack<T>> setter) where T : class, IInstanceIdentifiable { if (source == null) { return; } if (stack != null) { stack.Clear(); } else { // TODO: This isn't going to copy it back up the execution context chain stack = new ConcurrentStack<T>(); setter(key, stack); } var arr = new T[source.Count]; source.CopyTo(arr, 0); Array.Reverse(arr); foreach (T a in arr) { stack.Push(a); } source.Clear(); } private void SetCallContextScope(IScope value) { ConcurrentStack<IScope> stack = s_scopeStack.Value; #if DEBUG_SCOPES // first, null-register the existing value if (stack != null && stack.TryPeek(out IScope ambientScope)) { RegisterContext(ambientScope, null); } // then register the new value if (value != null) { RegisterContext(value, "call"); } #endif if (value == null) { if (stack != null) { stack.TryPop(out _); } } else { #if DEBUG_SCOPES _logger.LogDebug("AddObject " + value.InstanceId.ToString("N").Substring(0, 8)); #endif if (stack == null) { stack = new ConcurrentStack<IScope>(); } stack.Push(value); s_scopeStack.Value = stack; } } private void SetCallContextScopeContext(IScopeContext value) { ConcurrentStack<IScopeContext> stack = s_scopeContextStack.Value; if (value == null) { if (stack != null) { stack.TryPop(out _); } } else { if (stack == null) { stack = new ConcurrentStack<IScopeContext>(); } stack.Push(value); s_scopeContextStack.Value = stack; } } private T GetHttpContextObject<T>(string key, bool required = true) where T : class { if (!_requestCache.IsAvailable && required) { throw new Exception("Request cache is unavailable."); } var stack = (ConcurrentStack<T>)_requestCache.Get(key); return stack != null && stack.TryPeek(out T peek) ? peek : null; } private bool SetHttpContextObject<T>(string key, T value, bool required = true) { if (!_requestCache.IsAvailable) { if (required) { throw new Exception("Request cache is unavailable."); } return false; } #if DEBUG_SCOPES // manage the 'context' that contains the scope (null, "http" or "call") // only for scopes of course! if (key == s_scopeItemKey) { // first, null-register the existing value var ambientScope = (IScope)_requestCache.Get(s_scopeItemKey); if (ambientScope != null) { RegisterContext(ambientScope, null); } // then register the new value if (value is IScope scope) { RegisterContext(scope, "http"); } } #endif var stack = (ConcurrentStack<T>)_requestCache.Get(key); if (value == null) { if (stack != null) { stack.TryPop(out _); } } else { if (stack == null) { stack = new ConcurrentStack<T>(); } stack.Push(value); _requestCache.Set(key, stack); } return true; } #endregion #region Ambient Context /// <summary> /// Get the Ambient (Current) <see cref="IScopeContext"/> for the current execution context. /// </summary> /// <remarks> /// The current execution context may be request based (HttpContext) or on a background thread (AsyncLocal) /// </remarks> public IScopeContext AmbientContext { get { // try http context, fallback onto call context IScopeContext value = GetHttpContextObject<IScopeContext>(s_contextItemKey, false); if (value != null) { return value; } ConcurrentStack<IScopeContext> stack = s_scopeContextStack.Value; if (stack == null || !stack.TryPeek(out IScopeContext peek)) { return null; } return peek; } } #endregion #region Ambient Scope IScope IScopeAccessor.AmbientScope => AmbientScope; /// <summary> /// Get or set the Ambient (Current) <see cref="Scope"/> for the current execution context. /// </summary> /// <remarks> /// The current execution context may be request based (HttpContext) or on a background thread (AsyncLocal) /// </remarks> public Scope AmbientScope { get { // try http context, fallback onto call context IScope value = GetHttpContextObject<IScope>(s_scopeItemKey, false); if (value != null) { return (Scope)value; } ConcurrentStack<IScope> stack = s_scopeStack.Value; if (stack == null || !stack.TryPeek(out IScope peek)) { return null; } return (Scope)peek; } } public void PopAmbientScope(Scope scope) { // pop the stack from all contexts SetHttpContextObject<IScope>(s_scopeItemKey, null, false); SetCallContextScope(null); // We need to move the stack to a different context if the parent scope // is flagged with a different CallContext flag. This is required // if creating a child scope with callContext: true (thus forcing CallContext) // when there is actually a current HttpContext available. // It's weird but is required for Deploy somehow. bool parentScopeCallContext = (scope.ParentScope?.CallContext ?? false); if (scope.CallContext && !parentScopeCallContext) { MoveCallContextScopeToHttpContext(); MoveCallContextScopeContextToHttpContext(); } else if (!scope.CallContext && parentScopeCallContext) { MoveHttpContextScopeToCallContext(); MoveHttpContextScopeContextToCallContext(); } } #endregion public void PushAmbientScope(Scope scope) { if (scope is null) { throw new ArgumentNullException(nameof(scope)); } if (scope.CallContext != false || !SetHttpContextObject<IScope>(s_scopeItemKey, scope, false)) { // In this case, always ensure that the HttpContext items // is transfered to CallContext and then cleared since we // may be migrating context with the callContext = true flag. // This is a weird case when forcing callContext when HttpContext // is available. Required by Deploy. if (_requestCache.IsAvailable) { MoveHttpContextScopeToCallContext(); MoveHttpContextScopeContextToCallContext(); } SetCallContextScope(scope); } } public void PushAmbientScopeContext(IScopeContext scopeContext) { if (scopeContext is null) { throw new ArgumentNullException(nameof(scopeContext)); } SetHttpContextObject<IScopeContext>(s_contextItemKey, scopeContext, false); SetCallContextScopeContext(scopeContext); } public void PopAmbientScopeContext() { // pop stack from all contexts SetHttpContextObject<IScopeContext>(s_contextItemKey, null, false); SetCallContextScopeContext(null); } /// <inheritdoc /> public IScope CreateDetachedScope( IsolationLevel isolationLevel = IsolationLevel.Unspecified, RepositoryCacheMode repositoryCacheMode = RepositoryCacheMode.Unspecified, IEventDispatcher eventDispatcher = null, IScopedNotificationPublisher scopedNotificationPublisher = null, bool? scopeFileSystems = null) => new Scope(this, _coreDebugSettings, _mediaFileManager, _eventAggregator, _loggerFactory.CreateLogger<Scope>(), _fileSystems, true, null, isolationLevel, repositoryCacheMode, eventDispatcher, scopedNotificationPublisher, scopeFileSystems); /// <inheritdoc /> public void AttachScope(IScope other, bool callContext = false) { // IScopeProvider.AttachScope works with an IScope // but here we can only deal with our own Scope class if (other is not Scope otherScope) { throw new ArgumentException("Not a Scope instance."); } if (otherScope.Detachable == false) { throw new ArgumentException("Not a detachable scope."); } if (otherScope.Attached) { throw new InvalidOperationException("Already attached."); } otherScope.Attached = true; otherScope.OrigScope = AmbientScope; otherScope.OrigContext = AmbientContext; otherScope.CallContext = callContext; PushAmbientScopeContext(otherScope.Context); PushAmbientScope(otherScope); } /// <inheritdoc /> public IScope DetachScope() { Scope ambientScope = AmbientScope; if (ambientScope == null) { throw new InvalidOperationException("There is no ambient scope."); } if (ambientScope.Detachable == false) { throw new InvalidOperationException("Ambient scope is not detachable."); } PopAmbientScope(ambientScope); PopAmbientScopeContext(); Scope originalScope = AmbientScope; if (originalScope != ambientScope.OrigScope) { throw new InvalidOperationException($"The detatched scope ({ambientScope.GetDebugInfo()}) does not match the original ({originalScope.GetDebugInfo()})"); } IScopeContext originalScopeContext = AmbientContext; if (originalScopeContext != ambientScope.OrigContext) { throw new InvalidOperationException($"The detatched scope context does not match the original"); } ambientScope.OrigScope = null; ambientScope.OrigContext = null; ambientScope.Attached = false; return ambientScope; } /// <inheritdoc /> public IScope CreateScope( IsolationLevel isolationLevel = IsolationLevel.Unspecified, RepositoryCacheMode repositoryCacheMode = RepositoryCacheMode.Unspecified, IEventDispatcher eventDispatcher = null, IScopedNotificationPublisher notificationPublisher = null, bool? scopeFileSystems = null, bool callContext = false, bool autoComplete = false) { Scope ambientScope = AmbientScope; if (ambientScope == null) { IScopeContext ambientContext = AmbientContext; ScopeContext newContext = ambientContext == null ? new ScopeContext() : null; var scope = new Scope(this, _coreDebugSettings, _mediaFileManager, _eventAggregator, _loggerFactory.CreateLogger<Scope>(), _fileSystems, false, newContext, isolationLevel, repositoryCacheMode, eventDispatcher, notificationPublisher, scopeFileSystems, callContext, autoComplete); // assign only if scope creation did not throw! PushAmbientScope(scope); if (newContext != null) { PushAmbientScopeContext(newContext); } return scope; } var nested = new Scope(this, _coreDebugSettings, _mediaFileManager, _eventAggregator, _loggerFactory.CreateLogger<Scope>(), _fileSystems, ambientScope, isolationLevel, repositoryCacheMode, eventDispatcher, notificationPublisher, scopeFileSystems, callContext, autoComplete); PushAmbientScope(nested); return nested; } /// <inheritdoc /> public IScopeContext Context => AmbientContext; // for testing internal ConcurrentStack<IScope> GetCallContextScopeValue() => s_scopeStack.Value; #if DEBUG_SCOPES // this code needs TLC // // the idea here is to keep in a list all the scopes that have been created, and to remove them // when they are disposed, so we can track leaks, ie scopes that would not be properly taken // care of by our code // // note: the code could probably be optimized... but this is NOT supposed to go into any real // live build, either production or debug - it's just a debugging tool for the time being // helps identifying when non-httpContext scopes are created by logging the stack trace //private void LogCallContextStack() //{ // var trace = Environment.StackTrace; // if (trace.IndexOf("ScheduledPublishing") > 0) // LogHelper.Debug<ScopeProvider>("CallContext: Scheduled Publishing"); // else if (trace.IndexOf("TouchServerTask") > 0) // LogHelper.Debug<ScopeProvider>("CallContext: Server Registration"); // else if (trace.IndexOf("LogScrubber") > 0) // LogHelper.Debug<ScopeProvider>("CallContext: Log Scrubber"); // else // LogHelper.Debug<ScopeProvider>("CallContext: " + Environment.StackTrace); //} // all scope instances that are currently being tracked private static readonly object s_staticScopeInfosLock = new object(); private static readonly Dictionary<IScope, ScopeInfo> s_staticScopeInfos = new Dictionary<IScope, ScopeInfo>(); public IEnumerable<ScopeInfo> ScopeInfos { get { lock (s_staticScopeInfosLock) { return s_staticScopeInfos.Values.ToArray(); // capture in an array } } } public ScopeInfo GetScopeInfo(IScope scope) { lock (s_staticScopeInfosLock) { return s_staticScopeInfos.TryGetValue(scope, out ScopeInfo scopeInfo) ? scopeInfo : null; } } // register a scope and capture its ctor stacktrace public void RegisterScope(IScope scope) { if (scope is null) { throw new ArgumentNullException(nameof(scope)); } lock (s_staticScopeInfosLock) { if (s_staticScopeInfos.ContainsKey(scope)) { throw new Exception("oops: already registered."); } _logger.LogDebug("Register {ScopeId} on Thread {ThreadId}", scope.InstanceId.ToString("N").Substring(0, 8), Thread.CurrentThread.ManagedThreadId); s_staticScopeInfos[scope] = new ScopeInfo(scope, Environment.StackTrace); } } // register that a scope is in a 'context' // 'context' that contains the scope (null, "http" or "call") public void RegisterContext(IScope scope, string context) { if (scope is null) { throw new ArgumentNullException(nameof(scope)); } lock (s_staticScopeInfosLock) { if (s_staticScopeInfos.TryGetValue(scope, out ScopeInfo info) == false) { info = null; } if (info == null) { if (context == null) { return; } throw new Exception("oops: unregistered scope."); } var sb = new StringBuilder(); IScope s = scope; while (s != null) { if (sb.Length > 0) { sb.Append(" < "); } sb.Append(s.InstanceId.ToString("N").Substring(0, 8)); var ss = s as Scope; s = ss?.ParentScope; } _logger.LogTrace("Register " + (context ?? "null") + " context " + sb); if (context == null) { info.NullStack = Environment.StackTrace; } _logger.LogTrace("At:\r\n" + Head(Environment.StackTrace, 16)); info.Context = context; } } private static string Head(string s, int count) { var pos = 0; var i = 0; while (i < count && pos >= 0) { pos = s.IndexOf("\r\n", pos + 1, StringComparison.OrdinalIgnoreCase); i++; } if (pos < 0) { return s; } return s.Substring(0, pos); } public void Disposed(IScope scope) { lock (s_staticScopeInfosLock) { if (s_staticScopeInfos.ContainsKey(scope)) { // enable this by default //Console.WriteLine("unregister " + scope.InstanceId.ToString("N").Substring(0, 8)); s_staticScopeInfos.Remove(scope); _logger.LogDebug("Remove " + scope.InstanceId.ToString("N").Substring(0, 8)); // instead, enable this to keep *all* scopes // beware, there can be a lot of scopes! //info.Disposed = true; //info.DisposedStack = Environment.StackTrace; } } } #endif } #if DEBUG_SCOPES public class ScopeInfo { public ScopeInfo(IScope scope, string ctorStack) { Scope = scope; Created = DateTime.Now; CtorStack = ctorStack; } public IScope Scope { get; } // the scope itself // the scope's parent identifier public Guid Parent => ((Scope)Scope).ParentScope == null ? Guid.Empty : ((Scope)Scope).ParentScope.InstanceId; public DateTime Created { get; } // the date time the scope was created public bool Disposed { get; set; } // whether the scope has been disposed already public string Context { get; set; } // the current 'context' that contains the scope (null, "http" or "lcc") public string CtorStack { get; } // the stacktrace of the scope ctor //public string DisposedStack { get; set; } // the stacktrace when disposed public string NullStack { get; set; } // the stacktrace when the 'context' that contains the scope went null public override string ToString() => new StringBuilder() .AppendLine("ScopeInfo:") .Append("Instance Id: ") .AppendLine(Scope.InstanceId.ToString()) .Append("Parent Id: ") .AppendLine(Parent.ToString()) .Append("Created Thread Id: ") .AppendLine(Scope.CreatedThreadId.ToInvariantString()) .Append("Created At: ") .AppendLine(Created.ToString("O")) .Append("Disposed: ") .AppendLine(Disposed.ToString()) .Append("CTOR stack: ") .AppendLine(CtorStack) .ToString(); } #endif }
using OpenKh.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Xe.BinaryMapper; namespace OpenKh.Kh2.TextureFooter { public class TextureFooterData { public List<UvScroll> UvscList { get; } = new List<UvScroll>(); public List<TextureAnimation> TextureAnimationList { get; } = new List<TextureAnimation>(); public byte[] UnkFooter { get; set; } public bool ShouldEmitDMYAtFirst { get; set; } public bool ShouldEmitKN5 { get; set; } public override string ToString() => $"{UvscList.Count} UVSC, {TextureAnimationList.Count} TEXA"; public TextureFooterData() { } public TextureFooterData(Stream stream) { var shouldEmitDMYAtFirst = false; var index = -1; while (stream.Position < stream.Length) { ++index; var tag = Encoding.ASCII.GetString(stream.ReadBytes(4)); if (tag == "_KN5") { ShouldEmitDMYAtFirst = (index == 1) && shouldEmitDMYAtFirst; ShouldEmitKN5 = true; UnkFooter = stream.ReadBytes(); break; } var length = stream.ReadInt32(); var nextTag = stream.Position + length; var subStreamPos = Convert.ToInt32(stream.Position); if (tag == "UVSC") { UvscList.Add(BinaryMapping.ReadObject<UvScroll>(stream)); } else if (tag == "TEXA") { var header = BinaryMapping.ReadObject<TextureAnimation>(stream); stream.Position = subStreamPos + header.OffsetSlotTable; header.SlotTable = Enumerable.Range(0, 1 + header.MaximumSlotIndex - header.BaseSlotIndex) .Select(_ => stream.ReadInt16()) .ToArray(); stream.Position = subStreamPos + header.OffsetAnimationTable; var frameGroupOffsetList = Enumerable.Range(0, header.NumAnimations) .Select(idx => stream.ReadUInt32()) .ToArray(); header.FrameGroupList = frameGroupOffsetList .Select( firstPosition => { stream.Position = subStreamPos + firstPosition; var indexedFrameList = new Dictionary<int, TextureFrame>(); var idx = 0; while (true) { if (indexedFrameList.ContainsKey(idx)) { break; } var frame = BinaryMapping.ReadObject<TextureFrame>(stream); indexedFrameList[idx] = frame; if (frame.FrameControl == TextureFrameControl.Jump || frame.FrameControl == TextureFrameControl.Stop) { idx += frame.FrameIndexDelta; stream.Seek(TextureFrame.SizeInBytes * (-1 + frame.FrameIndexDelta), SeekOrigin.Current); } else { idx++; } } return new TextureFrameGroup { IndexedFrameList = indexedFrameList, }; } ) .ToArray(); header.SpriteImage = stream .SetPosition(subStreamPos + header.OffsetSpriteImage) .ReadBytes(header.SpriteStride * header.SpriteHeight * header.NumSpritesInImageData); TextureAnimationList.Add(header); } else if (tag == "_DMY") { shouldEmitDMYAtFirst |= (index == 0) ? true : false; } stream.Position = nextTag; } } public static TextureFooterData Read(Stream stream) => new TextureFooterData(stream); /// <summary> /// Terminator mark /// </summary> private static byte[] _KN5 = Encoding.ASCII.GetBytes("_KN5"); /// <summary> /// Dummy /// </summary> private static byte[] _DMY = Encoding.ASCII.GetBytes("_DMY"); private static byte[] UVSC = Encoding.ASCII.GetBytes("UVSC"); private static byte[] TEXA = Encoding.ASCII.GetBytes("TEXA"); public void Write(Stream stream) { if (ShouldEmitDMYAtFirst) { // Some map files has style "_DMY" "_KN5". This is for that consistency. stream.Write(_DMY); stream.Write(0); } foreach (var item in TextureAnimationList) { var texaStream = new MemoryStream(); { item.NumAnimations = Convert.ToUInt16(item.FrameGroupList.Length); var animationTable = new int[item.NumAnimations]; for (var pass = 1; pass <= 2; pass++) { texaStream.Position = 0; BinaryMapping.WriteObject(texaStream, item); item.OffsetSlotTable = Convert.ToInt32(texaStream.Position); item.SlotTable.ToList().ForEach(texaStream.Write); texaStream.AlignPosition(4); item.OffsetAnimationTable = Convert.ToInt32(texaStream.Position); texaStream.Write(animationTable); foreach (var (group, groupIndex) in item.FrameGroupList.Select((group, groupIndex) => (group, groupIndex))) { animationTable[groupIndex] = Convert.ToInt32(texaStream.Position); if (group.IndexedFrameList.Any()) { int minIdx = group.IndexedFrameList.Keys.Min(); int maxIdx = group.IndexedFrameList.Keys.Max(); for (; minIdx <= maxIdx; minIdx++) { group.IndexedFrameList.TryGetValue(minIdx, out TextureFrame frame); frame = frame ?? new TextureFrame(); BinaryMapping.WriteObject(texaStream, frame); } } } texaStream.AlignPosition(16); item.OffsetSpriteImage = Convert.ToInt32(texaStream.Position); texaStream.Write(item.SpriteImage); texaStream.AlignPosition(16); } } stream.Write(_DMY); stream.Write(0); stream.Write(TEXA); stream.Write(Convert.ToUInt32(texaStream.Length)); texaStream.Position = 0; texaStream.CopyTo(stream); } if (UvscList.Any()) { // Before first "UVSC", "_DMY" has to be placed. This is for that consistency. stream.Write(_DMY); stream.Write(0); foreach (var item in UvscList) { stream.Write(UVSC); stream.Write(12); BinaryMapping.WriteObject(stream, item); } } else if (TextureAnimationList.Any()) { // Between "TEXA" and "_KN5", "_DMY" has to be placed. This is for that consistency. stream.Write(_DMY); stream.Write(0); } if (ShouldEmitKN5) { stream.Write(_KN5); } if (UnkFooter != null) { stream.Write(UnkFooter); } } } }
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.14.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * TaskQueue API Version v1beta2 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/appengine/docs/python/taskqueue/rest'>TaskQueue API</a> * <tr><th>API Version<td>v1beta2 * <tr><th>API Rev<td>20160428 (483) * <tr><th>API Docs * <td><a href='https://developers.google.com/appengine/docs/python/taskqueue/rest'> * https://developers.google.com/appengine/docs/python/taskqueue/rest</a> * <tr><th>Discovery Name<td>taskqueue * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using TaskQueue API can be found at * <a href='https://developers.google.com/appengine/docs/python/taskqueue/rest'>https://developers.google.com/appengine/docs/python/taskqueue/rest</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Taskqueue.v1beta2 { /// <summary>The Taskqueue Service.</summary> public class TaskqueueService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta2"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public TaskqueueService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public TaskqueueService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { taskqueues = new TaskqueuesResource(this); tasks = new TasksResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "taskqueue"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/taskqueue/v1beta2/projects/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "taskqueue/v1beta2/projects/"; } } /// <summary>Available OAuth 2.0 scopes for use with the TaskQueue API.</summary> public class Scope { /// <summary>Manage your Tasks and Taskqueues</summary> public static string Taskqueue = "https://www.googleapis.com/auth/taskqueue"; /// <summary>Consume Tasks from your Taskqueues</summary> public static string TaskqueueConsumer = "https://www.googleapis.com/auth/taskqueue.consumer"; } private readonly TaskqueuesResource taskqueues; /// <summary>Gets the Taskqueues resource.</summary> public virtual TaskqueuesResource Taskqueues { get { return taskqueues; } } private readonly TasksResource tasks; /// <summary>Gets the Tasks resource.</summary> public virtual TasksResource Tasks { get { return tasks; } } } ///<summary>A base abstract class for Taskqueue requests.</summary> public abstract class TaskqueueBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new TaskqueueBaseServiceRequest instance.</summary> protected TaskqueueBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Taskqueue parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "taskqueues" collection of methods.</summary> public class TaskqueuesResource { private const string Resource = "taskqueues"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TaskqueuesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Get detailed information about a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The id of the /// taskqueue to get the properties of.</param> public virtual GetRequest Get(string project, string taskqueue) { return new GetRequest(service, project, taskqueue); } /// <summary>Get detailed information about a TaskQueue.</summary> public class GetRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta2.Data.TaskQueue> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string project, string taskqueue) : base(service) { Project = project; Taskqueue = taskqueue; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The id of the taskqueue to get the properties of.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>Whether to get stats. Optional.</summary> [Google.Apis.Util.RequestParameterAttribute("getStats", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> GetStats { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "getStats", new Google.Apis.Discovery.Parameter { Name = "getStats", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "tasks" collection of methods.</summary> public class TasksResource { private const string Resource = "tasks"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TasksResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Delete a task from a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The taskqueue /// to delete a task from.</param> /// <param name="task">The id of the task to delete.</param> public virtual DeleteRequest Delete(string project, string taskqueue, string task) { return new DeleteRequest(service, project, taskqueue, task); } /// <summary>Delete a task from a TaskQueue.</summary> public class DeleteRequest : TaskqueueBaseServiceRequest<string> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string project, string taskqueue, string task) : base(service) { Project = project; Taskqueue = taskqueue; Task = task; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue to delete a task from.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>The id of the task to delete.</summary> [Google.Apis.Util.RequestParameterAttribute("task", Google.Apis.Util.RequestParameterType.Path)] public virtual string Task { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/{task}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "task", new Google.Apis.Discovery.Parameter { Name = "task", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Get a particular task from a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The taskqueue /// in which the task belongs.</param> /// <param name="task">The task to get properties of.</param> public virtual GetRequest Get(string project, string taskqueue, string task) { return new GetRequest(service, project, taskqueue, task); } /// <summary>Get a particular task from a TaskQueue.</summary> public class GetRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta2.Data.Task> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string project, string taskqueue, string task) : base(service) { Project = project; Taskqueue = taskqueue; Task = task; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue in which the task belongs.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>The task to get properties of.</summary> [Google.Apis.Util.RequestParameterAttribute("task", Google.Apis.Util.RequestParameterType.Path)] public virtual string Task { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/{task}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "task", new Google.Apis.Discovery.Parameter { Name = "task", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Insert a new task in a TaskQueue</summary> /// <param name="body">The body of the request.</param> /// <param name="project">The project under which the queue lies</param> /// <param name="taskqueue">The taskqueue /// to insert the task into</param> public virtual InsertRequest Insert(Google.Apis.Taskqueue.v1beta2.Data.Task body, string project, string taskqueue) { return new InsertRequest(service, body, project, taskqueue); } /// <summary>Insert a new task in a TaskQueue</summary> public class InsertRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta2.Data.Task> { /// <summary>Constructs a new Insert request.</summary> public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Taskqueue.v1beta2.Data.Task body, string project, string taskqueue) : base(service) { Project = project; Taskqueue = taskqueue; Body = body; InitParameters(); } /// <summary>The project under which the queue lies</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue to insert the task into</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Taskqueue.v1beta2.Data.Task Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "insert"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks"; } } /// <summary>Initializes Insert parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Lease 1 or more tasks from a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The taskqueue /// to lease a task from.</param> /// <param name="numTasks">The number of tasks to lease.</param> /// <param /// name="leaseSecs">The lease in seconds.</param> public virtual LeaseRequest Lease(string project, string taskqueue, int numTasks, int leaseSecs) { return new LeaseRequest(service, project, taskqueue, numTasks, leaseSecs); } /// <summary>Lease 1 or more tasks from a TaskQueue.</summary> public class LeaseRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta2.Data.Tasks> { /// <summary>Constructs a new Lease request.</summary> public LeaseRequest(Google.Apis.Services.IClientService service, string project, string taskqueue, int numTasks, int leaseSecs) : base(service) { Project = project; Taskqueue = taskqueue; NumTasks = numTasks; LeaseSecs = leaseSecs; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue to lease a task from.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>The number of tasks to lease.</summary> [Google.Apis.Util.RequestParameterAttribute("numTasks", Google.Apis.Util.RequestParameterType.Query)] public virtual int NumTasks { get; private set; } /// <summary>The lease in seconds.</summary> [Google.Apis.Util.RequestParameterAttribute("leaseSecs", Google.Apis.Util.RequestParameterType.Query)] public virtual int LeaseSecs { get; private set; } /// <summary>When true, all returned tasks will have the same tag</summary> [Google.Apis.Util.RequestParameterAttribute("groupByTag", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> GroupByTag { get; set; } /// <summary>The tag allowed for tasks in the response. Must only be specified if group_by_tag is true. If /// group_by_tag is true and tag is not specified the tag will be that of the oldest task by eta, i.e. the /// first available tag</summary> [Google.Apis.Util.RequestParameterAttribute("tag", Google.Apis.Util.RequestParameterType.Query)] public virtual string Tag { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "lease"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/lease"; } } /// <summary>Initializes Lease parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "numTasks", new Google.Apis.Discovery.Parameter { Name = "numTasks", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "leaseSecs", new Google.Apis.Discovery.Parameter { Name = "leaseSecs", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "groupByTag", new Google.Apis.Discovery.Parameter { Name = "groupByTag", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "tag", new Google.Apis.Discovery.Parameter { Name = "tag", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>List Tasks in a TaskQueue</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The id of the /// taskqueue to list tasks from.</param> public virtual ListRequest List(string project, string taskqueue) { return new ListRequest(service, project, taskqueue); } /// <summary>List Tasks in a TaskQueue</summary> public class ListRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta2.Data.Tasks2> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string project, string taskqueue) : base(service) { Project = project; Taskqueue = taskqueue; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The id of the taskqueue to list tasks from.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Update tasks that are leased out of a TaskQueue. This method supports patch semantics.</summary> /// <param name="body">The body of the request.</param> /// <param name="project">The project under which the queue lies.</param> /// <param /// name="taskqueue"></param> /// <param name="task"></param> /// <param name="newLeaseSeconds">The new lease in /// seconds.</param> public virtual PatchRequest Patch(Google.Apis.Taskqueue.v1beta2.Data.Task body, string project, string taskqueue, string task, int newLeaseSeconds) { return new PatchRequest(service, body, project, taskqueue, task, newLeaseSeconds); } /// <summary>Update tasks that are leased out of a TaskQueue. This method supports patch semantics.</summary> public class PatchRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta2.Data.Task> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Taskqueue.v1beta2.Data.Task body, string project, string taskqueue, string task, int newLeaseSeconds) : base(service) { Project = project; Taskqueue = taskqueue; Task = task; NewLeaseSeconds = newLeaseSeconds; Body = body; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } [Google.Apis.Util.RequestParameterAttribute("task", Google.Apis.Util.RequestParameterType.Path)] public virtual string Task { get; private set; } /// <summary>The new lease in seconds.</summary> [Google.Apis.Util.RequestParameterAttribute("newLeaseSeconds", Google.Apis.Util.RequestParameterType.Query)] public virtual int NewLeaseSeconds { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Taskqueue.v1beta2.Data.Task Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "patch"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PATCH"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/{task}"; } } /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "task", new Google.Apis.Discovery.Parameter { Name = "task", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "newLeaseSeconds", new Google.Apis.Discovery.Parameter { Name = "newLeaseSeconds", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Update tasks that are leased out of a TaskQueue.</summary> /// <param name="body">The body of the request.</param> /// <param name="project">The project under which the queue lies.</param> /// <param /// name="taskqueue"></param> /// <param name="task"></param> /// <param name="newLeaseSeconds">The new lease in /// seconds.</param> public virtual UpdateRequest Update(Google.Apis.Taskqueue.v1beta2.Data.Task body, string project, string taskqueue, string task, int newLeaseSeconds) { return new UpdateRequest(service, body, project, taskqueue, task, newLeaseSeconds); } /// <summary>Update tasks that are leased out of a TaskQueue.</summary> public class UpdateRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta2.Data.Task> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Taskqueue.v1beta2.Data.Task body, string project, string taskqueue, string task, int newLeaseSeconds) : base(service) { Project = project; Taskqueue = taskqueue; Task = task; NewLeaseSeconds = newLeaseSeconds; Body = body; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } [Google.Apis.Util.RequestParameterAttribute("task", Google.Apis.Util.RequestParameterType.Path)] public virtual string Task { get; private set; } /// <summary>The new lease in seconds.</summary> [Google.Apis.Util.RequestParameterAttribute("newLeaseSeconds", Google.Apis.Util.RequestParameterType.Query)] public virtual int NewLeaseSeconds { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Taskqueue.v1beta2.Data.Task Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "update"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/{task}"; } } /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "task", new Google.Apis.Discovery.Parameter { Name = "task", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "newLeaseSeconds", new Google.Apis.Discovery.Parameter { Name = "newLeaseSeconds", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Taskqueue.v1beta2.Data { public class Task : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Time (in seconds since the epoch) at which the task was enqueued.</summary> [Newtonsoft.Json.JsonPropertyAttribute("enqueueTimestamp")] public virtual System.Nullable<long> EnqueueTimestamp { get; set; } /// <summary>Name of the task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The kind of object returned, in this case set to task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Time (in seconds since the epoch) at which the task lease will expire. This value is 0 if the task /// isnt currently leased out to a worker.</summary> [Newtonsoft.Json.JsonPropertyAttribute("leaseTimestamp")] public virtual System.Nullable<long> LeaseTimestamp { get; set; } /// <summary>A bag of bytes which is the task payload. The payload on the JSON side is always Base64 /// encoded.</summary> [Newtonsoft.Json.JsonPropertyAttribute("payloadBase64")] public virtual string PayloadBase64 { get; set; } /// <summary>Name of the queue that the task is in.</summary> [Newtonsoft.Json.JsonPropertyAttribute("queueName")] public virtual string QueueName { get; set; } /// <summary>The number of leases applied to this task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("retry_count")] public virtual System.Nullable<int> RetryCount { get; set; } /// <summary>Tag for the task, could be used later to lease tasks grouped by a specific tag.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tag")] public virtual string Tag { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class TaskQueue : Google.Apis.Requests.IDirectResponseSchema { /// <summary>ACLs that are applicable to this TaskQueue object.</summary> [Newtonsoft.Json.JsonPropertyAttribute("acl")] public virtual TaskQueue.AclData Acl { get; set; } /// <summary>Name of the taskqueue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The kind of REST object returned, in this case taskqueue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The number of times we should lease out tasks before giving up on them. If unset we lease them out /// forever until a worker deletes the task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("maxLeases")] public virtual System.Nullable<int> MaxLeases { get; set; } /// <summary>Statistics for the TaskQueue object in question.</summary> [Newtonsoft.Json.JsonPropertyAttribute("stats")] public virtual TaskQueue.StatsData Stats { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>ACLs that are applicable to this TaskQueue object.</summary> public class AclData { /// <summary>Email addresses of users who are "admins" of the TaskQueue. This means they can control the /// queue, eg set ACLs for the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("adminEmails")] public virtual System.Collections.Generic.IList<string> AdminEmails { get; set; } /// <summary>Email addresses of users who can "consume" tasks from the TaskQueue. This means they can /// Dequeue and Delete tasks from the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("consumerEmails")] public virtual System.Collections.Generic.IList<string> ConsumerEmails { get; set; } /// <summary>Email addresses of users who can "produce" tasks into the TaskQueue. This means they can Insert /// tasks into the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("producerEmails")] public virtual System.Collections.Generic.IList<string> ProducerEmails { get; set; } } /// <summary>Statistics for the TaskQueue object in question.</summary> public class StatsData { /// <summary>Number of tasks leased in the last hour.</summary> [Newtonsoft.Json.JsonPropertyAttribute("leasedLastHour")] public virtual System.Nullable<long> LeasedLastHour { get; set; } /// <summary>Number of tasks leased in the last minute.</summary> [Newtonsoft.Json.JsonPropertyAttribute("leasedLastMinute")] public virtual System.Nullable<long> LeasedLastMinute { get; set; } /// <summary>The timestamp (in seconds since the epoch) of the oldest unfinished task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("oldestTask")] public virtual System.Nullable<long> OldestTask { get; set; } /// <summary>Number of tasks in the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("totalTasks")] public virtual System.Nullable<int> TotalTasks { get; set; } } } public class Tasks : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The actual list of tasks returned as a result of the lease operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<Task> Items { get; set; } /// <summary>The kind of object returned, a list of tasks.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class Tasks2 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The actual list of tasks currently active in the TaskQueue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<Task> Items { get; set; } /// <summary>The kind of object returned, a list of tasks.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using FileHelpers.Options; namespace FileHelpers { /// <summary> /// Base class for all Field Types. /// Implements all the basic functionality of a field in a typed file. /// </summary> public abstract class FieldBase : ICloneable { #region " Private & Internal Fields " // -------------------------------------------------------------- // WARNING !!! // Remember to add each of these fields to the clone method !! // -------------------------------------------------------------- /// <summary> /// type of object to be created, eg DateTime /// </summary> public Type FieldType { get; private set; } /// <summary> /// Provider to convert to and from text /// </summary> public ConverterBase Converter { get; private set; } /// <summary> /// Number of extra characters used, delimiters and quote characters /// </summary> internal virtual int CharsToDiscard { get { return 0; } } /// <summary> /// Field type of an array or it is just fieldType. /// What actual object will be created /// </summary> internal Type FieldTypeInternal { get; set; } /// <summary> /// Is this field an array? /// </summary> public bool IsArray { get; private set; } /// <summary> /// Array must have this many entries /// </summary> public int ArrayMinLength { get; set; } /// <summary> /// Array may have this many entries, if equal to ArrayMinLength then /// it is a fixed length array /// </summary> public int ArrayMaxLength { get; set; } /// <summary> /// Seems to be duplicate of FieldTypeInternal except it is ONLY set /// for an array /// </summary> internal Type ArrayType { get; set; } /// <summary> /// Do we process this field but not store the value /// </summary> public bool Discarded { get; set; } /// <summary> /// Unused! /// </summary> internal bool TrailingArray { get; set; } /// <summary> /// Value to use if input is null or empty /// </summary> internal object NullValue { get; set; } /// <summary> /// Are we a simple string field we can just assign to /// </summary> internal bool IsStringField { get; set; } /// <summary> /// Details about the extraction criteria /// </summary> internal FieldInfo FieldInfo { get; set; } /// <summary> /// indicates whether we trim leading and/or trailing whitespace /// </summary> public TrimMode TrimMode { get; set; } /// <summary> /// Character to chop off front and / rear of the string /// </summary> internal char[] TrimChars { get; set; } /// <summary> /// The field may not be present on the input data (line not long enough) /// </summary> public bool IsOptional { get; set; } /// <summary> /// The next field along is optional, optimise processing next records /// </summary> internal bool NextIsOptional { get { if (Parent.FieldCount > ParentIndex + 1) return Parent.Fields[ParentIndex + 1].IsOptional; return false; } } /// <summary> /// Am I the first field in an array list /// </summary> internal bool IsFirst { get { return ParentIndex == 0; } } /// <summary> /// Am I the last field in the array list /// </summary> internal bool IsLast { get { return ParentIndex == Parent.FieldCount - 1; } } /// <summary> /// Set from the FieldInNewLIneAtribute. This field begins on a new /// line of the file /// </summary> internal bool InNewLine { get; set; } /// <summary> /// Order of the field in the file layout /// </summary> internal int? FieldOrder { get; set; } /// <summary> /// Can null be assigned to this value type, for example not int or /// DateTime /// </summary> internal bool IsNullableType { get; private set; } /// <summary> /// Name of the field without extra characters (eg property) /// </summary> internal string FieldFriendlyName { get; set; } /// <summary> /// The field must be not be empty /// </summary> public bool IsNotEmpty { get; set; } /// <summary> /// Caption of the field displayed in header row (see EngineBase.GetFileHeader) /// </summary> internal string FieldCaption { get; set; } // -------------------------------------------------------------- // WARNING !!! // Remember to add each of these fields to the clone method !! // -------------------------------------------------------------- /// <summary> /// Fieldname of the field we are storing /// </summary> internal string FieldName { get { return FieldInfo.Name; } } /* private static readonly char[] mWhitespaceChars = new[] { '\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200a', '\u200b', '\u3000', '\ufeff' */ #endregion #region " CreateField " /// <summary> /// Check the Attributes on the field and return a structure containing /// the settings for this file. /// </summary> /// <param name="fi">Information about this field</param> /// <param name="recordAttribute">Type of record we are reading</param> /// <returns>Null if not used</returns> public static FieldBase CreateField(FieldInfo fi, TypedRecordAttribute recordAttribute) { FieldBase res = null; MemberInfo mi = fi; var memberName = "The field: '" + fi.Name; Type fieldType = fi.FieldType; string fieldFriendlyName = AutoPropertyName(fi); if (string.IsNullOrEmpty(fieldFriendlyName)==false) { var prop = fi.DeclaringType.GetProperty(fieldFriendlyName); if (prop != null) { memberName = "The property: '" + prop.Name; mi = prop; } else { fieldFriendlyName = null; } } // If ignored, return null #pragma warning disable 612,618 // disable obsole warning if (mi.IsDefined(typeof (FieldNotInFileAttribute), true) || mi.IsDefined(typeof (FieldIgnoredAttribute), true) || mi.IsDefined(typeof (FieldHiddenAttribute), true)) #pragma warning restore 612,618 return null; var attributes = (FieldAttribute[]) mi.GetCustomAttributes(typeof (FieldAttribute), true); // CHECK USAGE ERRORS !!! // Fixed length record and no attributes at all if (recordAttribute is FixedLengthRecordAttribute && attributes.Length == 0) { throw new BadUsageException(memberName + "' must be marked the FieldFixedLength attribute because the record class is marked with FixedLengthRecord."); } if (attributes.Length > 1) { throw new BadUsageException(memberName + "' has a FieldFixedLength and a FieldDelimiter attribute."); } if (recordAttribute is DelimitedRecordAttribute && mi.IsDefined(typeof (FieldAlignAttribute), false)) { throw new BadUsageException(memberName + "' can't be marked with FieldAlign attribute, it is only valid for fixed length records and are used only for write purpose."); } if (fieldType.IsArray == false && mi.IsDefined(typeof (FieldArrayLengthAttribute), false)) { throw new BadUsageException(memberName + "' can't be marked with FieldArrayLength attribute is only valid for array fields."); } // PROCESS IN NORMAL CONDITIONS if (attributes.Length > 0) { FieldAttribute fieldAttb = attributes[0]; if (fieldAttb is FieldFixedLengthAttribute) { // Fixed Field if (recordAttribute is DelimitedRecordAttribute) { throw new BadUsageException(memberName + "' can't be marked with FieldFixedLength attribute, it is only for the FixedLengthRecords not for delimited ones."); } var attbFixedLength = (FieldFixedLengthAttribute) fieldAttb; var attbAlign = Attributes.GetFirst<FieldAlignAttribute>(mi); res = new FixedLengthField(fi, attbFixedLength.Length, attbAlign); ((FixedLengthField) res).FixedMode = ((FixedLengthRecordAttribute) recordAttribute).FixedMode; } else if (fieldAttb is FieldDelimiterAttribute) { // Delimited Field if (recordAttribute is FixedLengthRecordAttribute) { throw new BadUsageException(memberName + "' can't be marked with FieldDelimiter attribute, it is only for DelimitedRecords not for fixed ones."); } res = new DelimitedField(fi, ((FieldDelimiterAttribute) fieldAttb).Delimiter); } else { throw new BadUsageException( "Custom field attributes are not currently supported. Unknown attribute: " + fieldAttb.GetType().Name + " on field: " + fi.Name); } } else // attributes.Length == 0 { var delimitedRecordAttribute = recordAttribute as DelimitedRecordAttribute; if (delimitedRecordAttribute != null) { res = new DelimitedField(fi, delimitedRecordAttribute.Separator); } } if (res != null) { // FieldDiscarded res.Discarded = mi.IsDefined(typeof (FieldValueDiscardedAttribute), false); // FieldTrim Attributes.WorkWithFirst<FieldTrimAttribute>(mi, (x) => { res.TrimMode = x.TrimMode; res.TrimChars = x.TrimChars; }); // FieldQuoted Attributes.WorkWithFirst<FieldQuotedAttribute>(mi, (x) => { if (res is FixedLengthField) { throw new BadUsageException( memberName + "' can't be marked with FieldQuoted attribute, it is only for the delimited records."); } ((DelimitedField) res).QuoteChar = x.QuoteChar; ((DelimitedField) res).QuoteMode = x.QuoteMode; ((DelimitedField) res).QuoteMultiline = x.QuoteMultiline; }); // FieldOrder Attributes.WorkWithFirst<FieldOrderAttribute>(mi, x => res.FieldOrder = x.Order); // FieldCaption Attributes.WorkWithFirst<FieldCaptionAttribute>(mi, x => res.FieldCaption = x.Caption); // FieldOptional res.IsOptional = mi.IsDefined(typeof(FieldOptionalAttribute), false); // FieldInNewLine res.InNewLine = mi.IsDefined(typeof(FieldInNewLineAttribute), false); // FieldNotEmpty res.IsNotEmpty = mi.IsDefined(typeof(FieldNotEmptyAttribute), false); // FieldArrayLength if (fieldType.IsArray) { res.IsArray = true; res.ArrayType = fieldType.GetElementType(); // MinValue indicates that there is no FieldArrayLength in the array res.ArrayMinLength = int.MinValue; res.ArrayMaxLength = int.MaxValue; Attributes.WorkWithFirst<FieldArrayLengthAttribute>(mi, (x) => { res.ArrayMinLength = x.MinLength; res.ArrayMaxLength = x.MaxLength; if (res.ArrayMaxLength < res.ArrayMinLength || res.ArrayMinLength < 0 || res.ArrayMaxLength <= 0) { throw new BadUsageException(memberName + " has invalid length values in the [FieldArrayLength] attribute."); } }); } } if (string.IsNullOrEmpty(res.FieldFriendlyName)) res.FieldFriendlyName = res.FieldName; return res; } internal RecordOptions Parent { get; set; } internal int ParentIndex { get; set; } internal static string AutoPropertyName(FieldInfo fi) { if (fi.IsDefined(typeof(CompilerGeneratedAttribute), false)) { if (fi.Name.EndsWith("__BackingField") && fi.Name.StartsWith("<") && fi.Name.Contains(">")) return fi.Name.Substring(1, fi.Name.IndexOf(">") - 1); } return ""; } internal bool IsAutoProperty { get; set; } #endregion #region " Constructor " /// <summary> /// Create a field base without any configuration /// </summary> internal FieldBase() { IsNullableType = false; TrimMode = TrimMode.None; FieldOrder = null; InNewLine = false; //NextIsOptional = false; IsOptional = false; TrimChars = null; NullValue = null; TrailingArray = false; IsArray = false; IsNotEmpty = false; } /// <summary> /// Create a field base from a fieldinfo object /// Verify the settings against the actual field to ensure it will work. /// </summary> /// <param name="fi">Field Info Object</param> internal FieldBase(FieldInfo fi) : this() { FieldInfo = fi; FieldType = FieldInfo.FieldType; MemberInfo attibuteTarget = fi; this.FieldFriendlyName = AutoPropertyName(fi); if (string.IsNullOrEmpty(FieldFriendlyName) == false) { var prop = fi.DeclaringType.GetProperty(this.FieldFriendlyName); if (prop == null) { this.FieldFriendlyName = null; } else { this.IsAutoProperty = true; attibuteTarget = prop; } } if (FieldType.IsArray) FieldTypeInternal = FieldType.GetElementType(); else FieldTypeInternal = FieldType; IsStringField = FieldTypeInternal == typeof (string); object[] attribs = attibuteTarget.GetCustomAttributes(typeof (FieldConverterAttribute), true); if (attribs.Length > 0) { var conv = (FieldConverterAttribute) attribs[0]; this.Converter = conv.Converter; conv.ValidateTypes(FieldInfo); } else this.Converter = ConvertHelpers.GetDefaultConverter(FieldFriendlyName ?? fi.Name, FieldType); if (this.Converter != null) this.Converter.mDestinationType = FieldTypeInternal; attribs = attibuteTarget.GetCustomAttributes(typeof (FieldNullValueAttribute), true); if (attribs.Length > 0) { NullValue = ((FieldNullValueAttribute) attribs[0]).NullValue; // mNullValueOnWrite = ((FieldNullValueAttribute) attribs[0]).NullValueOnWrite; if (NullValue != null) { if (!FieldTypeInternal.IsAssignableFrom(NullValue.GetType())) { throw new BadUsageException("The NullValue is of type: " + NullValue.GetType().Name + " that is not asignable to the field " + FieldInfo.Name + " of type: " + FieldTypeInternal.Name); } } } IsNullableType = FieldTypeInternal.IsValueType && FieldTypeInternal.IsGenericType && FieldTypeInternal.GetGenericTypeDefinition() == typeof (Nullable<>); } #endregion #region " MustOverride (String Handling) " /// <summary> /// Extract the string from the underlying data, removes quotes /// characters for example /// </summary> /// <param name="line">Line to parse data from</param> /// <returns>Slightly processed string from the data</returns> internal abstract ExtractedInfo ExtractFieldString(LineInfo line); /// <summary> /// Create a text block containing the field from definition /// </summary> /// <param name="sb">Append string to output</param> /// <param name="fieldValue">Field we are adding</param> /// <param name="isLast">Indicates if we are processing last field</param> internal abstract void CreateFieldString(StringBuilder sb, object fieldValue, bool isLast); /// <summary> /// Convert a field value to a string representation /// </summary> /// <param name="fieldValue">Object containing data</param> /// <returns>String representation of field</returns> internal string CreateFieldString(object fieldValue) { if (this.Converter == null) { if (fieldValue == null) return string.Empty; else return fieldValue.ToString(); } else return this.Converter.FieldToString(fieldValue); } #endregion #region " ExtractValue " /// <summary> /// Get the data out of the records /// </summary> /// <param name="line">Line handler containing text</param> /// <returns></returns> internal object ExtractFieldValue(LineInfo line) { //-> extract only what I need if (InNewLine) { // Any trailing characters, terminate if (line.EmptyFromPos() == false) { throw new BadUsageException(line, "Text '" + line.CurrentString + "' found before the new line of the field: " + FieldInfo.Name + " (this is not allowed when you use [FieldInNewLine])"); } line.ReLoad(line.mReader.ReadNextLine()); if (line.mLineStr == null) { throw new BadUsageException(line, "End of stream found parsing the field " + FieldInfo.Name + ". Please check the class record."); } } if (IsArray == false) { ExtractedInfo info = ExtractFieldString(line); if (info.mCustomExtractedString == null) line.mCurrentPos = info.ExtractedTo + 1; line.mCurrentPos += CharsToDiscard; //total; if (Discarded) return GetDiscardedNullValue(); else return AssignFromString(info, line).Value; } else { if (ArrayMinLength <= 0) ArrayMinLength = 0; int i = 0; var res = new ArrayList(Math.Max(ArrayMinLength, 10)); while (line.mCurrentPos - CharsToDiscard < line.mLineStr.Length && i < ArrayMaxLength) { ExtractedInfo info = ExtractFieldString(line); if (info.mCustomExtractedString == null) line.mCurrentPos = info.ExtractedTo + 1; line.mCurrentPos += CharsToDiscard; try { var value = AssignFromString(info, line); if (value.NullValueUsed && i == 0 && line.IsEOL()) break; res.Add(value.Value); } catch (NullValueNotFoundException) { if (i == 0) break; else throw; } i++; } if (res.Count < ArrayMinLength) { throw new InvalidOperationException( string.Format( "Line: {0} Column: {1} Field: {2}. The array has only {3} values, less than the minimum length of {4}", line.mReader.LineNumber.ToString(), line.mCurrentPos.ToString(), FieldInfo.Name, res.Count, ArrayMinLength)); } else if (IsLast && line.IsEOL() == false) { throw new InvalidOperationException( string.Format( "Line: {0} Column: {1} Field: {2}. The array has more values than the maximum length of {3}", line.mReader.LineNumber, line.mCurrentPos, FieldInfo.Name, ArrayMaxLength)); } // TODO: is there a reason we go through all the array processing then discard it if (Discarded) return null; else return res.ToArray(ArrayType); } } #region " AssignFromString " private struct AssignResult { public object Value; public bool NullValueUsed; } /// <summary> /// Create field object after extracting the string from the underlying /// input data /// </summary> /// <param name="fieldString">Information extracted?</param> /// <param name="line">Underlying input data</param> /// <returns>Object to assign to field</returns> private AssignResult AssignFromString(ExtractedInfo fieldString, LineInfo line) { object val; var extractedString = fieldString.ExtractedString(); try { if (IsNotEmpty && String.IsNullOrEmpty(extractedString)) { throw new InvalidOperationException("The value is empty and must be populated."); } else if (this.Converter == null) { if (IsStringField) val = TrimString(extractedString); else { extractedString = extractedString.Trim(); if (extractedString.Length == 0) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } else val = Convert.ChangeType(extractedString, FieldTypeInternal, null); } } else { var trimmedString = extractedString.Trim(); if (this.Converter.CustomNullHandling == false && trimmedString.Length == 0) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } else { if (TrimMode == TrimMode.Both) val = this.Converter.StringToField(trimmedString); else val = this.Converter.StringToField(TrimString(extractedString)); if (val == null) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } } } return new AssignResult { Value = val }; } catch (ConvertException ex) { ex.FieldName = FieldInfo.Name; ex.LineNumber = line.mReader.LineNumber; ex.ColumnNumber = fieldString.ExtractedFrom + 1; throw; } catch (BadUsageException) { throw; } catch (Exception ex) { if (this.Converter == null || this.Converter.GetType().Assembly == typeof (FieldBase).Assembly) { throw new ConvertException(extractedString, FieldTypeInternal, FieldInfo.Name, line.mReader.LineNumber, fieldString.ExtractedFrom + 1, ex.Message, ex); } else { throw new ConvertException(extractedString, FieldTypeInternal, FieldInfo.Name, line.mReader.LineNumber, fieldString.ExtractedFrom + 1, "Your custom converter: " + this.Converter.GetType().Name + " throws an " + ex.GetType().Name + " with the message: " + ex.Message, ex); } } } private String TrimString(string extractedString) { switch (TrimMode) { case TrimMode.None: return extractedString; case TrimMode.Both: return extractedString.Trim(); case TrimMode.Left: return extractedString.TrimStart(); case TrimMode.Right: return extractedString.TrimEnd(); default: throw new Exception("Trim mode invalid in FieldBase.TrimString -> " + TrimMode.ToString()); } } /// <summary> /// Convert a null value into a representation, /// allows for a null value override /// </summary> /// <param name="line">input line to read, used for error messages</param> /// <returns>Null value for object</returns> private object GetNullValue(LineInfo line) { if (NullValue == null) { if (FieldTypeInternal.IsValueType) { if (IsNullableType) return null; string msg = "Not value found for the value type field: '" + FieldInfo.Name + "' Class: '" + FieldInfo.DeclaringType.Name + "'. " + Environment.NewLine + "You must use the [FieldNullValue] attribute because this is a value type and can't be null or use a Nullable Type instead of the current type."; throw new NullValueNotFoundException(line, msg); } else return null; } else return NullValue; } /// <summary> /// Get the null value that represent a discarded value /// </summary> /// <returns>null value of discard?</returns> private object GetDiscardedNullValue() { if (NullValue == null) { if (FieldTypeInternal.IsValueType) { if (IsNullableType) return null; string msg = "The field: '" + FieldInfo.Name + "' Class: '" + FieldInfo.DeclaringType.Name + "' is from a value type: " + FieldInfo.FieldType.Name + " and is discarded (null) you must provide a [FieldNullValue] attribute."; throw new BadUsageException(msg); } else return null; } else return NullValue; } #endregion #region " CreateValueForField " /// <summary> /// Convert a field value into a write able value /// </summary> /// <param name="fieldValue">object value to convert</param> /// <returns>converted value</returns> public object CreateValueForField(object fieldValue) { object val = null; if (fieldValue == null) { if (NullValue == null) { if (FieldTypeInternal.IsValueType && Nullable.GetUnderlyingType(FieldTypeInternal) == null) { throw new BadUsageException( "Null Value found. You must specify a FieldNullValueAttribute in the " + FieldInfo.Name + " field of type " + FieldTypeInternal.Name + ", because this is a ValueType."); } else val = null; } else val = NullValue; } else if (FieldTypeInternal == fieldValue.GetType()) val = fieldValue; else { if (this.Converter == null) val = Convert.ChangeType(fieldValue, FieldTypeInternal, null); else { try { if (Nullable.GetUnderlyingType(FieldTypeInternal) != null && Nullable.GetUnderlyingType(FieldTypeInternal) == fieldValue.GetType()) val = fieldValue; else val = Convert.ChangeType(fieldValue, FieldTypeInternal, null); } catch { val = Converter.StringToField(fieldValue.ToString()); } } } return val; } #endregion #endregion #region " AssignToString " /// <summary> /// convert field to string value and assign to a string builder /// buffer for output /// </summary> /// <param name="sb">buffer to collect record</param> /// <param name="fieldValue">value to convert</param> internal void AssignToString(StringBuilder sb, object fieldValue) { if (this.InNewLine == true) sb.Append(StringHelper.NewLine); if (IsArray) { if (fieldValue == null) { if (0 < this.ArrayMinLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array is null, but the minimum length is {1}", FieldInfo.Name, ArrayMinLength)); } return; } var array = (IList) fieldValue; if (array.Count < this.ArrayMinLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array has {1} values, but the minimum length is {2}", FieldInfo.Name, array.Count, ArrayMinLength)); } if (array.Count > this.ArrayMaxLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array has {1} values, but the maximum length is {2}", FieldInfo.Name, array.Count, ArrayMaxLength)); } for (int i = 0; i < array.Count; i++) { object val = array[i]; CreateFieldString(sb, val, IsLast && i == array.Count - 1); } } else CreateFieldString(sb, fieldValue, IsLast); } #endregion /// <summary> /// Copy the field object /// </summary> /// <returns>a complete copy of the Field object</returns> object ICloneable.Clone() { var res = CreateClone(); res.FieldType = FieldType; res.Converter = this.Converter; res.FieldTypeInternal = FieldTypeInternal; res.IsArray = IsArray; res.ArrayType = ArrayType; res.ArrayMinLength = ArrayMinLength; res.ArrayMaxLength = ArrayMaxLength; res.TrailingArray = TrailingArray; res.NullValue = NullValue; res.IsStringField = IsStringField; res.FieldInfo = FieldInfo; res.TrimMode = TrimMode; res.TrimChars = TrimChars; res.IsOptional = IsOptional; //res.NextIsOptional = NextIsOptional; res.InNewLine = InNewLine; res.FieldOrder = FieldOrder; res.IsNullableType = IsNullableType; res.Discarded = Discarded; res.FieldFriendlyName = FieldFriendlyName; res.IsNotEmpty = IsNotEmpty; res.FieldCaption = FieldCaption; res.Parent = Parent; res.ParentIndex = ParentIndex; return res; } /// <summary> /// Add the extra details that derived classes create /// </summary> /// <returns>field clone of right type</returns> protected abstract FieldBase CreateClone(); } }
// 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Resource usage statistics for the job. /// </summary> public partial class JobStatistics : IPropertyMetadata { private readonly long failedTaskCount; private readonly TimeSpan kernelCpuTime; private readonly DateTime lastUpdateTime; private readonly double readIOGiB; private readonly long readIOps; private readonly DateTime startTime; private readonly long succeededTaskCount; private readonly long taskRetryCount; private readonly string url; private readonly TimeSpan userCpuTime; private readonly TimeSpan waitTime; private readonly TimeSpan wallClockTime; private readonly double writeIOGiB; private readonly long writeIOps; #region Constructors internal JobStatistics(Models.JobStatistics protocolObject) { this.failedTaskCount = protocolObject.NumFailedTasks; this.kernelCpuTime = protocolObject.KernelCPUTime; this.lastUpdateTime = protocolObject.LastUpdateTime; this.readIOGiB = protocolObject.ReadIOGiB; this.readIOps = protocolObject.ReadIOps; this.startTime = protocolObject.StartTime; this.succeededTaskCount = protocolObject.NumSucceededTasks; this.taskRetryCount = protocolObject.NumTaskRetries; this.url = protocolObject.Url; this.userCpuTime = protocolObject.UserCPUTime; this.waitTime = protocolObject.WaitTime; this.wallClockTime = protocolObject.WallClockTime; this.writeIOGiB = protocolObject.WriteIOGiB; this.writeIOps = protocolObject.WriteIOps; } #endregion Constructors #region JobStatistics /// <summary> /// Gets the total number of task failures in the job. /// </summary> public long FailedTaskCount { get { return this.failedTaskCount; } } /// <summary> /// Gets the total kernel mode CPU time (per core) consumed by all tasks in the job. /// </summary> public TimeSpan KernelCpuTime { get { return this.kernelCpuTime; } } /// <summary> /// Gets the time at which the statistics were last updated. All statistics are limited to the range between <see /// cref="StartTime"/> and this value. /// </summary> public DateTime LastUpdateTime { get { return this.lastUpdateTime; } } /// <summary> /// Gets the total gibibytes of I/O read from disk by all tasks in the job. /// </summary> public double ReadIOGiB { get { return this.readIOGiB; } } /// <summary> /// Gets the total number of disk read operations made by all tasks in the job. /// </summary> public long ReadIOps { get { return this.readIOps; } } /// <summary> /// Gets the start time of the time range covered by the statistics. /// </summary> public DateTime StartTime { get { return this.startTime; } } /// <summary> /// Gets the total number of tasks successfully completed in the job during the given time range. /// </summary> public long SucceededTaskCount { get { return this.succeededTaskCount; } } /// <summary> /// Gets the total number of task retries in the job. /// </summary> public long TaskRetryCount { get { return this.taskRetryCount; } } /// <summary> /// Gets the URL of the job statistics. /// </summary> public string Url { get { return this.url; } } /// <summary> /// Gets the total user mode CPU time (per core) consumed by all tasks in the job. /// </summary> public TimeSpan UserCpuTime { get { return this.userCpuTime; } } /// <summary> /// Gets the total wait time of all tasks in the job. The wait time for a task is defined as the elapsed time between /// the creation of the task and the start of task execution. (If the task is retried due to failures, the wait time /// is the time to the most recent task execution.) /// </summary> /// <remarks> /// This value is only reported in the account lifetime statistics. /// </remarks> public TimeSpan WaitTime { get { return this.waitTime; } } /// <summary> /// Gets the total elapsed time. /// </summary> public TimeSpan WallClockTime { get { return this.wallClockTime; } } /// <summary> /// Gets the total gibibytes of I/O written to disk by all tasks in the job. /// </summary> public double WriteIOGiB { get { return this.writeIOGiB; } } /// <summary> /// Gets the total number of disk write operations made by all tasks in the job. /// </summary> public long WriteIOps { get { return this.writeIOps; } } #endregion // JobStatistics #region IPropertyMetadata bool IModifiable.HasBeenModified { //This class is compile time readonly so it cannot have been modified get { return false; } } bool IReadOnly.IsReadOnly { get { return true; } set { // This class is compile time readonly already } } #endregion // IPropertyMetadata } }
// 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.Text; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; using System.Security.Cryptography; using System.Runtime.InteropServices; namespace Internal.NativeCrypto { internal static partial class BCryptNative { /// <summary> /// Well known algorithm names /// </summary> internal static class AlgorithmName { public const string ECDHP256 = "ECDH_P256"; // BCRYPT_ECDH_P256_ALGORITHM public const string ECDHP384 = "ECDH_P384"; // BCRYPT_ECDH_P384_ALGORITHM public const string ECDHP521 = "ECDH_P521"; // BCRYPT_ECDH_P521_ALGORITHM public const string ECDsaP256 = "ECDSA_P256"; // BCRYPT_ECDSA_P256_ALGORITHM public const string ECDsaP384 = "ECDSA_P384"; // BCRYPT_ECDSA_P384_ALGORITHM public const string ECDsaP521 = "ECDSA_P521"; // BCRYPT_ECDSA_P521_ALGORITHM public const string MD5 = "MD5"; // BCRYPT_MD5_ALGORITHM public const string Sha1 = "SHA1"; // BCRYPT_SHA1_ALGORITHM public const string Sha256 = "SHA256"; // BCRYPT_SHA256_ALGORITHM public const string Sha384 = "SHA384"; // BCRYPT_SHA384_ALGORITHM public const string Sha512 = "SHA512"; // BCRYPT_SHA512_ALGORITHM } /// <summary> /// Magic numbers identifying blob types /// </summary> internal enum KeyBlobMagicNumber { ECDHPublicP256 = 0x314B4345, // BCRYPT_ECDH_PUBLIC_P256_MAGIC ECDHPublicP384 = 0x334B4345, // BCRYPT_ECDH_PUBLIC_P384_MAGIC ECDHPublicP521 = 0x354B4345, // BCRYPT_ECDH_PUBLIC_P521_MAGIC ECDsaPublicP256 = 0x31534345, // BCRYPT_ECDSA_PUBLIC_P256_MAGIC ECDsaPublicP384 = 0x33534345, // BCRYPT_ECDSA_PUBLIC_P384_MAGIC ECDsaPublicP521 = 0x35534345 // BCRYPT_ECDSA_PUBLIC_P521_MAGIC } internal static class KeyDerivationFunction { public const string Hash = "HASH"; // BCRYPT_KDF_HASH public const string Hmac = "HMAC"; // BCRYPT_KDF_HMAC public const string Tls = "TLS_PRF"; // BCRYPT_KDF_TLS_PRF } } // // Interop layer around Windows CNG api. // internal static partial class Cng { public const String CngDll = "BCrypt.dll"; public const String Capi2Dll = "Crypt32.dll"; [Flags] public enum OpenAlgorithmProviderFlags : int { NONE = 0x00000000, BCRYPT_ALG_HANDLE_HMAC_FLAG = 0x00000008, } public const String BCRYPT_AES_ALGORITHM = "AES"; public static SafeAlgorithmHandle BCryptOpenAlgorithmProvider(String pszAlgId, String pszImplementation, OpenAlgorithmProviderFlags dwFlags) { SafeAlgorithmHandle hAlgorithm = null; NTSTATUS ntStatus = Interop.BCryptOpenAlgorithmProvider(out hAlgorithm, pszAlgId, pszImplementation, (int)dwFlags); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return hAlgorithm; } public static SafeHashHandle BCryptCreateHash(this SafeAlgorithmHandle hAlgorithm, byte[] pbSecret, int dwFlags) { SafeHashHandle hHash = null; NTSTATUS ntStatus = Interop.BCryptCreateHash(hAlgorithm, out hHash, IntPtr.Zero, 0, pbSecret, pbSecret == null ? 0 : pbSecret.Length, dwFlags); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return hHash; } public static SafeHashHandle BCryptTryCreateReusableHash(this SafeAlgorithmHandle hAlgorithm, byte[] pbSecret) { const int BCRYPT_HASH_REUSABLE_FLAG = 0x00000020; SafeHashHandle hHash = null; NTSTATUS ntStatus = Interop.BCryptCreateHash(hAlgorithm, out hHash, IntPtr.Zero, 0, pbSecret, pbSecret == null ? 0 : pbSecret.Length, BCRYPT_HASH_REUSABLE_FLAG); if (ntStatus == NTSTATUS.STATUS_INVALID_PARAMETER) return null; // Pre-Win8 OS's do not support BCRYPT_HASH_REUSABLE_FLAG. if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return hHash; } public static unsafe void BCryptHashData(this SafeHashHandle hHash, byte* pbInput, int cbInput) { NTSTATUS ntStatus = Interop.BCryptHashData(hHash, pbInput, cbInput, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return; } public static byte[] BCryptFinishHash(this SafeHashHandle hHash, int cbHashSize) { byte[] hash = new byte[cbHashSize]; NTSTATUS ntStatus = Interop.BCryptFinishHash(hHash, hash, cbHashSize, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return hash; } public static int GetHashSizeInBytes(this SafeHashHandle hHash) { unsafe { int cbSizeOfHashSize; int hashSize; NTSTATUS ntStatus = Interop.BCryptGetProperty(hHash, BCryptGetPropertyStrings.BCRYPT_HASH_LENGTH, (byte*)&hashSize, 4, out cbSizeOfHashSize, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return hashSize; } } public static void BCryptGenRandom(byte[] buffer) { const int BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002; NTSTATUS ntStatus = Interop.BCryptGenRandom(IntPtr.Zero, buffer, buffer.Length, BCRYPT_USE_SYSTEM_PREFERRED_RNG); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); } public static SafeKeyHandle BCryptImportKey(this SafeAlgorithmHandle hAlg, byte[] key) { unsafe { const String BCRYPT_KEY_DATA_BLOB = "KeyDataBlob"; int keySize = key.Length; int blobSize = sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + keySize; byte[] blob = new byte[blobSize]; fixed (byte* pbBlob = blob) { BCRYPT_KEY_DATA_BLOB_HEADER* pBlob = (BCRYPT_KEY_DATA_BLOB_HEADER*)pbBlob; pBlob->dwMagic = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_MAGIC; pBlob->dwVersion = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_VERSION1; pBlob->cbKeyData = (uint)keySize; } Buffer.BlockCopy(key, 0, blob, sizeof(BCRYPT_KEY_DATA_BLOB_HEADER), keySize); SafeKeyHandle hKey; NTSTATUS ntStatus = Interop.BCryptImportKey(hAlg, IntPtr.Zero, BCRYPT_KEY_DATA_BLOB, out hKey, IntPtr.Zero, 0, blob, blobSize, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return hKey; } } [StructLayout(LayoutKind.Sequential)] private struct BCRYPT_KEY_DATA_BLOB_HEADER { public UInt32 dwMagic; public UInt32 dwVersion; public UInt32 cbKeyData; public const UInt32 BCRYPT_KEY_DATA_BLOB_MAGIC = 0x4d42444b; public const UInt32 BCRYPT_KEY_DATA_BLOB_VERSION1 = 0x1; } public static void SetCipherMode(this SafeKeyHandle hKey, CipherMode cipherMode) { String cipherModePropertyName; switch (cipherMode) { case CipherMode.CBC: cipherModePropertyName = "ChainingModeCBC"; break; case CipherMode.CTS: throw new NotSupportedException(); case CipherMode.ECB: cipherModePropertyName = "ChainingModeECB"; break; default: throw new NotSupportedException(); } NTSTATUS ntStatus = Interop.BCryptSetProperty(hKey, "ChainingMode", cipherModePropertyName, (cipherModePropertyName.Length + 1) * 2, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return; } // Note: input and output are allowed to be the same buffer. BCryptEncrypt will correctly do the encryption in place according to CNG documentation. public static int BCryptEncrypt(this SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[] iv, byte[] output, int outputOffset, int outputCount) { Debug.Assert(input != null); Debug.Assert(inputOffset >= 0); Debug.Assert(inputCount >= 0); Debug.Assert(inputCount <= input.Length - inputOffset); Debug.Assert(output != null); Debug.Assert(outputOffset >= 0); Debug.Assert(outputCount >= 0); Debug.Assert(outputCount <= output.Length - outputOffset); unsafe { fixed (byte* pbInput = input) { fixed (byte* pbOutput = output) { int cbResult; NTSTATUS ntStatus = Interop.BCryptEncrypt(hKey, pbInput + inputOffset, inputCount, IntPtr.Zero, iv, iv == null ? 0 : iv.Length, pbOutput + outputOffset, outputCount, out cbResult, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return cbResult; } } } } // Note: input and output are allowed to be the same buffer. BCryptDecrypt will correctly do the decryption in place according to CNG documentation. public static int BCryptDecrypt(this SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[] iv, byte[] output, int outputOffset, int outputCount) { Debug.Assert(input != null); Debug.Assert(inputOffset >= 0); Debug.Assert(inputCount >= 0); Debug.Assert(inputCount <= input.Length - inputOffset); Debug.Assert(output != null); Debug.Assert(outputOffset >= 0); Debug.Assert(outputCount >= 0); Debug.Assert(outputCount <= output.Length - outputOffset); unsafe { fixed (byte* pbInput = input) { fixed (byte* pbOutput = output) { int cbResult; NTSTATUS ntStatus = Interop.BCryptDecrypt(hKey, pbInput + inputOffset, inputCount, IntPtr.Zero, iv, iv == null ? 0 : iv.Length, pbOutput + outputOffset, outputCount, out cbResult, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return cbResult; } } } } private static class BCryptGetPropertyStrings { public const String BCRYPT_HASH_LENGTH = "HashDigestLength"; } public static String CryptFormatObject(String oidValue, byte[] rawData, bool multiLine) { const int X509_ASN_ENCODING = 0x00000001; const int CRYPT_FORMAT_STR_MULTI_LINE = 0x00000001; int dwFormatStrType = multiLine ? CRYPT_FORMAT_STR_MULTI_LINE : 0; int cbFormat = 0; if (!Interop.CryptFormatObject(X509_ASN_ENCODING, 0, dwFormatStrType, IntPtr.Zero, oidValue, rawData, rawData.Length, null, ref cbFormat)) return null; StringBuilder sb = new StringBuilder((cbFormat + 1) / 2); if (!Interop.CryptFormatObject(X509_ASN_ENCODING, 0, dwFormatStrType, IntPtr.Zero, oidValue, rawData, rawData.Length, sb, ref cbFormat)) return null; return sb.ToString(); } private enum NTSTATUS : uint { STATUS_SUCCESS = 0x0, STATUS_NOT_FOUND = 0xc0000225, STATUS_INVALID_PARAMETER = 0xc000000d, STATUS_NO_MEMORY = 0xc0000017, } private static Exception CreateCryptographicException(NTSTATUS ntStatus) { int hr = ((int)ntStatus) | 0x01000000; return new CryptographicException(hr); } } internal static partial class Cng { private static class Interop { [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern NTSTATUS BCryptOpenAlgorithmProvider(out SafeAlgorithmHandle phAlgorithm, String pszAlgId, String pszImplementation, int dwFlags); [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern NTSTATUS BCryptCreateHash(SafeAlgorithmHandle hAlgorithm, out SafeHashHandle phHash, IntPtr pbHashObject, int cbHashObject, [In, Out] byte[] pbSecret, int cbSecret, int dwFlags); [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern unsafe NTSTATUS BCryptHashData(SafeHashHandle hHash, byte* pbInput, int cbInput, int dwFlags); [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern NTSTATUS BCryptFinishHash(SafeHashHandle hHash, [Out] byte[] pbOutput, int cbOutput, int dwFlags); [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern unsafe NTSTATUS BCryptGetProperty(SafeBCryptHandle hObject, String pszProperty, byte* pbOutput, int cbOutput, out int pcbResult, int dwFlags); [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern unsafe NTSTATUS BCryptSetProperty(SafeBCryptHandle hObject, String pszProperty, String pbInput, int cbInput, int dwFlags); [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern NTSTATUS BCryptGenRandom(IntPtr hAlgorithm, [In, Out] byte[] pbBuffer, int cbBuffer, int dwFlags); [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern NTSTATUS BCryptImportKey(SafeAlgorithmHandle hAlgorithm, IntPtr hImportKey, String pszBlobType, out SafeKeyHandle hKey, IntPtr pbKeyObject, int cbKeyObject, byte[] pbInput, int cbInput, int dwFlags); [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern unsafe NTSTATUS BCryptEncrypt(SafeKeyHandle hKey, byte* pbInput, int cbInput, IntPtr paddingInfo, [In,Out] byte [] pbIV, int cbIV, byte* pbOutput, int cbOutput, out int cbResult, int dwFlags); [DllImport(CngDll, CharSet = CharSet.Unicode)] public static extern unsafe NTSTATUS BCryptDecrypt(SafeKeyHandle hKey, byte* pbInput, int cbInput, IntPtr paddingInfo, [In, Out] byte[] pbIV, int cbIV, byte* pbOutput, int cbOutput, out int cbResult, int dwFlags); [DllImport(Capi2Dll, CharSet = CharSet.Ansi, SetLastError = true, BestFitMapping = false)] public static extern bool CryptFormatObject( [In] int dwCertEncodingType, // only valid value is X509_ASN_ENCODING [In] int dwFormatType, // unused - pass 0. [In] int dwFormatStrType, // select multiline [In] IntPtr pFormatStruct, // unused - pass IntPtr.Zero [MarshalAs(UnmanagedType.LPStr)] [In] String lpszStructType, // OID value [In] byte[] pbEncoded, // Data to be formatted [In] int cbEncoded, // Length of data to be formatted [MarshalAs(UnmanagedType.LPWStr)] [In, Out] StringBuilder pbFormat, // Receives formatted string. [In, Out] ref int pcbFormat); // Sends/receives length of formatted String. } } internal abstract class SafeBCryptHandle : SafeHandle { public SafeBCryptHandle() : base(IntPtr.Zero, true) { } public sealed override bool IsInvalid { get { return handle == IntPtr.Zero; } } } internal sealed class SafeAlgorithmHandle : SafeBCryptHandle { protected sealed override bool ReleaseHandle() { uint ntStatus = BCryptCloseAlgorithmProvider(handle, 0); return ntStatus == 0; } [DllImport(Cng.CngDll)] private static extern uint BCryptCloseAlgorithmProvider(IntPtr hAlgorithm, int dwFlags); } internal sealed class SafeHashHandle : SafeBCryptHandle { protected sealed override bool ReleaseHandle() { uint ntStatus = BCryptDestroyHash(handle); return ntStatus == 0; } [DllImport(Cng.CngDll)] private static extern uint BCryptDestroyHash(IntPtr hHash); } internal sealed class SafeKeyHandle : SafeBCryptHandle { protected sealed override bool ReleaseHandle() { uint ntStatus = BCryptDestroyKey(handle); return ntStatus == 0; } [DllImport(Cng.CngDll)] private static extern uint BCryptDestroyKey(IntPtr hKey); } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Provisioning.OnPrem.AsyncWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Xaml.Xaml File: LogControl.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Xaml { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Windows; using System.Windows.Data; using System.Windows.Controls; using Ecng.Common; using Ecng.Serialization; using Ecng.Xaml; using StockSharp.Logging; /// <summary> /// The graphical component for logs displaying. /// </summary> public partial class LogControl : ILogListener { /// <summary> /// Initializes a new instance of the <see cref="LogControl"/>. /// </summary> public LogControl() { InitializeComponent(); Messages = new LogMessageCollection { MaxCount = LogMessageCollection.DefaultMaxItemsCount }; MessageGrid.SelectionMode = DataGridSelectionMode.Extended; } #region Dependency properties /// <summary> /// <see cref="DependencyProperty"/> for <see cref="AutoScroll"/>. /// </summary> public static readonly DependencyProperty AutoScrollProperty = DependencyProperty.Register(nameof(AutoScroll), typeof(bool), typeof(LogControl), new PropertyMetadata(false, AutoScrollChanged)); private static void AutoScrollChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctrl = d.FindLogicalChild<LogControl>(); var autoScroll = (bool)e.NewValue; ctrl._autoScroll = autoScroll; } private bool _autoScroll; /// <summary> /// Automatically to scroll control on the last row added. The default is off. /// </summary> public bool AutoScroll { get { return _autoScroll; } set { SetValue(AutoScrollProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="AutoResize"/>. /// </summary> public static readonly DependencyProperty AutoResizeProperty = DependencyProperty.Register(nameof(AutoResize), typeof(bool), typeof(LogControl), new PropertyMetadata(false, AutoResizeChanged)); private static void AutoResizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctrl = d.FindLogicalChild<LogControl>(); var autoResize = (bool)e.NewValue; ctrl.SetColumnsWidth(autoResize); } /// <summary> /// Automatically to align the width of the columns by content. The default is off. /// </summary> public bool AutoResize { get { return (bool)GetValue(AutoResizeProperty); } set { SetValue(AutoResizeProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="MaxItemsCount"/>. /// </summary> public static readonly DependencyProperty MaxItemsCountProperty = DependencyProperty.Register(nameof(MaxItemsCount), typeof(int), typeof(LogControl), new PropertyMetadata(LogMessageCollection.DefaultMaxItemsCount, MaxItemsCountChanged)); private static void MaxItemsCountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.FindLogicalChild<LogControl>()._messages.MaxCount = (int)e.NewValue; } /// <summary> /// The maximum number of entries to display. The -1 value means an unlimited amount of records. By default, the last 10000 records for 64-bit process and 1000 records for 32-bit process are displayed. /// </summary> public int MaxItemsCount { get { return _messages.MaxCount; } set { SetValue(MaxItemsCountProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="ShowSourceNameColumn"/>. /// </summary> public static readonly DependencyProperty ShowSourceNameColumnProperty = DependencyProperty.Register(nameof(ShowSourceNameColumn), typeof(bool), typeof(LogControl), new PropertyMetadata(true, ShowSourceNameColumnChanged)); private static void ShowSourceNameColumnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.FindLogicalChild<LogControl>().MessageGrid.Columns[0].Visibility = (bool)e.NewValue ? Visibility.Visible : Visibility.Collapsed; } /// <summary> /// To show the column with the source name. Enabled by default. /// </summary> public bool ShowSourceNameColumn { get { return (bool)GetValue(ShowSourceNameColumnProperty); } set { SetValue(ShowSourceNameColumnProperty, value); } } private const string _defaultTimeFormat = "yy/MM/dd HH:mm:ss.fff"; /// <summary> /// <see cref="DependencyProperty"/> for <see cref="LogControl.TimeFormat"/>. /// </summary> public static readonly DependencyProperty TimeFormatProperty = DependencyProperty.Register(nameof(TimeFormat), typeof(string), typeof(LogControl), new PropertyMetadata(_defaultTimeFormat, TimeFormatChanged)); private static void TimeFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctrl = (LogControl)d; var timeFormat = (string)e.NewValue; if (timeFormat.IsEmpty()) throw new ArgumentNullException(); ctrl._timeFormat = timeFormat; } private string _timeFormat = _defaultTimeFormat; /// <summary> /// Format for conversion time into a string. The default format is yy/MM/dd HH:mm:ss.fff. /// </summary> public string TimeFormat { get { return _timeFormat; } set { SetValue(TimeFormatProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="LogControl.ShowError"/>. /// </summary> public static readonly DependencyProperty ShowErrorProperty = DependencyProperty.Register(nameof(ShowError), typeof(bool), typeof(LogControl), new PropertyMetadata(true, ShowChanged)); private bool _showError = true; /// <summary> /// To show messages of type <see cref="LogLevels.Error"/>. Enabled by default. /// </summary> public bool ShowError { get { return _showError; } set { SetValue(ShowErrorProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="LogControl.ShowWarning"/>. /// </summary> public static readonly DependencyProperty ShowWarningProperty = DependencyProperty.Register(nameof(ShowWarning), typeof(bool), typeof(LogControl), new PropertyMetadata(true, ShowChanged)); private bool _showWarning = true; /// <summary> /// To show messages of type <see cref="LogLevels.Warning"/>. Enabled by default. /// </summary> public bool ShowWarning { get { return _showWarning; } set { SetValue(ShowWarningProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="LogControl.ShowInfo"/>. /// </summary> public static readonly DependencyProperty ShowInfoProperty = DependencyProperty.Register(nameof(ShowInfo), typeof(bool), typeof(LogControl), new PropertyMetadata(true, ShowChanged)); private bool _showInfo = true; /// <summary> /// To show messages of type <see cref="LogLevels.Info"/>. Enabled by default. /// </summary> public bool ShowInfo { get { return _showInfo; } set { SetValue(ShowInfoProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="LogControl.ShowDebug"/>. /// </summary> public static readonly DependencyProperty ShowDebugProperty = DependencyProperty.Register(nameof(ShowDebug), typeof(bool), typeof(LogControl), new PropertyMetadata(true, ShowChanged)); private bool _showDebug = true; /// <summary> /// To show messages of type <see cref="LogLevels.Debug"/>. Enabled by default. /// </summary> public bool ShowDebug { get { return _showDebug; } set { SetValue(ShowDebugProperty, value); } } private static void ShowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctrl = d.FindLogicalChild<LogControl>(); var newValue = (bool)e.NewValue; if (e.Property == ShowDebugProperty) ctrl._showDebug = newValue; else if (e.Property == ShowErrorProperty) ctrl._showError = newValue; else if (e.Property == ShowInfoProperty) ctrl._showInfo = newValue; else if (e.Property == ShowWarningProperty) ctrl._showWarning = newValue; ctrl._view?.Refresh(); } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="Messages"/>. /// </summary> public static readonly DependencyProperty MessagesProperty = DependencyProperty.Register(nameof(Messages), typeof(LogMessageCollection), typeof(LogControl), new PropertyMetadata(null, MessagesChanged)); /// <summary> /// The log entries collection. /// </summary> public LogMessageCollection Messages { get { return _messages; } set { SetValue(MessagesProperty, value); } } private static void MessagesChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { var ctrl = (LogControl)sender; var value = (LogMessageCollection)args.NewValue; ctrl.SetMessagesCollection(value); } #endregion #region Attached properties /// <summary> /// <see cref="DependencyProperty"/> for <see cref="AutoScroll"/>. /// </summary> public static readonly DependencyProperty LogAutoScrollProperty = DependencyProperty.RegisterAttached("Log" + nameof(AutoScroll), typeof(bool), typeof(LogControl), new PropertyMetadata(false, AutoScrollChanged)); /// <summary> /// To set the value for <see cref="AutoScroll"/>. /// </summary> /// <param name="element">Object <see cref="LogControl"/>.</param> /// <param name="value">New value for <see cref="AutoScroll"/>.</param> public static void SetLogAutoScroll(UIElement element, bool value) { element.SetValue(LogAutoScrollProperty, value); } /// <summary> /// To get the value for <see cref="AutoScroll"/>. /// </summary> /// <param name="element">Object <see cref="LogControl"/>.</param> /// <returns>The value of <see cref="AutoScroll"/>.</returns> public static bool GetLogAutoScroll(UIElement element) { return (bool)element.GetValue(LogAutoScrollProperty); } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="AutoResize"/>. /// </summary> public static readonly DependencyProperty LogAutoResizeProperty = DependencyProperty.Register("Log" + nameof(AutoResize), typeof(bool), typeof(LogControl), new PropertyMetadata(false, AutoResizeChanged)); /// <summary> /// To set the value for <see cref="AutoResize"/>. /// </summary> /// <param name="element">Object <see cref="LogControl"/>.</param> /// <param name="value">New value for <see cref="AutoResize"/>.</param> public static void SetLogAutoResize(UIElement element, bool value) { element.SetValue(LogAutoResizeProperty, value); } /// <summary> /// To get the value for <see cref="AutoResize"/>. /// </summary> /// <param name="element">Object <see cref="LogControl"/>.</param> /// <returns>The value of <see cref="AutoResize"/>.</returns> public static bool GetLogAutoResize(UIElement element) { return (bool)element.GetValue(LogAutoResizeProperty); } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="MaxItemsCount"/>. /// </summary> public static readonly DependencyProperty LogMaxItemsCountProperty = DependencyProperty.RegisterAttached("Log" + nameof(MaxItemsCount), typeof(int), typeof(LogControl), new PropertyMetadata(LogMessageCollection.DefaultMaxItemsCount, MaxItemsCountChanged)); /// <summary> /// To set the value for <see cref="MaxItemsCount"/>. /// </summary> /// <param name="element">Object <see cref="LogControl"/>.</param> /// <param name="value">New value for <see cref="MaxItemsCount"/>.</param> public static void SetLogMaxItemsCount(UIElement element, int value) { element.SetValue(LogMaxItemsCountProperty, value); } /// <summary> /// To get the value for <see cref="MaxItemsCount"/>. /// </summary> /// <param name="element">Object <see cref="LogControl"/>.</param> /// <returns>The value of <see cref="MaxItemsCount"/>.</returns> public static int GetLogMaxItemsCount(UIElement element) { return (int)element.GetValue(LogMaxItemsCountProperty); } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="ShowSourceNameColumn"/>. /// </summary> public static readonly DependencyProperty LogShowSourceNameColumnProperty = DependencyProperty.RegisterAttached("Log" + nameof(ShowSourceNameColumn), typeof(bool), typeof(LogControl), new PropertyMetadata(ShowSourceNameColumnChanged)); /// <summary> /// To set the value for <see cref="ShowSourceNameColumn"/>. /// </summary> /// <param name="element">Object <see cref="LogControl"/>.</param> /// <param name="value">New value for <see cref="ShowSourceNameColumn"/>.</param> public static void SetLogShowSourceNameColumn(UIElement element, bool value) { element.SetValue(LogShowSourceNameColumnProperty, value); } /// <summary> /// To get the value for <see cref="ShowSourceNameColumn"/>. /// </summary> /// <param name="element">Object <see cref="LogControl"/>.</param> /// <returns>The value of <see cref="ShowSourceNameColumn"/>.</returns> public static bool GetLogShowSourceNameColumn(UIElement element) { return (bool)element.GetValue(LogShowSourceNameColumnProperty); } #endregion private LogMessageCollection _messages; private ICollectionView _view; private void SetMessagesCollection(LogMessageCollection value) { if (value == null) throw new ArgumentNullException(); if (_messages != null) ((INotifyCollectionChanged)_messages.Items).CollectionChanged -= MessagesCollectionChanged; if (_view != null) _view.Filter = null; _messages = value; ((INotifyCollectionChanged)_messages.Items).CollectionChanged += MessagesCollectionChanged; _view = CollectionViewSource.GetDefaultView(_messages.Items); _view.Filter = MessageFilter; MessageGrid.ItemsSource = _messages.Items; TryScroll(); } private bool MessageFilter(object obj) { var message = obj as LogMessage; if (message != null) { switch (message.Level) { case LogLevels.Debug: return ShowDebug; case LogLevels.Info: return ShowInfo; case LogLevels.Warning: return ShowWarning; case LogLevels.Error: return ShowError; } } return false; } private void SetColumnsWidth(bool auto) { foreach (var column in MessageGrid.Columns) { column.Width = auto ? DataGridLength.Auto : column.ActualWidth; } } private void MessagesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { TryScroll(); } private void TryScroll() { if (!AutoScroll || _messages == null || _messages.Count <= 0 || Visibility != Visibility.Visible) return; var scroll = MessageGrid.FindVisualChild<ScrollViewer>(); scroll?.ScrollToEnd(); } void ILogListener.WriteMessages(IEnumerable<LogMessage> messages) { if (messages == null) throw new ArgumentNullException(nameof(messages)); _messages.AddRange(messages); } #region Implementation of IPersistable /// <summary> /// Load settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Load(SettingsStorage storage) { AutoScroll = storage.GetValue(nameof(AutoScroll), false); AutoResize = storage.GetValue(nameof(AutoResize), false); ShowSourceNameColumn = storage.GetValue(nameof(ShowSourceNameColumn), true); MaxItemsCount = storage.GetValue(nameof(MaxItemsCount), LogMessageCollection.DefaultMaxItemsCount); TimeFormat = storage.GetValue(nameof(TimeFormat), _defaultTimeFormat); ShowInfo = storage.GetValue(nameof(ShowInfo), true); ShowError = storage.GetValue(nameof(ShowError), true); ShowWarning = storage.GetValue(nameof(ShowWarning), true); ShowDebug = storage.GetValue(nameof(ShowDebug), true); } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Save(SettingsStorage storage) { storage.SetValue(nameof(AutoScroll), AutoScroll); storage.SetValue(nameof(AutoResize), AutoResize); storage.SetValue(nameof(ShowSourceNameColumn), ShowSourceNameColumn); storage.SetValue(nameof(MaxItemsCount), MaxItemsCount); storage.SetValue(nameof(TimeFormat), TimeFormat); storage.SetValue(nameof(ShowInfo), ShowInfo); storage.SetValue(nameof(ShowError), ShowError); storage.SetValue(nameof(ShowWarning), ShowWarning); storage.SetValue(nameof(ShowDebug), ShowDebug); } #endregion void IDisposable.Dispose() { } } }
using System; using System.Linq; using ClosedXML.Excel; namespace ClosedXML_Examples.Misc { public class SortExample : IXLExample { #region Variables // Public // Private #endregion #region Properties // Public // Private // Override #endregion #region Events // Public // Private // Override #endregion #region Methods // Public public void Create(String filePath) { var wb = new XLWorkbook(); #region Sort a table var wsTable = wb.Worksheets.Add("Table"); AddTestTable(wsTable); var header = wsTable.Row(1).InsertRowsAbove(1).First(); for(Int32 co = 1; co <= wsTable.LastColumnUsed().ColumnNumber(); co++) { header.Cell(co).Value = "Column" + co.ToString(); } var rangeTable = wsTable.RangeUsed(); var table = rangeTable.CopyTo(wsTable.Column(wsTable.LastColumnUsed().ColumnNumber() + 3)).CreateTable(); table.Sort("Column2, Column3 Desc, Column1 ASC"); wsTable.Row(1).InsertRowsAbove(2); wsTable.Cell(1, 1) .SetValue(".Sort(\"Column2, Column3 Desc, Column1 ASC\") = Sort table Top to Bottom, Col 2 Asc, Col 3 Desc, Col 1 Asc, Ignore Blanks, Ignore Case") .Style.Font.SetBold(); #endregion #region Sort a simple range left to right var wsLeftToRight = wb.Worksheets.Add("Sort Left to Right"); AddTestTable(wsLeftToRight); wsLeftToRight.RangeUsed().Transpose(XLTransposeOptions.MoveCells); var rangeLeftToRight = wsLeftToRight.RangeUsed(); var copyLeftToRight = rangeLeftToRight.CopyTo(wsLeftToRight.Row(wsLeftToRight.LastRowUsed().RowNumber() + 3)); copyLeftToRight.SortLeftToRight(); wsLeftToRight.Row(1).InsertRowsAbove(2); wsLeftToRight.Cell(1, 1) .SetValue(".SortLeftToRight() = Sort Range Left to Right, Ascendingly, Ignore Blanks, Ignore Case") .Style.Font.SetBold(); #endregion #region Sort a range var wsComplex2 = wb.Worksheets.Add("Complex 2"); AddTestTable(wsComplex2); var rangeComplex2 = wsComplex2.RangeUsed(); var copyComplex2 = rangeComplex2.CopyTo(wsComplex2.Column(wsComplex2.LastColumnUsed().ColumnNumber() + 3)); copyComplex2.SortColumns.Add(1, XLSortOrder.Ascending, false, true); copyComplex2.SortColumns.Add(3, XLSortOrder.Descending); copyComplex2.Sort(); wsComplex2.Row(1).InsertRowsAbove(4); wsComplex2.Cell(1, 1) .SetValue(".SortColumns.Add(1, XLSortOrder.Ascending, false, true) = Sort Col 1 Asc, Match Blanks, Match Case").Style.Font.SetBold(); wsComplex2.Cell(2, 1) .SetValue(".SortColumns.Add(3, XLSortOrder.Descending) = Sort Col 3 Desc, Ignore Blanks, Ignore Case").Style.Font.SetBold(); wsComplex2.Cell(3, 1) .SetValue(".Sort() = Sort range using the parameters defined in SortColumns").Style.Font.SetBold(); #endregion #region Sort a range var wsComplex1 = wb.Worksheets.Add("Complex 1"); AddTestTable(wsComplex1); var rangeComplex1 = wsComplex1.RangeUsed(); var copyComplex1 = rangeComplex1.CopyTo(wsComplex1.Column(wsComplex1.LastColumnUsed().ColumnNumber() + 3)); copyComplex1.Sort("2, 1 DESC", XLSortOrder.Ascending, true); wsComplex1.Row(1).InsertRowsAbove(2); wsComplex1.Cell(1, 1) .SetValue(".Sort(\"2, 1 DESC\", XLSortOrder.Ascending, true) = Sort Range Top to Bottom, Col 2 Asc, Col 1 Desc, Ignore Blanks, Match Case").Style.Font.SetBold(); #endregion #region Sort a simple column var wsSimpleColumn = wb.Worksheets.Add("Simple Column"); AddTestColumn(wsSimpleColumn); var rangeSimpleColumn = wsSimpleColumn.RangeUsed(); var copySimpleColumn = rangeSimpleColumn.CopyTo(wsSimpleColumn.Column(wsSimpleColumn.LastColumnUsed().ColumnNumber() + 3)); copySimpleColumn.FirstColumn().Sort(XLSortOrder.Descending, true); wsSimpleColumn.Row(1).InsertRowsAbove(2); wsSimpleColumn.Cell(1, 1) .SetValue(".Sort(XLSortOrder.Descending, true) = Sort Range Top to Bottom, Descendingly, Ignore Blanks, Match Case").Style.Font.SetBold(); #endregion #region Sort a simple range var wsSimple = wb.Worksheets.Add("Simple"); AddTestTable(wsSimple); var rangeSimple = wsSimple.RangeUsed(); var copySimple = rangeSimple.CopyTo(wsSimple.Column(wsSimple.LastColumnUsed().ColumnNumber() + 3)); copySimple.Sort(); wsSimple.Row(1).InsertRowsAbove(2); wsSimple.Cell(1, 1).SetValue(".Sort() = Sort Range Top to Bottom, Ascendingly, Ignore Blanks, Ignore Case").Style.Font.SetBold(); #endregion wb.SaveAs(filePath); } private void AddTestColumnMixed(IXLWorksheet ws) { ws.Cell("A1").SetValue(new DateTime(2011, 1, 30)).Style.Fill.SetBackgroundColor(XLColor.LightGreen); ws.Cell("A2").SetValue(1.15).Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise); ws.Cell("A3").SetValue(new TimeSpan(1, 1, 12, 30)).Style.Fill.SetBackgroundColor(XLColor.BurlyWood); ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray); ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon); ws.Cell("A6").SetValue(9).Style.Fill.SetBackgroundColor(XLColor.DodgerBlue); ws.Cell("A7").SetValue(new TimeSpan(9, 4, 30)).Style.Fill.SetBackgroundColor(XLColor.IndianRed); ws.Cell("A8").SetValue(new DateTime(2011, 4, 15)).Style.Fill.SetBackgroundColor(XLColor.DeepPink); } private void AddTestColumnNumbers(IXLWorksheet ws) { ws.Cell("A1").SetValue(1.30).Style.Fill.SetBackgroundColor(XLColor.LightGreen); ws.Cell("A2").SetValue(1.15).Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise); ws.Cell("A3").SetValue(1230).Style.Fill.SetBackgroundColor(XLColor.BurlyWood); ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray); ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon); ws.Cell("A6").SetValue(9).Style.Fill.SetBackgroundColor(XLColor.DodgerBlue); ws.Cell("A7").SetValue(4.30).Style.Fill.SetBackgroundColor(XLColor.IndianRed); ws.Cell("A8").SetValue(4.15).Style.Fill.SetBackgroundColor(XLColor.DeepPink); } private void AddTestColumnTimeSpans(IXLWorksheet ws) { ws.Cell("A1").SetValue(new TimeSpan(0, 12, 35, 21)).Style.Fill.SetBackgroundColor(XLColor.LightGreen); ws.Cell("A2").SetValue(new TimeSpan(45, 1, 15)).Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise); ws.Cell("A3").SetValue(new TimeSpan(1, 1, 12, 30)).Style.Fill.SetBackgroundColor(XLColor.BurlyWood); ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray); ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon); ws.Cell("A6").SetValue(new TimeSpan(0, 12, 15)).Style.Fill.SetBackgroundColor(XLColor.DodgerBlue); ws.Cell("A7").SetValue(new TimeSpan(1, 4, 30)).Style.Fill.SetBackgroundColor(XLColor.IndianRed); ws.Cell("A8").SetValue(new TimeSpan(1, 4, 15)).Style.Fill.SetBackgroundColor(XLColor.DeepPink); } private void AddTestColumnDates(IXLWorksheet ws) { ws.Cell("A1").SetValue(new DateTime(2011, 1, 30)).Style.Fill.SetBackgroundColor(XLColor.LightGreen); ws.Cell("A2").SetValue(new DateTime(2011, 1, 15)).Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise); ws.Cell("A3").SetValue(new DateTime(2011, 12, 30)).Style.Fill.SetBackgroundColor(XLColor.BurlyWood); ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray); ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon); ws.Cell("A6").SetValue(new DateTime(2011, 12, 15)).Style.Fill.SetBackgroundColor(XLColor.DodgerBlue); ws.Cell("A7").SetValue(new DateTime(2011, 4, 30)).Style.Fill.SetBackgroundColor(XLColor.IndianRed); ws.Cell("A8").SetValue(new DateTime(2011, 4, 15)).Style.Fill.SetBackgroundColor(XLColor.DeepPink); } private void AddTestColumn(IXLWorksheet ws) { ws.Cell("A1").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.LightGreen); ws.Cell("A2").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise); ws.Cell("A3").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.BurlyWood); ws.Cell("A4").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkGray); ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon); ws.Cell("A6").SetValue("b").Style.Fill.SetBackgroundColor(XLColor.DodgerBlue); ws.Cell("A7").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.IndianRed); ws.Cell("A8").SetValue("c").Style.Fill.SetBackgroundColor(XLColor.DeepPink); } private void AddTestTable(IXLWorksheet ws) { ws.Cell("A1").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.LightGreen); ws.Cell("A2").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise); ws.Cell("A3").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.BurlyWood); ws.Cell("A4").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkGray); ws.Cell("A5").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon); ws.Cell("A6").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DodgerBlue); ws.Cell("A7").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.IndianRed); ws.Cell("A8").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.DeepPink); ws.Cell("B1").SetValue("").Style.Fill.SetBackgroundColor(XLColor.LightGreen); ws.Cell("B2").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise); ws.Cell("B3").SetValue("B").Style.Fill.SetBackgroundColor(XLColor.BurlyWood); ws.Cell("B4").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkGray); ws.Cell("B5").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon); ws.Cell("B6").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DodgerBlue); ws.Cell("B7").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.IndianRed); ws.Cell("B8").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.DeepPink); ws.Cell("C1").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.LightGreen); ws.Cell("C2").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DarkTurquoise); ws.Cell("C3").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.BurlyWood); ws.Cell("C4").SetValue("a").Style.Fill.SetBackgroundColor(XLColor.DarkGray); ws.Cell("C5").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.DarkSalmon); ws.Cell("C6").SetValue("b").Style.Fill.SetBackgroundColor(XLColor.DodgerBlue); ws.Cell("C7").SetValue("A").Style.Fill.SetBackgroundColor(XLColor.IndianRed); ws.Cell("C8").SetValue("").Style.Fill.SetBackgroundColor(XLColor.DeepPink); } // Private // Override #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.DataFactories.Common.Models; using Microsoft.Azure.Management.DataFactories.Core; namespace Microsoft.Azure.Management.DataFactories.Core { public partial class DataFactoryManagementClient : ServiceClient<DataFactoryManagementClient>, IDataFactoryManagementClient { private Uri _baseUri; /// <summary> /// The URI used as the base for all Service Management requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } set { this._baseUri = value; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// When you create a Windows Azure subscription, it is uniquely /// identified by a subscription ID. The subscription ID forms part of /// the URI for every call that you make to the Service Management /// API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } set { this._credentials = value; } } 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 IActivityTypeOperations _activityTypes; /// <summary> /// Operations for managing data factory ActivityTypes. /// </summary> public virtual IActivityTypeOperations ActivityTypes { get { return this._activityTypes; } } private IComputeTypeOperations _computeTypes; /// <summary> /// Operations for managing data factory ComputeTypes. /// </summary> public virtual IComputeTypeOperations ComputeTypes { get { return this._computeTypes; } } private IDataFactoryOperations _dataFactories; /// <summary> /// Operations for managing data factories. /// </summary> public virtual IDataFactoryOperations DataFactories { get { return this._dataFactories; } } private IDatasetOperations _datasets; /// <summary> /// Operations for managing datasets. /// </summary> public virtual IDatasetOperations Datasets { get { return this._datasets; } } private IDataSliceOperations _dataSlices; /// <summary> /// Operations for managing data slices. /// </summary> public virtual IDataSliceOperations DataSlices { get { return this._dataSlices; } } private IDataSliceRunOperations _dataSliceRuns; /// <summary> /// Operations for managing data slice runs. /// </summary> public virtual IDataSliceRunOperations DataSliceRuns { get { return this._dataSliceRuns; } } private IGatewayOperations _gateways; /// <summary> /// Operations for managing data factory gateways. /// </summary> public virtual IGatewayOperations Gateways { get { return this._gateways; } } private IHubOperations _hubs; /// <summary> /// Operations for managing hubs. /// </summary> public virtual IHubOperations Hubs { get { return this._hubs; } } private ILinkedServiceOperations _linkedServices; /// <summary> /// Operations for managing data factory internal linkedServices. /// </summary> public virtual ILinkedServiceOperations LinkedServices { get { return this._linkedServices; } } private IOAuthOperations _oAuth; /// <summary> /// Operations for OAuth authorizations. /// </summary> public virtual IOAuthOperations OAuth { get { return this._oAuth; } } private IPipelineOperations _pipelines; /// <summary> /// Operations for managing pipelines. /// </summary> public virtual IPipelineOperations Pipelines { get { return this._pipelines; } } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> public DataFactoryManagementClient() : base() { this._activityTypes = new ActivityTypeOperations(this); this._computeTypes = new ComputeTypeOperations(this); this._dataFactories = new DataFactoryOperations(this); this._datasets = new DatasetOperations(this); this._dataSlices = new DataSliceOperations(this); this._dataSliceRuns = new DataSliceRunOperations(this); this._gateways = new GatewayOperations(this); this._hubs = new HubOperations(this); this._linkedServices = new LinkedServiceOperations(this); this._oAuth = new OAuthOperations(this); this._pipelines = new PipelineOperations(this); this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(60); } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='baseUri'> /// Optional. The URI used as the base for all Service Management /// requests. /// </param> public DataFactoryManagementClient(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 DataFactoryManagementClient class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> public DataFactoryManagementClient(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 DataFactoryManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public DataFactoryManagementClient(HttpClient httpClient) : base(httpClient) { this._activityTypes = new ActivityTypeOperations(this); this._computeTypes = new ComputeTypeOperations(this); this._dataFactories = new DataFactoryOperations(this); this._datasets = new DatasetOperations(this); this._dataSlices = new DataSliceOperations(this); this._dataSliceRuns = new DataSliceRunOperations(this); this._gateways = new GatewayOperations(this); this._hubs = new HubOperations(this); this._linkedServices = new LinkedServiceOperations(this); this._oAuth = new OAuthOperations(this); this._pipelines = new PipelineOperations(this); this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(60); } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='baseUri'> /// Optional. The URI used as the base for all Service Management /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public DataFactoryManagementClient(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 DataFactoryManagementClient class. /// </summary> /// <param name='credentials'> /// Required. When you create a Windows Azure subscription, it is /// uniquely identified by a subscription ID. The subscription ID /// forms part of the URI for every call that you make to the Service /// Management API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests are /// allowed. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public DataFactoryManagementClient(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 /// DataFactoryManagementClient instance /// </summary> /// <param name='client'> /// Instance of DataFactoryManagementClient to clone to /// </param> protected override void Clone(ServiceClient<DataFactoryManagementClient> client) { base.Clone(client); if (client is DataFactoryManagementClient) { DataFactoryManagementClient clonedClient = ((DataFactoryManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get 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 Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; // Deserialize Response 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.Conflict) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using UnityEngine; using System.Collections.Generic; using System; using System.Globalization; using Ecosim; using Ecosim.SceneData; using Ecosim.SceneData.Action; namespace Ecosim.GameCtrl.GameButtons { public class Reports : GameButtonHandler { private Texture2D closeTex; private Texture2D closeHTex; private Texture2D toggleVisual; private Texture2D toggleVisualH; private GUIStyle header; private GUIStyle entry; private GUIStyle entrySelected; private Progression.InventarisationResult selectedIR = null; private Inventarisation selectedINV = null; private string selectedInvName = null; private int totalYearsSelected = 0; private string name; private Dictionary<Progression.InventarisationResult, InventarisationResultWindow> windows; private Vector2 entriesScrollPos; // Inventarisations private class Inventarisation { public string name; public List<Progression.InventarisationResult> results; public Inventarisation (string name) { this.name = name; this.results = new List<Progression.InventarisationResult> (); } } private List<Inventarisation> inventarisations = null; // Graph editor private bool graphEditorOpened = false; public Reports () { header = GameControl.self.skin.FindStyle ("ArialB16-50"); entry = GameControl.self.skin.FindStyle ("Arial16-75"); entrySelected = GameControl.self.skin.FindStyle ("Arial16-W"); toggleVisual = (Texture2D)Resources.Load ("Icons/cross_w", typeof (Texture2D)); toggleVisualH = (Texture2D)Resources.Load ("Icons/cross_zw", typeof (Texture2D)); } public override bool SelectRender (GameButton button) { RetrieveInventarisations (); int colWidth = 250; int yearWidth = 80; int yearToggleBtnWidth = 32; int graphEditorWidth = 150; int invGraphEditorBtnWidth = 100; int graphBtnWidth = 80; int entryHeight = 32; foreach (Inventarisation inv in inventarisations) { // Calculate the width of the entry name, with or without the graph editor count int calcWidth = (int)entry.CalcSize (new GUIContent (inv.name + ((graphEditorOpened)?" (99/99)":""))).x; calcWidth = (((calcWidth / (entryHeight + 1)) + 1) * (entryHeight + 1) - 1) + 25; if (calcWidth > colWidth) { colWidth = calcWidth; } } bool isOver = false; int x = (int)(button.position.x + (entryHeight + 1)); int y = (int)(button.position.y); int width = 6; // Graph editor if (ExportMgr.self.graphExportEnabled) { Rect graphRect = new Rect (x, y, graphEditorWidth, entryHeight); // Label graphRect.width = colWidth + yearWidth - 175; isOver |= SimpleGUI.Label (graphRect, "Graph Editor", header); graphRect.x += graphRect.width + 1; graphRect.width = 175 - 33; isOver |= SimpleGUI.CheckMouseOver (graphRect); if (SimpleGUI.Button (graphRect, ((graphEditorOpened)?"Hide Functions":"Show Functions"), entry, entrySelected)) { graphEditorOpened = !graphEditorOpened; } graphRect.x += graphRect.width + 1; graphRect.width = 32; isOver |= SimpleGUI.CheckMouseOver (graphRect); if (SimpleGUI.Button (graphRect, " ?", entry, entrySelected)) { new ExportGraphInfoWindow (); } // Show graph editor controls if (graphEditorOpened) { // Calculate graph btn width int newGraphBtnWidth = (int)((float)(colWidth + yearWidth) / 3f); if (newGraphBtnWidth > graphBtnWidth) graphBtnWidth = newGraphBtnWidth; y += entryHeight + 1; Rect r = new Rect (x, y, graphBtnWidth, entryHeight); int totalCosts = 0; bool enoughBudget = true; // Costs switch (ExportMgr.self.graphCostType) { case ExportMgr.GraphCostTypes.OnePrice : { // Price Rect pr = new Rect (r); // Cost header pr.width = ((float)(colWidth + yearWidth) / 3f); isOver |= SimpleGUI.Label (pr, "", header); pr.x += pr.width + 1; pr.width--; isOver |= SimpleGUI.Label (pr, "Cost", entry); // Set costs totalCosts = ExportMgr.self.graphCosts; enoughBudget = (GameControl.self.scene.progression.budget - GameControl.self.scene.progression.expenses >= totalCosts); // Actual costs if (!enoughBudget) GUI.color = Color.red; pr.x += pr.width + 1; pr.width ++; isOver |= SimpleGUI.Label (pr, ExportMgr.self.graphCosts.ToString ("#,##0\\.-", CultureInfo.GetCultureInfo ("en-GB")), entry); GUI.color = Color.white; // Up the entry height y += entryHeight + 1; r.y += entryHeight + 1; } break; } // Select all isOver |= SimpleGUI.CheckMouseOver (r); if (SimpleGUI.Button (r, "Select all", entry, entrySelected)) { foreach (Inventarisation i in inventarisations) { foreach (Progression.InventarisationResult ir in i.results) { ir.selected = true; } } } // Clear selection r.x += r.width + 1; isOver |= SimpleGUI.CheckMouseOver (r); if (SimpleGUI.Button (r, "Clear all", entry, entrySelected)) { foreach (Inventarisation i in inventarisations) { foreach (Progression.InventarisationResult ir in i.results) { ir.selected = false; } } } // Generate graph GUI.enabled = enoughBudget && totalYearsSelected > 0; r.x += r.width + 1; isOver |= SimpleGUI.CheckMouseOver (r); bool generateClicked = false; if (GUI.enabled) generateClicked = SimpleGUI.Button (r, "Generate", entry, entrySelected); if (!GUI.enabled) generateClicked = SimpleGUI.Button (r, "Generate", entry); if (generateClicked) { // Subtract costs GameControl.self.scene.progression.budget -= totalCosts; GameControl.BudgetChanged (); new Ecosim.GameCtrl.ExportGraphWindow (); } GUI.enabled = true; } y += entryHeight + 1; } // Inventarisations isOver |= SimpleGUI.Label (new Rect (x, y, colWidth, entryHeight), name, header); // Years isOver |= SimpleGUI.Label (new Rect (x + colWidth + 1, y, yearWidth, entryHeight), "Years", header); if (isOver) { selectedIR = null; //selectedInvName = null; } // Reset total selected totalYearsSelected = 0; // Show sorted inventarisations Progression.InventarisationResult newSelectedIR = null; if (inventarisations.Count == 0) { //y = y + ((graphEditorOpened) ? (entryHeight + 1) : 0); SimpleGUI.Label (new Rect (x, y + (entryHeight + 1), colWidth, entryHeight), "No reports available", entry); } else { GUILayout.BeginArea (new Rect (x, y + (entryHeight), colWidth, Screen.height - (y + entryHeight))); entriesScrollPos = GUILayout.BeginScrollView (entriesScrollPos); { GUILayout.Space (1); foreach (Inventarisation inv in inventarisations) { // Get the graph suffix (X/X) string graphSuffix = ""; if (graphEditorOpened) { graphSuffix = " "; int total = inv.results.Count; int selected = 0; foreach (Progression.InventarisationResult ir in inv.results) { if (ir.selected) { selected++; totalYearsSelected++; } } graphSuffix = string.Format (" ({0}/{1})", selected, total); } // Check if this entry is selected/highlighted bool isSelected = (inv.name == selectedInvName); bool isOverGroup = false; string label = inv.name + graphSuffix; // We show a label if it's selected if (isSelected) { GUILayout.Label (label, entrySelected, GUILayout.MaxWidth (Mathf.Infinity), GUILayout.Height (entryHeight)); // Check for mouse over isOverGroup = CheckGUILayoutMouseOver (colWidth); } // We make it a button if it's not selected else { if (GUILayout.Button (label, entry, GUILayout.MaxWidth (Mathf.Infinity), GUILayout.Height (entryHeight))) { // Select the inventarisation selectedInvName = inv.name; selectedINV = inv; } // Check for mouse over isOverGroup = CheckGUILayoutMouseOver (colWidth); } GUILayout.Space (1); // Remember if we have an overall mouse over isOver |= isOverGroup; // Show functions if selected and editor is opened if (isSelected && graphEditorOpened) { GUILayout.BeginHorizontal (); { // Select all if (GUILayout.Button ("Select all", entry, GUILayout.MaxWidth (colWidth * 0.5f), GUILayout.Height (entryHeight))) { foreach (Progression.InventarisationResult ir in inv.results) { ir.selected = true; } } // Check if we have a mouse over isOver |= CheckGUILayoutMouseOver (); GUILayout.Space (1f); // Select all if (GUILayout.Button ("Clear all", entry, GUILayout.MaxWidth (colWidth * 0.5f), GUILayout.Height (entryHeight))) { foreach (Progression.InventarisationResult ir in inv.results) { ir.selected = false; } } // Check if we have a mouse over isOver |= CheckGUILayoutMouseOver (colWidth * 0.5f); } GUILayout.EndHorizontal (); GUILayout.Space (1); } } } GUILayout.EndScrollView (); GUILayout.EndArea (); // Show years seperately if (selectedINV != null) { // Calculate the amount of columns float yearsAreaHeight = Screen.height - (y + entryHeight); int maxEntriesPerColumn = Mathf.FloorToInt (yearsAreaHeight / (entryHeight + 1)); int columns = Mathf.FloorToInt ((float)selectedINV.results.Count / maxEntriesPerColumn) + 1; // Setup the layout area float yearEntryWidth = yearWidth + ((graphEditorOpened)?yearToggleBtnWidth+1:0); float yearsAreaWidth = columns * (yearEntryWidth + 1); Rect yearsAreaRect = new Rect (x + colWidth + 1, y + (entryHeight), yearsAreaWidth, yearsAreaHeight); GUILayout.BeginArea (yearsAreaRect); GUILayout.Space (1); GUILayout.BeginHorizontal(); // For use of columns for (int i = 0; i < columns; i++) { GUILayout.BeginVertical (); // Column for (int n = 0; n < maxEntriesPerColumn; n++) { int resultIndex = n + (maxEntriesPerColumn * i); if (resultIndex < selectedINV.results.Count) { Progression.InventarisationResult ir = selectedINV.results [resultIndex]; if (graphEditorOpened) { GUILayout.BeginHorizontal (); } bool isSelected = (ir == selectedIR); GUIStyle yearStyle = (isSelected) ? entrySelected : entry; if (GUILayout.Button (ir.year.ToString (), yearStyle, GUILayout.MaxWidth (yearWidth), GUILayout.Height (entryHeight))) { // Handle click HandleInventarisationResultClicked (ir); } isOver |= CheckGUILayoutMouseOver (yearWidth); // Graph toggle button if (graphEditorOpened) { GUILayout.Space (1); // Toggle button string toggleBtnLabel = (ir.selected) ? "<b> X</b>" : null; if (GUILayout.Button (toggleBtnLabel, entry, GUILayout.MaxWidth (yearToggleBtnWidth), GUILayout.Height (entryHeight))) { ir.selected = !ir.selected; } isOver |= CheckGUILayoutMouseOver (yearToggleBtnWidth); } if (graphEditorOpened) { GUILayout.EndHorizontal (); } GUILayout.Space (1); } else break; } GUILayout.EndVertical (); // ~ Column GUILayout.Space (1); } GUILayout.EndHorizontal (); // ~ For use of columns GUILayout.EndArea (); } } selectedIR = newSelectedIR; return isOver; /////// OLD /////// /*Progression.InventarisationResult newSelectedIR = null; List<Progression.InventarisationResult> inventarisations = GameControl.self.scene.progression.inventarisationResults; if (inventarisations.Count == 0) { SimpleGUI.Label (new Rect (x, y + 33, 197, 32), "No reports available", entry); } else { int colWidth = 164; foreach (Progression.InventarisationResult ir in inventarisations) { int calcWidth = (int)entry.CalcSize (new GUIContent (ir.name)).x; calcWidth = ((calcWidth / 33) + 1) * 33 - 1; if (calcWidth > colWidth) { colWidth = calcWidth; } } int i = 0; foreach (Progression.InventarisationResult ir in inventarisations) { bool hl = (ir == selectedIR); bool isOverGroup = SimpleGUI.Label (new Rect (x, y + 33 * (i + 1), colWidth, 32), ir.name, hl ? entrySelected : entry); isOverGroup |= SimpleGUI.Label (new Rect (x + colWidth + 1, y + 33 * (i + 1), 65, 32), ir.year.ToString (), hl ? entrySelected : entry); if (isOverGroup && (Event.current.type == EventType.MouseDown)) { InventarisationAction ia = (InventarisationAction)GameControl.self.scene.actions.GetAction (ir.actionId); InventarisationResultWindow irw = new InventarisationResultWindow (this, ir, ia); if (windows.ContainsKey (ir)) { windows [ir].Close (); } // On request: close all open windows... List<InventarisationResultWindow> tmpCopy = new List<InventarisationResultWindow> (windows.Values); foreach (InventarisationResultWindow w in tmpCopy) { w.Close (); } windows.Add (ir, irw); Event.current.Use (); } if (isOverGroup) { newSelectedIR = ir; } isOver |= isOverGroup; i++; if ((y + 33 * (i + 4)) > Screen.height) { // prevent entries going past bottom of screen... i = 0; x += colWidth + 67; } } } selectedIR = newSelectedIR; return isOver;*/ } private void HandleInventarisationResultClicked (Progression.InventarisationResult ir) { InventarisationAction ia = (InventarisationAction)GameControl.self.scene.actions.GetAction (ir.actionId); InventarisationResultWindow irw = new InventarisationResultWindow (this, ir, ia); if (windows.ContainsKey (ir)) { windows [ir].Close (); } // On request: close all open windows... List<InventarisationResultWindow> tmpCopy = new List<InventarisationResultWindow> (windows.Values); foreach (InventarisationResultWindow w in tmpCopy) { w.Close (); } windows.Add (ir, irw); } private bool CheckGUILayoutMouseOver () { return CheckGUILayoutMouseOver (0f); } private bool CheckGUILayoutMouseOver (float overrideWidth) { // Check if we have a mouse over, we set the width manually // because if we would have a scollbar this would not be taken // into account in the mouse over check. This principle // also applies to other mouse over checks. Rect uiRect = GUILayoutUtility.GetLastRect (); if (overrideWidth > 0f) uiRect.width = overrideWidth; bool isOver = uiRect.Contains (Event.current.mousePosition); CameraControl.MouseOverGUI |= isOver; return isOver; } private void RetrieveInventarisations () { if (inventarisations != null) return; // Get and sort all inventarisations inventarisations = new List<Inventarisation> (); // Sort them by name foreach (Progression.InventarisationResult ir in GameControl.self.scene.progression.inventarisations) { // Add to the list Inventarisation inv = null; foreach (Inventarisation i in inventarisations) { if (i.name == ir.name) { inv = i; break; } } if (inv == null) { inv = new Inventarisation (ir.name); inventarisations.Add (inv); } inv.results.Add (ir); } } public void WindowIsClosed (Progression.InventarisationResult ir) { windows.Remove (ir); inventarisations = null; //selectedInvName = null; selectedIR = null; } public override void UpdateScene (Scene scene, GameButton button) { if (windows != null) { List<InventarisationResultWindow> tmpCopy = new List<InventarisationResultWindow> (windows.Values); foreach (InventarisationResultWindow w in tmpCopy) { w.Close (); } } name = button.name; selectedIR = null; selectedInvName = null; selectedINV = null; inventarisations = null; windows = new Dictionary<Progression.InventarisationResult, InventarisationResultWindow> (); } public override void UpdateState (GameButton button) { button.isVisible = CameraControl.IsNear; button.alwaysRender = false; } } }
// // MutableLookupTest.cs // // Author: // Eric Maupin <[email protected]> // // Copyright (c) 2010 Eric Maupin (http://www.ermau.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Collections.Generic; using NUnit.Framework; namespace Cadenza.Collections.Tests { [TestFixture] public class MutableLookupTest { internal MutableLookup<string, string> GetTestLookup() { var lookup = new MutableLookup<string, string>(); lookup.Add (null, (string)null); lookup.Add (null, "blah"); lookup.Add (null, "monkeys"); lookup.Add ("F", "Foo"); lookup.Add ("F", "Foobar"); lookup.Add ("B", "Bar"); return lookup; } [Test] [ExpectedException (typeof (ArgumentNullException))] public void CtorNull() { new MutableLookup<string, string> ((ILookup<string,string>)null); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void CtorEqualityComparerNull() { new MutableLookup<string, string> ((IEqualityComparer<string>)null); } [Test] public void CtorILookup() { List<int> ints = new List<int> { 10, 20, 21, 30 }; var lookup = new MutableLookup <int, int> (ints.ToLookup (i => Int32.Parse (i.ToString()[0].ToString()))); Assert.AreEqual (3, lookup.Count); Assert.AreEqual (1, lookup[1].Count()); Assert.AreEqual (2, lookup[2].Count()); Assert.AreEqual (1, lookup[3].Count()); } [Test] public void CtorILookupWithNulls() { List<string> strs = new List<string> { "Foo", "Foos", "Foobar", "Monkeys", "Bar", "Ban", "Barfoo" }; var lookup = new MutableLookup<string, string> (strs.ToLookup (s => (s[0] != 'F' && s[0] != 'B') ? null : s[0].ToString())); Assert.AreEqual (3, lookup.Count); Assert.AreEqual (3, lookup["F"].Count()); Assert.AreEqual (3, lookup["B"].Count()); Assert.AreEqual (1, lookup[null].Count()); } [Test] public void Add() { var lookup = new MutableLookup<string, string>(); lookup.Add ("F", "Foo"); Assert.AreEqual (1, lookup.Count); Assert.AreEqual ("Foo", lookup["F"].First()); lookup.Add ("F", "Foobar"); Assert.AreEqual (1, lookup.Count); Assert.AreEqual (2, lookup["F"].Count()); } [Test] public void AddNull() { var lookup = new MutableLookup<string, string>(); lookup.Add (null, "Foo"); Assert.AreEqual (1, lookup.Count); Assert.AreEqual (1, lookup[null].Count()); lookup.Add (null, (string)null); Assert.AreEqual (1, lookup.Count); Assert.AreEqual (2, lookup[null].Count()); } [Test] public void AddMultiple() { var values = new [] { "Foo", "Foobar" }; var lookup = new MutableLookup<string, string>(); lookup.Add ("key", values); Assert.AreEqual (1, lookup.Count); CollectionAssert.Contains (lookup["key"], values[0]); CollectionAssert.Contains (lookup["key"], values[1]); lookup.Add ("key2", values); Assert.AreEqual (2, lookup.Count); CollectionAssert.Contains (lookup["key2"], values[0]); CollectionAssert.Contains (lookup["key2"], values[1]); } [Test] public void AddMultipleNull() { var values = new [] { "Foo", "Foobar" }; var lookup = new MutableLookup<string, string>(); lookup.Add (null, values); Assert.AreEqual (1, lookup.Count); Assert.IsTrue (values.SequenceEqual (lookup[null]), "S"); Assert.Throws<ArgumentNullException> (() => lookup.Add ("foo", (IEnumerable<string>)null)); } [Test] public void CountRefType() { var lookup = new MutableLookup<string, string>(); Assert.AreEqual (0, lookup.Count); lookup.Add (null, "blah"); Assert.AreEqual (1, lookup.Count); lookup.Add ("F", "Foo"); Assert.AreEqual (2, lookup.Count); lookup.Add ("F", "Foobar"); Assert.AreEqual (2, lookup.Count); lookup.Remove (null, "blah"); Assert.AreEqual (1, lookup.Count); } [Test] public void CountValueType() { var lookup = new MutableLookup<int, int>(); Assert.AreEqual (0, lookup.Count); lookup.Add (1, 10); Assert.AreEqual (1, lookup.Count); lookup.Add (2, 20); Assert.AreEqual (2, lookup.Count); lookup.Add (2, 21); Assert.AreEqual (2, lookup.Count); lookup.Remove (1, 10); Assert.AreEqual(1, lookup.Count); } [Test] public void RemoveExisting() { var lookup = new MutableLookup<string, string>(); lookup.Add (null, "blah"); lookup.Add (null, "monkeys"); lookup.Add ("F", "Foo"); lookup.Add ("F", "Foobar"); lookup.Add ("B", "Bar"); Assert.AreEqual (3, lookup.Count); Assert.IsTrue (lookup.Remove (null, "blah")); Assert.AreEqual (3, lookup.Count); Assert.IsTrue (lookup.Remove (null, "monkeys")); Assert.AreEqual (2, lookup.Count); Assert.IsTrue (lookup.Remove ("F")); Assert.AreEqual (1, lookup.Count); } [Test] public void RemoveNonExisting() { var lookup = new MutableLookup<string, string>(); lookup.Add(null, "blah"); lookup.Add(null, "monkeys"); lookup.Add("F", "Foo"); lookup.Add("F", "Foobar"); lookup.Add("B", "Bar"); Assert.IsFalse (lookup.Remove ("D")); Assert.AreEqual(3, lookup.Count); Assert.IsFalse (lookup.Remove ("F", "asdf")); Assert.AreEqual(3, lookup.Count); lookup.Remove (null); Assert.IsFalse (lookup.Remove (null)); Assert.AreEqual (2, lookup.Count); } [Test] public void ClearWithNull() { var lookup = new MutableLookup<string, string>(); lookup.Add (null, "blah"); lookup.Add ("F", "Foo"); lookup.Clear(); Assert.AreEqual (0, lookup.Count); Assert.IsFalse (lookup.Contains (null)); Assert.IsFalse (lookup.Contains ("F")); } [Test] public void ClearWithoutNull() { var lookup = new MutableLookup<string, string>(); lookup.Add("F", "Foo"); lookup.Add("F", "Foobar"); lookup.Add("B", "Bar"); lookup.Clear(); Assert.AreEqual (0, lookup.Count); Assert.IsFalse (lookup.Contains ("F")); Assert.IsFalse (lookup.Contains ("B")); } [Test] public void ClearValueType() { var lookup = new MutableLookup<int, int>(); lookup.Add (1, 10); lookup.Add (1, 12); lookup.Add (1, 13); lookup.Add (2, 21); lookup.Add (2, 22); lookup.Add (2, 23); lookup.Clear(); Assert.AreEqual (0, lookup.Count); Assert.IsFalse (lookup.Contains (1)); Assert.IsFalse (lookup.Contains (2)); } [Test] public void Contains() { var lookup = new MutableLookup<string, string>(); lookup.Add(null, "blah"); lookup.Add(null, "monkeys"); lookup.Add("F", "Foo"); lookup.Add("F", "Foobar"); lookup.Add("B", "Bar"); Assert.IsTrue (lookup.Contains ("B")); } [Test] public void DoesNotContain() { var lookup = new MutableLookup<string, string>(); lookup.Add(null, "blah"); lookup.Add(null, "monkeys"); lookup.Add("F", "Foo"); lookup.Add("F", "Foobar"); lookup.Add("B", "Bar"); Assert.IsFalse (lookup.Contains ("D")); } [Test] public void ContainsNull() { var lookup = GetTestLookup(); Assert.IsTrue (lookup.Contains (null)); } [Test] public void DoesNotContainNull() { var lookup = new MutableLookup<string, string>(); lookup.Add("F", "Foo"); lookup.Add("F", "Foobar"); lookup.Add("B", "Bar"); Assert.IsFalse (lookup.Contains (null)); } [Test] public void Indexer() { var lookup = GetTestLookup(); Assert.AreEqual (2, lookup["F"].Count()); } [Test] public void IndexerNull() { var lookup = GetTestLookup(); Assert.AreEqual (3, lookup[null].Count()); } [Test] public void IndexerNotFound() { var lookup = GetTestLookup(); Assert.AreEqual (0, lookup["D"].Count()); } [Test] public void Enumerator() { List<int> ints = new List<int> { 10, 20, 21, 30 }; var lookup = new MutableLookup<int, int>(ints.ToLookup(i => Int32.Parse(i.ToString()[0].ToString()))); Assert.AreEqual (3, lookup.Count()); Assert.IsTrue (lookup.Any (g => g.Key == 1)); Assert.IsTrue (lookup.Any (g => g.Key == 2)); Assert.IsTrue (lookup.Any (g => g.Key == 3)); } [Test] public void EnumeratorNotNull() { List<string> strings = new List<string> { "hi", "hai", "bai", "bye" }; var lookup = new MutableLookup<string, string> (strings.ToLookup (s => s[0].ToString())); Assert.AreEqual (2, lookup.Count); Assert.IsTrue (lookup.Any (g => g.Key == "h")); Assert.IsTrue (lookup.Any (g => g.Key == "b")); Assert.IsFalse (lookup.Any (g => g.Key == null)); } [Test] public void EnumeratorNull() { var lookup = GetTestLookup(); Assert.AreEqual (3, lookup.Count()); Assert.IsTrue (lookup.Any (g => g.Key == null)); Assert.IsTrue (lookup.Any (g => g.Key == "F")); Assert.IsTrue (lookup.Any (g => g.Key == "B")); } [Test] public void NullGroupingEnumerator() { var lookup = GetTestLookup(); Assert.AreEqual (3, lookup[null].Count()); Assert.IsTrue (lookup[null].Any (s => s == "blah")); Assert.IsTrue (lookup[null].Any (s => s == "monkeys")); Assert.IsTrue (lookup[null].Any (s => s == null)); } [Test] public void GroupingEnumerator() { List<int> ints = new List<int> { 10, 20, 21, 30 }; var lookup = new MutableLookup<int, int>(ints.ToLookup(i => Int32.Parse(i.ToString()[0].ToString()))); Assert.AreEqual (2, lookup[2].Count()); Assert.IsTrue (lookup[2].Any (i => i == 20)); Assert.IsTrue (lookup[2].Any(i => i == 21)); } [Test] public void TryGetValuesNull() { var lookup = GetTestLookup(); IEnumerable<string> values; Assert.IsTrue (lookup.TryGetValues (null, out values)); Assert.IsNotNull (values); var v = values.ToList(); Assert.AreEqual (3, v.Count); CollectionAssert.Contains (v, "blah"); CollectionAssert.Contains (v, "monkeys"); Assert.Contains ("blah", v); Assert.Contains ("monkeys", v); Assert.Contains (null, v); } [Test] public void TryGetValues() { var lookup = GetTestLookup(); IEnumerable<string> values; Assert.IsTrue (lookup.TryGetValues ("F", out values)); Assert.IsNotNull (values); var v = values.ToList(); Assert.AreEqual (2, v.Count); Assert.Contains ("Foo", v); Assert.Contains ("Foobar", v); } [Test] public void TryGetValuesFail() { var lookup = GetTestLookup(); IEnumerable<string> values; Assert.IsFalse (lookup.TryGetValues ("notfound", out values)); Assert.IsNull (values); } [Test] public void TryGetValuesNullFail() { var lookup = new MutableLookup<string,string>(); IEnumerable<string> values; Assert.IsFalse (lookup.TryGetValues (null, out values)); Assert.IsNull (values); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure; namespace Microsoft.AspNetCore.Mvc.Diagnostics { /// <summary> /// An <see cref="EventData"/> that occurs before a handler method is called. /// </summary> public sealed class BeforeHandlerMethodEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "BeforeHandlerMethod"; /// <summary> /// Initializes a new instance of <see cref="BeforeHandlerMethodEventData"/>. /// </summary> /// <param name="actionContext">The action context.</param> /// <param name="arguments">The arguments to the method.</param> /// <param name="handlerMethodDescriptor">The method descriptor.</param> /// <param name="instance">The instance.</param> public BeforeHandlerMethodEventData(ActionContext actionContext, IReadOnlyDictionary<string, object?> arguments, HandlerMethodDescriptor handlerMethodDescriptor, object instance) { ActionContext = actionContext; Arguments = arguments; HandlerMethodDescriptor = handlerMethodDescriptor; Instance = instance; } /// <summary> /// The <see cref="ActionContext"/>. /// </summary> public ActionContext ActionContext { get; } /// <summary> /// The arguments to the method. /// </summary> public IReadOnlyDictionary<string, object?> Arguments { get; } /// <summary> /// The <see cref="HandlerMethodDescriptor"/>. /// </summary> public HandlerMethodDescriptor HandlerMethodDescriptor { get; } /// <summary> /// The instance. /// </summary> public object Instance { get; } /// <inheritdoc/> protected override int Count => 4; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionContext), ActionContext), 1 => new KeyValuePair<string, object>(nameof(Arguments), Arguments), 2 => new KeyValuePair<string, object>(nameof(HandlerMethodDescriptor), HandlerMethodDescriptor), 3 => new KeyValuePair<string, object>(nameof(Instance), Instance), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs after a handler method is called. /// </summary> public sealed class AfterHandlerMethodEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "AfterHandlerMethod"; /// <summary> /// Initializes a new instance of <see cref="AfterHandlerMethodEventData"/>. /// </summary> /// <param name="actionContext">The action context.</param> /// <param name="arguments">The arguments to the method.</param> /// <param name="handlerMethodDescriptor">The method descriptor.</param> /// <param name="instance">The instance.</param> /// <param name="result">The result of the handler method</param> public AfterHandlerMethodEventData(ActionContext actionContext, IReadOnlyDictionary<string, object?> arguments, HandlerMethodDescriptor handlerMethodDescriptor, object instance, IActionResult? result) { ActionContext = actionContext; Arguments = arguments; HandlerMethodDescriptor = handlerMethodDescriptor; Instance = instance; Result = result; } /// <summary> /// The <see cref="ActionContext"/>. /// </summary> public ActionContext ActionContext { get; } /// <summary> /// The arguments to the method. /// </summary> public IReadOnlyDictionary<string, object?> Arguments { get; } /// <summary> /// The <see cref="HandlerMethodDescriptor"/>. /// </summary> public HandlerMethodDescriptor HandlerMethodDescriptor { get; } /// <summary> /// The instance. /// </summary> public object Instance { get; } /// <summary> /// The result of the method. /// </summary> public IActionResult? Result { get; } /// <inheritdoc/> protected override int Count => 5; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionContext), ActionContext), 1 => new KeyValuePair<string, object>(nameof(Arguments), Arguments), 2 => new KeyValuePair<string, object>(nameof(HandlerMethodDescriptor), HandlerMethodDescriptor), 3 => new KeyValuePair<string, object>(nameof(Instance), Instance), 4 => new KeyValuePair<string, object>(nameof(Result), Result!), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs before page handler execution. /// </summary> public sealed class BeforePageFilterOnPageHandlerExecutionEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "BeforeOnPageHandlerExecution"; /// <summary> /// Initializes a new instance of <see cref="AfterHandlerMethodEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerExecutionContext">The <see cref="HandlerExecutionContext"/>.</param> /// <param name="filter">The <see cref="IAsyncPageFilter"/>.</param> public BeforePageFilterOnPageHandlerExecutionEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerExecutingContext handlerExecutionContext, IAsyncPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerExecutionContext = handlerExecutionContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerExecutingContext"/>. /// </summary> public PageHandlerExecutingContext HandlerExecutionContext { get; } /// <summary> /// The <see cref="IAsyncPageFilter"/>. /// </summary> public IAsyncPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerExecutionContext), HandlerExecutionContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs after page handler execution. /// </summary> public sealed class AfterPageFilterOnPageHandlerExecutionEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "AfterOnPageHandlerExecution"; /// <summary> /// Initializes a new instance of <see cref="AfterPageFilterOnPageHandlerExecutionEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerExecutedContext">The <see cref="HandlerExecutedContext"/>.</param> /// <param name="filter">The <see cref="IAsyncPageFilter"/>.</param> public AfterPageFilterOnPageHandlerExecutionEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerExecutedContext handlerExecutedContext, IAsyncPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerExecutedContext = handlerExecutedContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerExecutedContext"/>. /// </summary> public PageHandlerExecutedContext HandlerExecutedContext { get; } /// <summary> /// The <see cref="IAsyncPageFilter"/>. /// </summary> public IAsyncPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerExecutedContext), HandlerExecutedContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs before page handler executing. /// </summary> public sealed class BeforePageFilterOnPageHandlerExecutingEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "BeforeOnPageHandlerExecuting"; /// <summary> /// Initializes a new instance of <see cref="BeforePageFilterOnPageHandlerExecutingEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerExecutingContext">The <see cref="PageHandlerExecutingContext"/>.</param> /// <param name="filter">The <see cref="IPageFilter"/>.</param> public BeforePageFilterOnPageHandlerExecutingEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerExecutingContext handlerExecutingContext, IPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerExecutingContext = handlerExecutingContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerExecutingContext"/>. /// </summary> public PageHandlerExecutingContext HandlerExecutingContext { get; } /// <summary> /// The <see cref="IAsyncPageFilter"/>. /// </summary> public IPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerExecutingContext), HandlerExecutingContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs after page handler executing. /// </summary> public sealed class AfterPageFilterOnPageHandlerExecutingEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "AfterOnPageHandlerExecuting"; /// <summary> /// Initializes a new instance of <see cref="AfterPageFilterOnPageHandlerExecutingEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerExecutingContext">The <see cref="PageHandlerExecutingContext"/>.</param> /// <param name="filter">The <see cref="IPageFilter"/>.</param> public AfterPageFilterOnPageHandlerExecutingEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerExecutingContext handlerExecutingContext, IPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerExecutingContext = handlerExecutingContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerExecutingContext"/>. /// </summary> public PageHandlerExecutingContext HandlerExecutingContext { get; } /// <summary> /// The <see cref="IPageFilter"/>. /// </summary> public IPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerExecutingContext), HandlerExecutingContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs before page handler executed. /// </summary> public sealed class BeforePageFilterOnPageHandlerExecutedEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "BeforeOnPageHandlerExecuted"; /// <summary> /// Initializes a new instance of <see cref="BeforePageFilterOnPageHandlerExecutedEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerExecutedContext">The <see cref="PageHandlerExecutedContext"/>.</param> /// <param name="filter">The <see cref="IPageFilter"/>.</param> public BeforePageFilterOnPageHandlerExecutedEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerExecutedContext handlerExecutedContext, IPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerExecutedContext = handlerExecutedContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerExecutedContext"/>. /// </summary> public PageHandlerExecutedContext HandlerExecutedContext { get; } /// <summary> /// The <see cref="IPageFilter"/>. /// </summary> public IPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerExecutedContext), HandlerExecutedContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs after page handler executed. /// </summary> public sealed class AfterPageFilterOnPageHandlerExecutedEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "AfterOnPageHandlerExecuted"; /// <summary> /// Initializes a new instance of <see cref="AfterPageFilterOnPageHandlerExecutedEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerExecutedContext">The <see cref="PageHandlerExecutedContext"/>.</param> /// <param name="filter">The <see cref="IPageFilter"/>.</param> public AfterPageFilterOnPageHandlerExecutedEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerExecutedContext handlerExecutedContext, IPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerExecutedContext = handlerExecutedContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerExecutedContext"/>. /// </summary> public PageHandlerExecutedContext HandlerExecutedContext { get; } /// <summary> /// The <see cref="IPageFilter"/>. /// </summary> public IPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerExecutedContext), HandlerExecutedContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs before page handler selection. /// </summary> public sealed class BeforePageFilterOnPageHandlerSelectionEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "BeforeOnPageHandlerSelection"; /// <summary> /// Initializes a new instance of <see cref="BeforePageFilterOnPageHandlerSelectionEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerSelectedContext">The <see cref="PageHandlerSelectedContext"/>.</param> /// <param name="filter">The <see cref="IAsyncPageFilter"/>.</param> public BeforePageFilterOnPageHandlerSelectionEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerSelectedContext handlerSelectedContext, IAsyncPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerSelectedContext = handlerSelectedContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerSelectedContext"/>. /// </summary> public PageHandlerSelectedContext HandlerSelectedContext { get; } /// <summary> /// The <see cref="IPageFilter"/>. /// </summary> public IAsyncPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerSelectedContext), HandlerSelectedContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs after page handler selection. /// </summary> public sealed class AfterPageFilterOnPageHandlerSelectionEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "AfterOnPageHandlerSelection"; /// <summary> /// Initializes a new instance of <see cref="AfterPageFilterOnPageHandlerSelectionEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerSelectedContext">The <see cref="PageHandlerSelectedContext"/>.</param> /// <param name="filter">The <see cref="IAsyncPageFilter"/>.</param> public AfterPageFilterOnPageHandlerSelectionEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerSelectedContext handlerSelectedContext, IAsyncPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerSelectedContext = handlerSelectedContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerSelectedContext"/>. /// </summary> public PageHandlerSelectedContext HandlerSelectedContext { get; } /// <summary> /// The <see cref="IAsyncPageFilter"/>. /// </summary> public IAsyncPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerSelectedContext), HandlerSelectedContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs before <see cref="IPageFilter.OnPageHandlerSelected(PageHandlerSelectedContext)"/>. /// </summary> public sealed class BeforePageFilterOnPageHandlerSelectedEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "BeforeOnPageHandlerSelected"; /// <summary> /// Initializes a new instance of <see cref="BeforePageFilterOnPageHandlerSelectedEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerSelectedContext">The <see cref="PageHandlerSelectedContext"/>.</param> /// <param name="filter">The <see cref="IPageFilter"/>.</param> public BeforePageFilterOnPageHandlerSelectedEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerSelectedContext handlerSelectedContext, IPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerSelectedContext = handlerSelectedContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerSelectedContext"/>. /// </summary> public PageHandlerSelectedContext HandlerSelectedContext { get; } /// <summary> /// The <see cref="IPageFilter"/>. /// </summary> public IPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerSelectedContext), HandlerSelectedContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } /// <summary> /// An <see cref="EventData"/> that occurs after <see cref="IPageFilter.OnPageHandlerSelected(PageHandlerSelectedContext)"/>. /// </summary> public sealed class AfterPageFilterOnPageHandlerSelectedEventData : EventData { /// <summary> /// Name of the event. /// </summary> public const string EventName = EventNamespace + "AfterOnPageHandlerSelected"; /// <summary> /// Initializes a new instance of <see cref="AfterPageFilterOnPageHandlerSelectedEventData"/>. /// </summary> /// <param name="actionDescriptor">The <see cref="CompiledPageActionDescriptor"/>.</param> /// <param name="handlerSelectedContext">The <see cref="PageHandlerSelectedContext"/>.</param> /// <param name="filter">The <see cref="IPageFilter"/>.</param> public AfterPageFilterOnPageHandlerSelectedEventData(CompiledPageActionDescriptor actionDescriptor, PageHandlerSelectedContext handlerSelectedContext, IPageFilter filter) { ActionDescriptor = actionDescriptor; HandlerSelectedContext = handlerSelectedContext; Filter = filter; } /// <summary> /// The <see cref="CompiledPageActionDescriptor"/>. /// </summary> public CompiledPageActionDescriptor ActionDescriptor { get; } /// <summary> /// The <see cref="PageHandlerSelectedContext"/>. /// </summary> public PageHandlerSelectedContext HandlerSelectedContext { get; } /// <summary> /// The <see cref="IPageFilter"/>. /// </summary> public IPageFilter Filter { get; } /// <inheritdoc/> protected override int Count => 3; /// <inheritdoc/> protected override KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair<string, object>(nameof(HandlerSelectedContext), HandlerSelectedContext), 2 => new KeyValuePair<string, object>(nameof(Filter), Filter), _ => throw new IndexOutOfRangeException(nameof(index)) }; } }
using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using Microsoft.BizTalk.BaseFunctoids; using System.Drawing; using System.Windows.Forms; using System.Text.RegularExpressions; namespace BizTalk.MapperExtensions.Functoid.Wizard { public class WzPageResourceSetup2 : Microsoft.BizTalk.Wizard.WizardInteriorPage, WizardControlInterface { #region Global Variables public event AddWizardResultEvent _AddWizardResultEvent; private bool _IsLoaded = false; #endregion #region Form Components private System.ComponentModel.IContainer components = null; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label5; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.PictureBox FunctoidIcon; private System.Windows.Forms.ComboBox cmbCategory; private System.Windows.Forms.GroupBox grpLanguage; private System.Windows.Forms.RadioButton optCS; private System.Windows.Forms.RadioButton optVB; private System.Windows.Forms.ErrorProvider errorProvider; #endregion public WzPageResourceSetup2() { // This call is required by the Windows Form Designer. InitializeComponent(); this.AutoScaleDimensions = new SizeF(6F, 13F); this.AutoScaleMode = AutoScaleMode.Font; // TODO: Add any initialization after the 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 ); } public bool NextButtonEnabled { get { return true; } } public bool NeedSummary { get { return false; } } protected void AddWizardResult(string strName, object Value) { PropertyPairEvent PropertyPair = new PropertyPairEvent(strName, Value); OnAddWizardResult(PropertyPair); } /// <summary> /// The protected OnRaiseProperty method raises the event by invoking /// the delegates. The sender is always this, the current instance /// of the class. /// </summary> /// <param name="e"></param> protected virtual void OnAddWizardResult(PropertyPairEvent e) { if (e != null) { // Invokes the delegates. _AddWizardResultEvent(this,e); } } private void WzPageResourceSetup2_Leave(object sender, System.EventArgs e) { try { // Save wizard results AddWizardResult(WizardValues.FunctoidBitmap, FunctoidIcon.Image); AddWizardResult(WizardValues.FunctoidExceptionText, ""); AddWizardResult(WizardValues.CodeLanguage, (optCS.Checked ? "CSharp" : "VB")); AddWizardResult(WizardValues.FunctoidCategory, cmbCategory.SelectedItem.ToString()); } catch(Exception err) { MessageBox.Show(err.Message); Trace.WriteLine(err.Message + Environment.NewLine + err.StackTrace); } } /// <summary> /// Resets all of the errorproviders when anything succeeds /// </summary> private void ResetAllErrProviders() { foreach(Control ctl in this.Controls) { errorProvider.SetError(ctl, ""); } } private bool GetAllStates() { return true; } private void WzPageResourceSetup2_Load(object sender, System.EventArgs e) { //float dpiX, dpiY; //Graphics graphics = this.CreateGraphics(); //dpiX = graphics.DpiX; //dpiY = graphics.DpiY; //if (dpiX == dpiY) //{ // var 16heightEquivalent = picture //} //this.FunctoidIcon. string[] strFunctoidCategories= Enum.GetNames(typeof(FunctoidCategory)); try { if (_IsLoaded) return; foreach(string strFunctoidCategory in strFunctoidCategories) { cmbCategory.Items.Add(strFunctoidCategory); } cmbCategory.SelectedIndex = cmbCategory.FindStringExact("String"); AddWizardResult(WizardValues.FunctoidCategory, cmbCategory.SelectedItem.ToString()); _IsLoaded = true; } catch(Exception err) { MessageBox.Show(err.Message); Trace.WriteLine(err.Message + Environment.NewLine + err.StackTrace); } } private void FunctoidIcon_DoubleClick(object sender, System.EventArgs e) { if(openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FunctoidIcon.Image = Image.FromFile(openFileDialog.FileName); AddWizardResult(WizardValues.FunctoidBitmap, FunctoidIcon.Image); } } private void FunctoidIcon_Click(object sender, System.EventArgs e) { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(WzPageResourceSetup2)); this.FunctoidIcon.Image = ((System.Drawing.Image)(resources.GetObject("FunctoidIcon.Image"))); AddWizardResult(WizardValues.FunctoidBitmap, FunctoidIcon.Image); } #region 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(WzPageResourceSetup2)); this.label2 = new System.Windows.Forms.Label(); this.errorProvider = new System.Windows.Forms.ErrorProvider(this.components); this.label5 = new System.Windows.Forms.Label(); this.FunctoidIcon = new System.Windows.Forms.PictureBox(); this.cmbCategory = new System.Windows.Forms.ComboBox(); this.grpLanguage = new System.Windows.Forms.GroupBox(); this.optVB = new System.Windows.Forms.RadioButton(); this.optCS = new System.Windows.Forms.RadioButton(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.panelHeader.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.FunctoidIcon)).BeginInit(); this.grpLanguage.SuspendLayout(); this.SuspendLayout(); // // panelHeader // resources.ApplyResources(this.panelHeader, "panelHeader"); // // labelTitle // resources.ApplyResources(this.labelTitle, "labelTitle"); // // labelSubTitle // resources.ApplyResources(this.labelSubTitle, "labelSubTitle"); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // errorProvider // this.errorProvider.ContainerControl = this; resources.ApplyResources(this.errorProvider, "errorProvider"); // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // FunctoidIcon // resources.ApplyResources(this.FunctoidIcon, "FunctoidIcon"); this.FunctoidIcon.Name = "FunctoidIcon"; this.FunctoidIcon.TabStop = false; this.FunctoidIcon.Click += new System.EventHandler(this.FunctoidIcon_Click); this.FunctoidIcon.DoubleClick += new System.EventHandler(this.FunctoidIcon_DoubleClick); // // cmbCategory // this.cmbCategory.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbCategory, "cmbCategory"); this.cmbCategory.Name = "cmbCategory"; this.cmbCategory.Sorted = true; // // grpLanguage // this.grpLanguage.Controls.Add(this.optVB); this.grpLanguage.Controls.Add(this.optCS); resources.ApplyResources(this.grpLanguage, "grpLanguage"); this.grpLanguage.Name = "grpLanguage"; this.grpLanguage.TabStop = false; // // optVB // resources.ApplyResources(this.optVB, "optVB"); this.optVB.Name = "optVB"; // // optCS // this.optCS.Checked = true; resources.ApplyResources(this.optCS, "optCS"); this.optCS.Name = "optCS"; this.optCS.TabStop = true; // // openFileDialog // this.openFileDialog.DefaultExt = "bmp"; resources.ApplyResources(this.openFileDialog, "openFileDialog"); this.openFileDialog.RestoreDirectory = true; // // WzPageResourceSetup2 // this.Controls.Add(this.grpLanguage); this.Controls.Add(this.cmbCategory); this.Controls.Add(this.FunctoidIcon); this.Controls.Add(this.label5); this.Controls.Add(this.label2); this.Name = "WzPageResourceSetup2"; resources.ApplyResources(this, "$this"); this.SubTitle = "Specify Functoid Properties"; this.Title = "Functoid Properties"; this.Load += new System.EventHandler(this.WzPageResourceSetup2_Load); this.Leave += new System.EventHandler(this.WzPageResourceSetup2_Leave); this.Controls.SetChildIndex(this.label2, 0); this.Controls.SetChildIndex(this.label5, 0); this.Controls.SetChildIndex(this.panelHeader, 0); this.Controls.SetChildIndex(this.FunctoidIcon, 0); this.Controls.SetChildIndex(this.cmbCategory, 0); this.Controls.SetChildIndex(this.grpLanguage, 0); this.panelHeader.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.FunctoidIcon)).EndInit(); this.grpLanguage.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Viainternet.OnionArchitecture.Presentation.Website.Areas.HelpPage.ModelDescriptions; using Viainternet.OnionArchitecture.Presentation.Website.Areas.HelpPage.Models; namespace Viainternet.OnionArchitecture.Presentation.Website.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using Microsoft.Rest.Azure; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest; using Newtonsoft.Json.Linq; using Xunit; using Microsoft.Rest.Azure.OData; namespace ResourceGroups.Tests { public class InMemoryResourceGroupTests { public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler) { var subscriptionId = Guid.NewGuid().ToString(); var token = new TokenCredentials(subscriptionId, "abc123"); handler.IsPassThrough = false; var client = new ResourceManagementClient(token, handler); client.SubscriptionId = subscriptionId; return client; } [Fact] public void ResourceGroupCreateOrUpdateValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'name': 'foo', 'location': 'WestEurope', 'tags' : { 'department':'finance', 'tagname':'tagvalue' }, 'properties': { 'provisioningState': 'Succeeded' } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.CreateOrUpdate("foo", new ResourceGroup { Location = "WestEurope", Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } }, }); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal(HttpMethod.Put, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate payload Assert.Equal("WestEurope", json["location"].Value<string>()); Assert.Equal("finance", json["tags"]["department"].Value<string>()); Assert.Equal("tagvalue", json["tags"]["tagname"].Value<string>()); // Validate response Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.Equal("foo", result.Name); Assert.Equal("finance", result.Tags["department"]); Assert.Equal("tagvalue", result.Tags["tagname"]); Assert.Equal("WestEurope", result.Location); } [Fact] public void ResourceGroupCreateOrUpdateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<Microsoft.Rest.ValidationException>(() => client.ResourceGroups.CreateOrUpdate(null, new ResourceGroup())); Assert.Throws<Microsoft.Rest.ValidationException>(() => client.ResourceGroups.CreateOrUpdate("foo", null)); } [Fact] public void ResourceGroupExistsReturnsTrue() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.NoContent }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.CheckExistence("foo"); // Validate payload Assert.Empty(handler.Request); // Validate response Assert.True(result.Value); } [Fact] public void ResourceGroupExistsReturnsFalse() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.NotFound }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.CheckExistence(Guid.NewGuid().ToString()); // Validate payload Assert.Empty(handler.Request); // Validate response Assert.False(result.Value); } [Fact()] public void ResourceGroupExistsThrowsException() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.BadRequest }; var client = GetResourceManagementClient(handler); Assert.Throws<CloudException>(() => client.ResourceGroups.CheckExistence("foo")); } [Fact] public void ResourceGroupPatchValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'subscriptionId': '123456', 'name': 'foo', 'location': 'WestEurope', 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'properties': { 'provisioningState': 'Succeeded' } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.Patch("foo", new ResourceGroup { Location = "WestEurope", }); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal("patch", handler.Method.Method.Trim().ToLower()); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate payload Assert.Equal("WestEurope", json["location"].Value<string>()); // Validate response Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.Equal("foo", result.Name); Assert.Equal("WestEurope", result.Location); } [Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")] public void ResourceGroupUpdateStateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Patch(null, new ResourceGroup())); Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Patch("foo", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.ResourceGroups.Patch("~`123", new ResourceGroup())); } [Fact] public void ResourceGroupGetValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'name': 'foo', 'location': 'WestEurope', 'properties': { 'provisioningState': 'Succeeded' } }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.Get("foo"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.Id); Assert.Equal("WestEurope", result.Location); Assert.Equal("foo", result.Name); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.True(result.Properties.ProvisioningState == "Succeeded"); } [Fact] public void ResourceGroupNameAcceptsAllAllowableCharacters() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'name': 'foo', 'location': 'WestEurope', 'properties': { 'provisioningState': 'Succeeded' } }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); client.ResourceGroups.Get("foo-123_(bar)"); } [Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")] public void ResourceGroupGetThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.ResourceGroups.Get(null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.ResourceGroups.Get("~`123")); } [Fact] public void ResourceGroupListAllValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [{ 'id': '/subscriptions/abc123/resourcegroups/csmrgr5mfggio', 'name': 'myresourcegroup1', 'location': 'westus', 'properties': { 'provisioningState': 'Succeeded' } }, { 'id': '/subscriptions/abc123/resourcegroups/fdfdsdsf', 'name': 'myresourcegroup2', 'location': 'eastus', 'properties': { 'provisioningState': 'Succeeded' } } ], 'nextLink': 'https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.List(null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal(2, result.Count()); Assert.Equal("myresourcegroup1", result.First().Name); Assert.Equal("Succeeded", result.First().Properties.ProvisioningState); Assert.Equal("/subscriptions/abc123/resourcegroups/csmrgr5mfggio", result.First().Id); Assert.Equal("https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk", result.NextPageLink); } [Fact] public void ResourceGroupListAllWorksForEmptyLists() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{'value': []}") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.List(null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal(0, result.Count()); } [Fact] public void ResourceGroupListValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [{ 'name': 'myresourcegroup1', 'location': 'westus', 'locked': 'true' }, { 'name': 'myresourcegroup2', 'location': 'eastus', 'locked': 'false' } ], 'nextLink': 'https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk', }") }; response.Headers.Add("x-ms-request-id", "1"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.ResourceGroups.List(new ODataQuery<ResourceGroupFilter> { Top = 5 }); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.True(handler.Uri.ToString().Contains("$top=5")); // Validate result Assert.Equal(2, result.Count()); Assert.Equal("myresourcegroup1", result.First().Name); Assert.Equal("https://wa/subscriptions/subId/resourcegroups?api-version=1.0&$skiptoken=662idk", result.NextPageLink); } [Fact] public void ResourceGroupDeleteValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.Accepted); response.Headers.Add("Location", "http://foo"); var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.Accepted, SubsequentStatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); client.LongRunningOperationRetryTimeout = 0; client.ResourceGroups.Delete("foo"); } [Fact] public void ResourceGroupDeleteThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ValidationException>(() => client.ResourceGroups.Delete(null)); Assert.Throws<ValidationException>(() => client.ResourceGroups.Delete("~`123")); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocCommentFormatting { public class DocCommentFormattingTests { private CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string xmlFragment, string expectedCSharp, string expectedVB) { var csharpFormattedText = _csharpService.Format(xmlFragment); var vbFormattedText = _vbService.Format(xmlFragment); Assert.Equal(expectedCSharp, csharpFormattedText); Assert.Equal(expectedVB, vbFormattedText); } private void TestFormat(string xmlFragment, string expected) { TestFormat(xmlFragment, expected, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void CTag() { var comment = "Class <c>Point</c> models a point in a two-dimensional plane."; var expected = "Class Point models a point in a two-dimensional plane."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ExampleAndCodeTags() { var comment = @"This method changes the point's location by the given x- and y-offsets. <example>For example: <code> Point p = new Point(3,5); p.Translate(-1,3); </code> results in <c>p</c>'s having the value (2,8). </example>"; var expected = "This method changes the point's location by the given x- and y-offsets. For example: Point p = new Point(3,5); p.Translate(-1,3); results in p's having the value (2,8)."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ListTag() { var comment = @"Here is an example of a bulleted list: <list type=""bullet""> <item> <description>Item 1.</description> </item> <item> <description>Item 2.</description> </item> </list>"; var expected = @"Here is an example of a bulleted list: Item 1. Item 2."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ParaTag() { var comment = @"This is the entry point of the Point class testing program. <para>This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class.</para>"; var expected = @"This is the entry point of the Point class testing program. This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestPermissionTag() { var comment = @"<permission cref=""System.Security.PermissionSet"">Everyone can access this method.</permission>"; var expected = @"Everyone can access this method."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeTag() { var comment = @"<see cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlsoTag() { var comment = @"<seealso cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ValueTag() { var comment = @"<value>Property <c>X</c> represents the point's x-coordinate.</value>"; var expected = @"Property X represents the point's x-coordinate."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestParamRefTag() { var comment = @"This constructor initializes the new Point to (<paramref name=""xor""/>,<paramref name=""yor""/>)."; var expected = "This constructor initializes the new Point to (xor,yor)."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestTypeParamRefTag() { var comment = @"This method fetches data and returns a list of <typeparamref name=""Z""/>."; var expected = @"This method fetches data and returns a list of Z."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace1() { var comment = " This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace2() { var comment = @" This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace3() { var comment = "This has extra whitespace."; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs1() { var comment = @" <para>This is part of a paragraph.</para> "; var expected = "This is part of a paragraph."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs2() { var comment = @" <para>This is part of a paragraph.</para> <para>This is also part of a paragraph.</para> "; var expected = @"This is part of a paragraph. This is also part of a paragraph."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs3() { var comment = @" This is a summary. <para>This is part of a paragraph.</para> "; var expected = @"This is a summary. This is part of a paragraph."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs4() { var comment = @" <para>This is part of a paragraph.</para> This is part of the summary, too. "; var expected = @"This is part of a paragraph. This is part of the summary, too."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See1() { var comment = @"See <see cref=""T:System.Object"" />"; var expected = "See System.Object"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See2() { var comment = @"See <see />"; var expected = @"See"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso1() { var comment = @"See also <seealso cref=""T:System.Object"" />"; var expected = @"See also System.Object"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso2() { var comment = @"See also <seealso />"; var expected = @"See also"; TestFormat(comment, expected); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using Glass.Mapper.Pipelines.DataMapperResolver; using Glass.Mapper.Umb.Configuration; using Glass.Mapper.Umb.DataMappers; using NSubstitute; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Services; namespace Glass.Mapper.Umb.Integration.DataMappers { [TestFixture] public class UmbracoParentMapperFixture { private PetaPocoUnitOfWorkProvider _unitOfWork; private RepositoryFactory _repoFactory; #region Property - ReadOnly [Test] public void ReadOnly_ReturnsTrue() { //Assign var mapper = new UmbracoParentMapper(); //Act var result = mapper.ReadOnly; //Assert Assert.IsTrue(result); } #endregion #region Method - MapToProperty [Test] public void MapToProperty_ConfigurationSetupCorrectly_CallsCreateClassOnService() { //Assign var contentService = new ContentService(_unitOfWork, _repoFactory); var content = contentService.GetById(new Guid("{C382AE57-D325-4357-A32A-0A959BBD4101}")); var service = Substitute.For<IUmbracoService>(); service.ContentService.Returns(contentService); var context = new UmbracoDataMappingContext(null, content, service, false); var config = new UmbracoParentConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new UmbracoParentMapper(); mapper.Setup(new DataMapperResolverArgs(null, config)); //Act mapper.MapToProperty(context); //Assert //ME - I am not sure why I have to use the Arg.Is but just using item.Parent as the argument fails. service.Received().CreateType(config.PropertyInfo.PropertyType, Arg.Is<IContent>(x => x.Id == content.ParentId), true, false); } [Test] public void MapToProperty_ConfigurationIsLazy_CallsCreateClassOnServiceWithIsLazy() { //Assign var contentService = new ContentService(_unitOfWork, _repoFactory); var content = contentService.GetById(new Guid("{C382AE57-D325-4357-A32A-0A959BBD4101}")); var service = Substitute.For<IUmbracoService>(); service.ContentService.Returns(contentService); var context = new UmbracoDataMappingContext(null, content, service, false); var config = new UmbracoParentConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); config.IsLazy = true; var mapper = new UmbracoParentMapper(); mapper.Setup(new DataMapperResolverArgs(null, config)); //Act mapper.MapToProperty(context); //Assert //ME - I am not sure why I have to use the Arg.Is but just using item.Parent as the argument fails. service.Received().CreateType(config.PropertyInfo.PropertyType, Arg.Is<IContent>(x => x.Id == content.ParentId), true, false); } [Test] public void MapToProperty_ConfigurationInferType_CallsCreateClassOnServiceWithInferType() { //Assign var contentService = new ContentService(_unitOfWork, _repoFactory); var content = contentService.GetById(new Guid("{C382AE57-D325-4357-A32A-0A959BBD4101}")); var service = Substitute.For<IUmbracoService>(); service.ContentService.Returns(contentService); var context = new UmbracoDataMappingContext(null, content, service, false); var config = new UmbracoParentConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); config.InferType = true; var mapper = new UmbracoParentMapper(); mapper.Setup(new DataMapperResolverArgs(null, config)); //Act mapper.MapToProperty(context); //Assert //ME - I am not sure why I have to use the Arg.Is but just using item.Parent as the argument fails. service.Received().CreateType(config.PropertyInfo.PropertyType, Arg.Is<IContent>(x => x.Id == content.ParentId), true, true); } #endregion #region Method - CanHandle [Test] public void CanHandle_ConfigurationIsUmbracoParent_ReturnsTrue() { //Assign var config = new UmbracoParentConfiguration(); var mapper = new UmbracoParentMapper(); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsTrue(result); } [Test] public void CanHandle_ConfigurationIsUmbracoInfo_ReturnsFalse() { //Assign var config = new UmbracoInfoConfiguration(); var mapper = new UmbracoParentMapper(); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsFalse(result); } #endregion #region Method - MapToCms [Test] [ExpectedException(typeof(NotSupportedException))] public void MapToCms_ThrowsException() { //Assign var mapper = new UmbracoParentMapper(); //Act mapper.MapToCms(null); } #endregion #region Stubs [TestFixtureSetUp] public void CreateStub() { string name = "Target"; string contentTypeAlias = "TestType"; string contentTypeName = "Test Type"; _unitOfWork = Global.CreateUnitOfWork(); _repoFactory = new RepositoryFactory(); var contentService = new ContentService(_unitOfWork, _repoFactory); var contentTypeService = new ContentTypeService(_unitOfWork, _repoFactory, new ContentService(_unitOfWork), new MediaService(_unitOfWork, _repoFactory)); var contentType = new ContentType(-1); contentType.Name = contentTypeName; contentType.Alias = contentTypeAlias; contentType.Thumbnail = string.Empty; contentTypeService.Save(contentType); Assert.Greater(contentType.Id, 0); var parentContent = new Content(name, -1, contentType); parentContent.Key = new Guid("{4172C94F-52C1-4301-9CDA-FD2142496C95}"); contentService.Save(parentContent); var content = new Content(name, parentContent.Id, contentType); content.Key = new Guid("{C382AE57-D325-4357-A32A-0A959BBD4101}"); contentService.Save(content); } public class Stub { public string Property { get; set; } } #endregion } }
/* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using Common.Logging; using Spring.Collections; using Spring.Core; using Spring.Core.TypeConversion; using Spring.Core.TypeResolution; using Spring.Objects.Factory.Config; using Spring.Util; using System.Linq; namespace Spring.Objects.Factory.Support { /// <summary> /// Helper class for resolving constructors and factory methods. /// Performs constructor resolution through argument matching. /// </summary> /// <remarks> /// Operates on a <see cref="AbstractObjectFactory"/> and an <see cref="IInstantiationStrategy"/>. /// Used by <see cref="AbstractAutowireCapableObjectFactory"/>. /// </remarks> /// <author>Juergen Hoeller</author> /// <author>Mark Pollack</author> public class ConstructorResolver { private readonly ILog log = LogManager.GetLogger(typeof(ConstructorResolver)); private readonly AbstractObjectFactory objectFactory; private readonly IAutowireCapableObjectFactory autowireFactory; private readonly IInstantiationStrategy instantiationStrategy; private readonly ObjectDefinitionValueResolver valueResolver; /// <summary> /// Initializes a new instance of the <see cref="ConstructorResolver"/> class for the given factory /// and instantiation strategy. /// </summary> /// <param name="objectFactory">The object factory to work with.</param> /// <param name="autowireFactory">The object factory as IAutowireCapableObjectFactory.</param> /// <param name="instantiationStrategy">The instantiation strategy for creating objects.</param> /// <param name="valueResolver">the resolver to resolve property value placeholders if any</param> public ConstructorResolver(AbstractObjectFactory objectFactory, IAutowireCapableObjectFactory autowireFactory, IInstantiationStrategy instantiationStrategy, ObjectDefinitionValueResolver valueResolver) { this.objectFactory = objectFactory; this.autowireFactory = autowireFactory; this.instantiationStrategy = instantiationStrategy; this.valueResolver = valueResolver; } /// <summary> /// "autowire constructor" (with constructor arguments by type) behavior. /// Also applied if explicit constructor argument values are specified, /// matching all remaining arguments with objects from the object factory. /// </summary> /// <para> /// This corresponds to constructor injection: In this mode, a Spring /// object factory is able to host components that expect constructor-based /// dependency resolution. /// </para> /// <param name="objectName">Name of the object.</param> /// <param name="rod">The merged object definition for the object.</param> /// <param name="chosenCtors">The chosen chosen candidate constructors (or <code>null</code> if none).</param> /// <param name="explicitArgs">The explicit argument values passed in programmatically via the getBean method, /// or <code>null</code> if none (-> use constructor argument values from object definition)</param> /// <returns>An IObjectWrapper for the new instance</returns> public IObjectWrapper AutowireConstructor(string objectName, RootObjectDefinition rod, ConstructorInfo[] chosenCtors, object[] explicitArgs) { ObjectWrapper wrapper = new ObjectWrapper(); ConstructorInstantiationInfo constructorInstantiationInfo = GetConstructorInstantiationInfo( objectName, rod, chosenCtors, explicitArgs); wrapper.WrappedInstance = instantiationStrategy.Instantiate(rod, objectName, objectFactory, constructorInstantiationInfo.ConstructorInfo, constructorInstantiationInfo.ArgInstances); if (log.IsDebugEnabled) { log.Debug( $"Object '{objectName}' instantiated via constructor [{constructorInstantiationInfo.ConstructorInfo}]."); } return wrapper; } /// <summary> /// Gets the constructor instantiation info given the object definition. /// </summary> /// <param name="objectName">Name of the object.</param> /// <param name="rod">The RootObjectDefinition</param> /// <param name="chosenConstructors">The explicitly chosen ctors.</param> /// <param name="explicitArgs">The explicit chose ctor args.</param> /// <returns>A ConstructorInstantiationInfo containg the specified constructor in the RootObjectDefinition or /// one based on type matching.</returns> public ConstructorInstantiationInfo GetConstructorInstantiationInfo( string objectName, RootObjectDefinition rod, ConstructorInfo[] chosenConstructors, object[] explicitArgs) { object[] argsToUse = null; if (explicitArgs != null) { argsToUse = explicitArgs; } else { //TODO performance optmization on cached ctors. } // Need to resolve the constructor. bool autowiring = chosenConstructors != null || rod.ResolvedAutowireMode == AutoWiringMode.Constructor; ConstructorArgumentValues resolvedValues = null; ObjectWrapper wrapper = null; ConstructorInfo constructorToUse = null; int minNrOfArgs; if (explicitArgs != null) { minNrOfArgs = explicitArgs.Length; } else { ConstructorArgumentValues cargs = rod.ConstructorArgumentValues; resolvedValues = new ConstructorArgumentValues(); wrapper = new ObjectWrapper(); minNrOfArgs = ResolveConstructorArguments(objectName, rod, wrapper, cargs, resolvedValues); } // Take specified constructors, if any. ConstructorInfo[] candidates = chosenConstructors ?? AutowireUtils.GetConstructors(rod, 0); AutowireUtils.SortConstructors(candidates); int minTypeDiffWeight = int.MaxValue; for (int i = 0; i < candidates.Length; i++) { ConstructorInfo candidate = candidates[i]; var parameters = candidate.GetParameters(); if (constructorToUse != null && argsToUse.Length > parameters.Length) { // already found greedy constructor that can be satisfied, so // don't look any further, there are only less greedy constructors left... break; } if (parameters.Length < minNrOfArgs) { throw new ObjectCreationException(rod.ResourceDescription, objectName, $"'{minNrOfArgs}' constructor arguments specified but no matching constructor found " + $"in object '{objectName}' (hint: specify argument indexes, names, or " + "types to avoid ambiguities)."); } Type[] paramTypes = ReflectionUtils.GetParameterTypes(parameters); ArgumentsHolder args; if (resolvedValues != null) { // Try to resolve arguments for current constructor //need to check for null as indicator of no ctor arg match instead of using exceptions for flow //control as in the Java implementation args = CreateArgumentArray( objectName, rod, resolvedValues, wrapper, paramTypes, candidate, autowiring, out var unsatisfiedDependencyExceptionData); if (args == null) { if (i == candidates.Length - 1 && constructorToUse == null) { throw new UnsatisfiedDependencyException(rod.ResourceDescription, objectName, unsatisfiedDependencyExceptionData.ParameterIndex, unsatisfiedDependencyExceptionData.ParameterType, unsatisfiedDependencyExceptionData.ErrorMessage); } // try next constructor... continue; } } else { // Explicit arguments given -> arguments length must match exactly if (parameters.Length != explicitArgs.Length) { continue; } args = ArgumentsHolder.Create(explicitArgs); } int typeDiffWeight = args.GetTypeDifferenceWeight(paramTypes); // Choose this constructor if it represents the closest match. if (typeDiffWeight < minTypeDiffWeight) { constructorToUse = candidate; argsToUse = args.arguments; minTypeDiffWeight = typeDiffWeight; } } if (constructorToUse == null) { throw new ObjectCreationException(rod.ResourceDescription, objectName, "Could not resolve matching constructor."); } return new ConstructorInstantiationInfo(constructorToUse, argsToUse); } /// <summary> /// Instantiate an object instance using a named factory method. /// </summary> /// <remarks> /// <p> /// The method may be static, if the <paramref name="definition"/> /// parameter specifies a class, rather than a /// <see cref="Spring.Objects.Factory.IFactoryObject"/> instance, or an /// instance variable on a factory object itself configured using Dependency /// Injection. /// </p> /// <p> /// Implementation requires iterating over the static or instance methods /// with the name specified in the supplied <paramref name="definition"/> /// (the method may be overloaded) and trying to match with the parameters. /// We don't have the types attached to constructor args, so trial and error /// is the only way to go here. /// </p> /// </remarks> /// <param name="name"> /// The name associated with the supplied <paramref name="definition"/>. /// </param> /// <param name="definition"> /// The definition describing the instance that is to be instantiated. /// </param> /// <param name="arguments"> /// Any arguments to the factory method that is to be invoked. /// </param> /// <returns> /// The result of the factory method invocation (the instance). /// </returns> public virtual IObjectWrapper InstantiateUsingFactoryMethod(string name, RootObjectDefinition definition, object[] arguments) { ObjectWrapper wrapper = new ObjectWrapper(); Type factoryClass = null; bool isStatic = true; ConstructorArgumentValues cargs = definition.ConstructorArgumentValues; ConstructorArgumentValues resolvedValues = new ConstructorArgumentValues(); int expectedArgCount = 0; // we don't have arguments passed in programmatically, so we need to resolve the // arguments specified in the constructor arguments held in the object definition... if (arguments == null || arguments.Length == 0) { expectedArgCount = cargs.ArgumentCount; ResolveConstructorArguments(name, definition, wrapper, cargs, resolvedValues); } else { // if we have constructor args, don't need to resolve them... expectedArgCount = arguments.Length; } if (StringUtils.HasText(definition.FactoryObjectName)) { // it's an instance method on the factory object's class... factoryClass = objectFactory.GetObject(definition.FactoryObjectName).GetType(); isStatic = false; } else { // it's a static factory method on the object class... factoryClass = definition.ObjectType; } GenericArgumentsHolder genericArgsInfo = new GenericArgumentsHolder(definition.FactoryMethodName); IList<MethodInfo> factoryMethodCandidates = FindMethods(genericArgsInfo.GenericMethodName, expectedArgCount, isStatic, factoryClass); bool autowiring = (definition.AutowireMode == AutoWiringMode.Constructor); // try all matching methods to see if they match the constructor arguments... for (int i = 0; i < factoryMethodCandidates.Count; i++) { MethodInfo factoryMethodCandidate = factoryMethodCandidates[i]; if (genericArgsInfo.ContainsGenericArguments) { string[] unresolvedGenericArgs = genericArgsInfo.GetGenericArguments(); if (factoryMethodCandidate.GetGenericArguments().Length != unresolvedGenericArgs.Length) continue; Type[] paramTypes = new Type[unresolvedGenericArgs.Length]; for (int j = 0; j < unresolvedGenericArgs.Length; j++) { paramTypes[j] = TypeResolutionUtils.ResolveType(unresolvedGenericArgs[j]); } factoryMethodCandidate = factoryMethodCandidate.MakeGenericMethod(paramTypes); } if (arguments == null || arguments.Length == 0) { Type[] paramTypes = ReflectionUtils.GetParameterTypes(factoryMethodCandidate.GetParameters()); // try to create the required arguments... UnsatisfiedDependencyExceptionData unsatisfiedDependencyExceptionData = null; ArgumentsHolder args = CreateArgumentArray(name, definition, resolvedValues, wrapper, paramTypes, factoryMethodCandidate, autowiring, out unsatisfiedDependencyExceptionData); if (args == null) { arguments = null; // if we failed to match this method, keep // trying new overloaded factory methods... continue; } else { arguments = args.arguments; } } // if we get here, we found a usable candidate factory method - check, if arguments match //arguments = (arguments.Length == 0 ? null : arguments); if (ReflectionUtils.GetMethodByArgumentValues(new MethodInfo[] { factoryMethodCandidate }, arguments) == null) { continue; } object objectInstance = instantiationStrategy.Instantiate(definition, name, objectFactory, factoryMethodCandidate, arguments); wrapper.WrappedInstance = objectInstance; if (log.IsDebugEnabled) { log.Debug($"Object '{name}' instantiated via factory method [{factoryMethodCandidate}]."); } return wrapper; } // if we get here, we didn't match any method... throw new ObjectDefinitionStoreException( $"Cannot find matching factory method '{definition.FactoryMethodName} on Type [{factoryClass}]."); } /// <summary> /// Create an array of arguments to invoke a constructor or static factory method, /// given the resolved constructor arguments values. /// </summary> /// <remarks>When return value is null the out parameter UnsatisfiedDependencyExceptionData will contain /// information for use in throwing a UnsatisfiedDependencyException by the caller. This avoids using /// exceptions for flow control as in the original implementation.</remarks> private ArgumentsHolder CreateArgumentArray( string objectName, RootObjectDefinition rod, ConstructorArgumentValues resolvedValues, ObjectWrapper wrapper, Type[] paramTypes, MethodBase methodOrCtorInfo, bool autowiring, out UnsatisfiedDependencyExceptionData unsatisfiedDependencyExceptionData) { string GetMethodType() { return methodOrCtorInfo is ConstructorInfo ? "constructor" : "factory method"; } unsatisfiedDependencyExceptionData = null; if (paramTypes.Length == 0) { return ArgumentsHolder.Empty; } ArgumentsHolder args = new ArgumentsHolder(paramTypes.Length); var usedValueHolders = new HybridSet(); List<string> autowiredObjectNames = null; ParameterInfo[] argTypes = methodOrCtorInfo.GetParameters(); for (int paramIndex = 0; paramIndex < paramTypes.Length; paramIndex++) { Type paramType = paramTypes[paramIndex]; string parameterName = argTypes[paramIndex].Name; // If we couldn't find a direct match and are not supposed to autowire, // let's try the next generic, untyped argument value as fallback: // it could match after type conversion (for example, String -> int). ConstructorArgumentValues.ValueHolder valueHolder = null; if (resolvedValues.GetNamedArgumentValue(parameterName) != null) { valueHolder = resolvedValues.GetArgumentValue(parameterName, paramType, usedValueHolders); } else { valueHolder = resolvedValues.GetArgumentValue(paramIndex, paramType, usedValueHolders); } if (valueHolder == null && !autowiring) { valueHolder = resolvedValues.GetGenericArgumentValue(null, usedValueHolders); } if (valueHolder != null) { // We found a potential match - let's give it a try. // Do not consider the same value definition multiple times! usedValueHolders.Add(valueHolder); args.rawArguments[paramIndex] = valueHolder.Value; try { object originalValue = valueHolder.Value; object convertedValue = TypeConversionUtils.ConvertValueIfNecessary(paramType, originalValue, null); args.arguments[paramIndex] = convertedValue; //? args.preparedArguments[paramIndex] = convertedValue; } catch (TypeMismatchException ex) { // to avoid using exceptions for flow control, this is not a cost in Java as stack trace is lazily created. string errorMessage = $"Could not convert {GetMethodType()} argument value [{valueHolder.Value}] to required type [{paramType}] : {ex.Message}"; unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage); return null; } } else { // No explicit match found: we're either supposed to autowire or // have to fail creating an argument array for the given constructor. if (!autowiring) { string errorMessage = $"Ambiguous {GetMethodType()} argument types - " + $"Did you specify the correct object references as {GetMethodType()} arguments?"; unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage); return null; } try { MethodParameter param = MethodParameter.ForMethodOrConstructor(methodOrCtorInfo, paramIndex); autowiredObjectNames = new List<string>(); object autowiredArgument = ResolveAutoWiredArgument(param, objectName, autowiredObjectNames); args.rawArguments[paramIndex] = autowiredArgument; args.arguments[paramIndex] = autowiredArgument; args.preparedArguments[paramIndex] = new AutowiredArgumentMarker(); } catch (ObjectsException ex) { unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, ex.Message); return null; } } } if (log.IsDebugEnabled && autowiredObjectNames != null) { for (var i = 0; i < autowiredObjectNames.Count; i++) { string autowiredObjectName = autowiredObjectNames[i]; log.Debug( $"Autowiring by type from object name '{objectName}' via {GetMethodType()} to object named '{autowiredObjectName}'"); } } return args; } private class AutowiredArgumentMarker { } private object ResolveAutoWiredArgument( MethodParameter methodParameter, string objectName, List<string> autowiredObjectNames) { return autowireFactory.ResolveDependency( new DependencyDescriptor(methodParameter, true), objectName, autowiredObjectNames); } /// <summary> /// Resolves the <see cref="Spring.Objects.Factory.Config.ConstructorArgumentValues"/> /// of the supplied <paramref name="definition"/>. /// </summary> /// <param name="objectName">The name of the object that is being resolved by this factory.</param> /// <param name="definition">The rod.</param> /// <param name="wrapper">The wrapper.</param> /// <param name="cargs">The cargs.</param> /// <param name="resolvedValues">Where the resolved constructor arguments will be placed.</param> /// <returns> /// The minimum number of arguments that any constructor for the supplied /// <paramref name="definition"/> must have. /// </returns> /// <remarks> /// <p> /// 'Resolve' can be taken to mean that all of the <paramref name="definition"/>s /// constructor arguments is resolved into a concrete object that can be plugged /// into one of the <paramref name="definition"/>s constructors. Runtime object /// references to other objects in this (or a parent) factory are resolved, /// type conversion is performed, etc. /// </p> /// <p> /// These resolved values are plugged into the supplied /// <paramref name="resolvedValues"/> object, because we wouldn't want to touch /// the <paramref name="definition"/>s constructor arguments in case it (or any of /// its constructor arguments) is a prototype object definition. /// </p> /// <p> /// This method is also used for handling invocations of static factory methods. /// </p> /// </remarks> private int ResolveConstructorArguments(string objectName, RootObjectDefinition definition, ObjectWrapper wrapper, ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) { // ObjectDefinitionValueResolver valueResolver = new ObjectDefinitionValueResolver(objectFactory); int minNrOfArgs = cargs.ArgumentCount; if (cargs._indexedArgumentValues != null) { foreach (var entry in cargs._indexedArgumentValues) { int index = entry.Key; if (index < 0) { throw new ObjectCreationException( definition.ResourceDescription, objectName, $"Invalid constructor argument index: {index}"); } if (index > minNrOfArgs) { minNrOfArgs = index + 1; } ConstructorArgumentValues.ValueHolder valueHolder = entry.Value; string argName = "constructor argument with index " + index; object resolvedValue = valueResolver.ResolveValueIfNecessary(objectName, definition, argName, valueHolder.Value); resolvedValues.AddIndexedArgumentValue(index, resolvedValue, StringUtils.HasText(valueHolder.Type) ? TypeResolutionUtils.ResolveType(valueHolder.Type).AssemblyQualifiedName : null); } } if (definition.ConstructorArgumentValues._genericArgumentValues != null) { const string argName = "constructor argument"; for (var i = 0; i < definition.ConstructorArgumentValues._genericArgumentValues.Count; i++) { var valueHolder = definition.ConstructorArgumentValues._genericArgumentValues[i]; object resolvedValue = valueResolver.ResolveValueIfNecessary(objectName, definition, argName, valueHolder.Value); resolvedValues.AddGenericArgumentValue( resolvedValue, StringUtils.HasText(valueHolder.Type) ? TypeResolutionUtils.ResolveType(valueHolder.Type).AssemblyQualifiedName : null); } } if (definition.ConstructorArgumentValues._namedArgumentValues != null) { foreach (var entry in definition.ConstructorArgumentValues._namedArgumentValues) { string argumentName = entry.Key; string syntheticArgumentName = "constructor argument with name " + argumentName; ConstructorArgumentValues.ValueHolder valueHolder = entry.Value; object resolvedValue = valueResolver.ResolveValueIfNecessary(objectName, definition, syntheticArgumentName, valueHolder.Value); resolvedValues.AddNamedArgumentValue(argumentName, resolvedValue); } } return minNrOfArgs; } /// <summary> /// Returns an array of all of those /// <see cref="System.Reflection.MethodInfo">methods</see> exposed on the /// <paramref name="searchType"/> that match the supplied criteria. /// </summary> /// <param name="methodName"> /// Methods that have this name (can be in the form of a regular expression). /// </param> /// <param name="expectedArgumentCount"> /// Methods that have exactly this many arguments. /// </param> /// <param name="isStatic"> /// Methods that are static / instance. /// </param> /// <param name="searchType"> /// The <see cref="System.Type"/> on which the methods (if any) are to be found. /// </param> /// <returns> /// An array of all of those /// <see cref="System.Reflection.MethodInfo">methods</see> exposed on the /// <paramref name="searchType"/> that match the supplied criteria. /// </returns> private static IList<MethodInfo> FindMethods(string methodName, int expectedArgumentCount, bool isStatic, Type searchType) { ComposedCriteria methodCriteria = new ComposedCriteria(); methodCriteria.Add(new MethodNameMatchCriteria(methodName)); methodCriteria.Add(new MethodParametersCountCriteria(expectedArgumentCount)); BindingFlags methodFlags = BindingFlags.Public | BindingFlags.IgnoreCase | (isStatic ? BindingFlags.Static : BindingFlags.Instance); MemberInfo[] methods = searchType.FindMembers(MemberTypes.Method, methodFlags, new CriteriaMemberFilter().FilterMemberByCriteria, methodCriteria); return methods.Cast<MethodInfo>().ToArray(); } private class ArgumentsHolder { internal static readonly ArgumentsHolder Empty = new ArgumentsHolder(0); public readonly object[] rawArguments; public readonly object[] arguments; public readonly object[] preparedArguments; public ArgumentsHolder(int size) { rawArguments = size == 0 ? ObjectUtils.EmptyObjects : new object[size]; arguments = size == 0 ? ObjectUtils.EmptyObjects : new object[size]; preparedArguments = size == 0 ? ObjectUtils.EmptyObjects : new object[size]; } private ArgumentsHolder(object[] args) { rawArguments = args; arguments = args; preparedArguments = args; } public static ArgumentsHolder Create(object[] args) { if (args.Length == 0) { return Empty; } return new ArgumentsHolder(args); } public static ArgumentsHolder Create(int size) { if (size == 0) { return Empty; } return new ArgumentsHolder(size); } public int GetTypeDifferenceWeight(Type[] paramTypes) { // If valid arguments found, determine type difference weight. // Try type difference weight on both the converted arguments and // the raw arguments. If the raw weight is better, use it. // Decrease raw weight by 1024 to prefer it over equal converted weight. int typeDiffWeight = AutowireUtils.GetTypeDifferenceWeight(paramTypes, arguments); int rawTypeDiffWeight = AutowireUtils.GetTypeDifferenceWeight(paramTypes, rawArguments) - 1024; return (rawTypeDiffWeight < typeDiffWeight ? rawTypeDiffWeight : typeDiffWeight); } } } }
#if false /* ** $Id: ldump.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $ ** save precompiled Lua chunks ** See Copyright Notice in lua.h */ using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; using System.Runtime.Serialization; namespace SharpLua { using lua_Number = System.Double; using TValue = Lua.lua_TValue; public partial class Lua { public class DumpState { public LuaState L; public lua_Writer writer; public object data; public int strip; public int status; }; public static void DumpMem(object b, DumpState D) { #if XBOX || SILVERLIGHT // todo: implement this - mjf Debug.Assert(false); #else //Console.WriteLine(b.GetType().ToString() + ":::" + b.ToString()); //uint size = (uint)Marshal.SizeOf(b); //D.status = D.writer(D.L, new CharPtr(b.ToString()), size, D.data); ///* int size = Marshal.SizeOf(b); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(b, ptr, false); byte[] bytes = new byte[size]; Marshal.Copy(ptr, bytes, 0, size); char[] ch = new char[bytes.Length]; for (int i = 0; i < bytes.Length; i++) ch[i] = (char)bytes[i]; CharPtr str = ch; DumpBlock(str, (uint)str.chars.Length, D); Marshal.Release(ptr); // */ #endif } public static void DumpMem(object b, int n, DumpState D) { Array array = b as Array; // Fix for stripped debug info. Debug.Assert(array.Length == n || (D.strip != 0 && array.Length == 0)); for (int i = 0; i < n; i++) DumpMem(array.GetValue(i), D); } public static void DumpVar(object x, DumpState D) { DumpMem(x, D); } private static void DumpBlock(CharPtr b, uint size, DumpState D) { if (D.status == 0) { lua_unlock(D.L); D.status = D.writer(D.L, b, size, D.data); lua_lock(D.L); } } private static void DumpChar(int y, DumpState D) { char x = (char)y; DumpVar(x, D); } private static void DumpInt(int x, DumpState D) { DumpVar(x, D); } private static void DumpNumber(lua_Number x, DumpState D) { DumpVar(x, D); } static void DumpVector(object b, int n, DumpState D) { DumpInt(n, D); DumpMem(b, n, D); } private static void DumpString(TString s, DumpState D) { if (s == null || getstr(s) == null) { uint size = 0; DumpVar(size, D); } else { uint size = s.tsv.len + 1; /* include trailing '\0' */ DumpVar(size, D); DumpBlock(getstr(s), size, D); } } private static void DumpCode(Proto f, DumpState D) { DumpVector(f.code, f.sizecode, D); } private static void DumpConstants(Proto f, DumpState D) { int i, n = f.sizek; DumpInt(n, D); for (i = 0; i < n; i++) { /*const*/ TValue o = f.k[i]; DumpChar(ttype(o), D); switch (ttype(o)) { case LUA_TNIL: break; case LUA_TBOOLEAN: DumpChar(bvalue(o), D); break; case LUA_TNUMBER: DumpNumber(nvalue(o), D); break; case LUA_TSTRING: DumpString(rawtsvalue(o), D); break; default: lua_assert(0); /* cannot happen */ break; } } n = f.sizep; DumpInt(n, D); for (i = 0; i < n; i++) DumpFunction(f.p[i], f.source, D); } private static void DumpDebug(Proto f, DumpState D) { int i, n; n = (D.strip != 0) ? 0 : f.sizelineinfo; DumpVector(f.lineinfo, n, D); n = (D.strip != 0) ? 0 : f.sizelocvars; DumpInt(n, D); for (i = 0; i < n; i++) { DumpString(f.locvars[i].varname, D); DumpInt(f.locvars[i].startpc, D); DumpInt(f.locvars[i].endpc, D); } n = (D.strip != 0) ? 0 : f.sizeupvalues; DumpInt(n, D); for (i = 0; i < n; i++) DumpString(f.upvalues[i], D); } private static void DumpFunction(Proto f, TString p, DumpState D) { DumpString(((f.source == p) || (D.strip != 0)) ? null : f.source, D); DumpInt(f.linedefined, D); DumpInt(f.lastlinedefined, D); DumpChar(f.nups, D); DumpChar(f.numparams, D); DumpChar(f.is_vararg, D); DumpChar(f.maxstacksize, D); DumpCode(f, D); DumpConstants(f, D); DumpDebug(f, D); } private static void DumpHeader(DumpState D) { CharPtr h = new char[LUAC_HEADERSIZE]; luaU_header(h); DumpBlock(h, LUAC_HEADERSIZE, D); } /* ** dump Lua function as precompiled chunk */ public static int luaU_dump(LuaState L, Proto f, lua_Writer w, object data, int strip) { DumpState D = new DumpState(); D.L = L; D.writer = w; D.data = data; D.strip = strip; D.status = 0; DumpHeader(D); DumpFunction(f, null, D); return D.status; } } } #else /* ** $Id: ldump.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $ ** save precompiled Lua chunks ** See Copyright Notice in lua.h */ using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; using System.Runtime.Serialization; namespace SharpLua { using lua_Number = System.Double; using TValue = Lua.lua_TValue; public partial class Lua { public class DumpState { public LuaState L; public lua_Writer writer; public object data; public int strip; public int status; }; public static void DumpMem(byte[] b, DumpState D) { #if XBOX || SILVERLIGHT // todo: implement this - mjf Debug.Assert(false); #else char[] ch = new char[b.Length]; for (int i = 0; i < b.Length; i++) ch[i] = (char)b[i]; CharPtr str = ch; DumpBlock(str, (uint)str.chars.Length, D); #endif } private static void DumpBlock(CharPtr b, uint size, DumpState D) { if (D.status == 0) { lua_unlock(D.L); D.status = D.writer(D.L, b, size, D.data); lua_lock(D.L); } } private static void DumpByte(int y, DumpState D) { byte[] x = new byte[1]; x[0] = (byte)y; DumpMem(x, D); } private static void DumpInt(int x, DumpState D) { byte[] b = BitConverter.GetBytes((UInt32) x); if (!BitConverter.IsLittleEndian) Array.Reverse(b); DumpMem(b, D); } private static void DumpNumber(lua_Number x, DumpState D) { DumpMem(BitConverter.GetBytes(x), D); } private static void DumpString(TString s, DumpState D) { if (s == null || getstr(s) == null) { uint size = 0; DumpInt((int)size, D); } else { uint size = s.tsv.len + 1; /* include trailing '\0' */ DumpInt((int)size, D); DumpBlock(getstr(s), size, D); } } private static void DumpCode(Proto f, DumpState D) { DumpInt(f.sizecode, D); for (int i = 0; i < f.sizecode; i++) DumpInt((int)f.code[i], D); } private static void DumpConstants(Proto f, DumpState D) { int i, n = f.sizek; DumpInt(n, D); for (i = 0; i < n; i++) { /*const*/ TValue o = f.k[i]; DumpByte(ttype(o), D); switch (ttype(o)) { case LUA_TNIL: break; case LUA_TBOOLEAN: DumpByte(bvalue(o), D); break; case LUA_TNUMBER: DumpNumber(nvalue(o), D); break; case LUA_TSTRING: DumpString(rawtsvalue(o), D); break; default: lua_assert(0); /* cannot happen */ break; } } n = f.sizep; DumpInt(n, D); for (i = 0; i < n; i++) DumpFunction(f.p[i], f.source, D); } private static void DumpDebug(Proto f, DumpState D) { int i, n; n = (D.strip != 0) ? 0 : f.sizelineinfo; DumpInt(n, D); for (i = 0; i < n; i++) DumpInt(f.lineinfo[i], D); n = (D.strip != 0) ? 0 : f.sizelocvars; DumpInt(n, D); for (i = 0; i < n; i++) { DumpString(f.locvars[i].varname, D); DumpInt(f.locvars[i].startpc, D); DumpInt(f.locvars[i].endpc, D); } n = (D.strip != 0) ? 0 : f.sizeupvalues; DumpInt(n, D); for (i = 0; i < n; i++) DumpString(f.upvalues[i], D); } private static void DumpFunction(Proto f, TString p, DumpState D) { DumpString(((f.source == p) || (D.strip != 0)) ? null : f.source, D); DumpInt(f.linedefined, D); DumpInt(f.lastlinedefined, D); DumpByte(f.nups, D); DumpByte(f.numparams, D); DumpByte(f.is_vararg, D); DumpByte(f.maxstacksize, D); DumpCode(f, D); DumpConstants(f, D); DumpDebug(f, D); } private static void DumpHeader(DumpState D) { CharPtr h = new char[LUAC_HEADERSIZE]; luaU_header(h); DumpBlock(h, LUAC_HEADERSIZE, D); } /* ** dump Lua function as precompiled chunk */ public static int luaU_dump(LuaState L, Proto f, lua_Writer w, object data, int strip) { DumpState D = new DumpState(); D.L = L; D.writer = w; D.data = data; D.strip = strip; D.status = 0; DumpHeader(D); DumpFunction(f, null, D); return D.status; } } } #endif
/* * 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 Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Messages.Linden; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections; using System.Reflection; using Caps = OpenSim.Framework.Capabilities.Caps; using ExtraParamType = OpenMetaverse.ExtraParamType; using OSDMap = OpenMetaverse.StructuredData.OSDMap; namespace OpenSim.Region.ClientStack.Linden { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UploadObjectAssetModule")] public class UploadObjectAssetModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; #region Region Module interfaceBase Members public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { } public void AddRegion(Scene pScene) { m_scene = pScene; } public void RemoveRegion(Scene scene) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; m_scene = null; } public void RegionLoaded(Scene scene) { m_scene.EventManager.OnRegisterCaps += RegisterCaps; } #endregion #region Region Module interface public void Close() { } public string Name { get { return "UploadObjectAssetModuleModule"; } } public void RegisterCaps(UUID agentID, Caps caps) { UUID capID = UUID.Random(); // m_log.Debug("[UPLOAD OBJECT ASSET MODULE]: /CAPS/" + capID); caps.RegisterHandler( "UploadObjectAsset", new RestHTTPHandler( "POST", "/CAPS/OA/" + capID + "/", httpMethod => ProcessAdd(httpMethod, agentID, caps), "UploadObjectAsset", agentID.ToString())); /* caps.RegisterHandler("NewFileAgentInventoryVariablePrice", new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDNewFileAngentInventoryVariablePriceReplyResponse>("POST", "/CAPS/" + capID.ToString(), delegate(LLSDAssetUploadRequest req) { return NewAgentInventoryRequest(req,agentID); })); */ } #endregion /// <summary> /// Parses add request /// </summary> /// <param name="request"></param> /// <param name="AgentId"></param> /// <param name="cap"></param> /// <returns></returns> public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap) { Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 400; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = "Request wasn't what was expected"; ScenePresence avatar; if (!m_scene.TryGetScenePresence(AgentId, out avatar)) return responsedata; OSDMap r = (OSDMap)OSDParser.Deserialize((string)request["requestbody"]); UploadObjectAssetMessage message = new UploadObjectAssetMessage(); try { message.Deserialize(r); } catch (Exception ex) { m_log.Error("[UPLOAD OBJECT ASSET MODULE]: Error deserializing message " + ex.ToString()); message = null; } if (message == null) { responsedata["int_response_code"] = 400; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = "<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>"; return responsedata; } Vector3 pos = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation); Quaternion rot = Quaternion.Identity; Vector3 rootpos = Vector3.Zero; // Quaternion rootrot = Quaternion.Identity; SceneObjectGroup rootGroup = null; SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length]; for (int i = 0; i < message.Objects.Length; i++) { UploadObjectAssetMessage.Object obj = message.Objects[i]; PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox(); if (i == 0) { rootpos = obj.Position; // rootrot = obj.Rotation; } // Combine the extraparams data into it's ugly blob again.... //int bytelength = 0; //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++) //{ // bytelength += obj.ExtraParams[extparams].ExtraParamData.Length; //} //byte[] extraparams = new byte[bytelength]; //int position = 0; //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++) //{ // Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position, // obj.ExtraParams[extparams].ExtraParamData.Length); // // position += obj.ExtraParams[extparams].ExtraParamData.Length; // } //pbs.ExtraParams = extraparams; for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++) { UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[extparams]; switch ((ushort)extraParam.Type) { case (ushort)ExtraParamType.Sculpt: Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0); pbs.SculptEntry = true; pbs.SculptTexture = obj.SculptID; pbs.SculptType = (byte)sculpt.Type; break; case (ushort)ExtraParamType.Flexible: Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0); pbs.FlexiEntry = true; pbs.FlexiDrag = flex.Drag; pbs.FlexiForceX = flex.Force.X; pbs.FlexiForceY = flex.Force.Y; pbs.FlexiForceZ = flex.Force.Z; pbs.FlexiGravity = flex.Gravity; pbs.FlexiSoftness = flex.Softness; pbs.FlexiTension = flex.Tension; pbs.FlexiWind = flex.Wind; break; case (ushort)ExtraParamType.Light: Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0); pbs.LightColorA = light.Color.A; pbs.LightColorB = light.Color.B; pbs.LightColorG = light.Color.G; pbs.LightColorR = light.Color.R; pbs.LightCutoff = light.Cutoff; pbs.LightEntry = true; pbs.LightFalloff = light.Falloff; pbs.LightIntensity = light.Intensity; pbs.LightRadius = light.Radius; break; case 0x40: pbs.ReadProjectionData(extraParam.ExtraParamData, 0); break; } } pbs.PathBegin = (ushort) obj.PathBegin; pbs.PathCurve = (byte) obj.PathCurve; pbs.PathEnd = (ushort) obj.PathEnd; pbs.PathRadiusOffset = (sbyte) obj.RadiusOffset; pbs.PathRevolutions = (byte) obj.Revolutions; pbs.PathScaleX = (byte) obj.ScaleX; pbs.PathScaleY = (byte) obj.ScaleY; pbs.PathShearX = (byte) obj.ShearX; pbs.PathShearY = (byte) obj.ShearY; pbs.PathSkew = (sbyte) obj.Skew; pbs.PathTaperX = (sbyte) obj.TaperX; pbs.PathTaperY = (sbyte) obj.TaperY; pbs.PathTwist = (sbyte) obj.Twist; pbs.PathTwistBegin = (sbyte) obj.TwistBegin; pbs.HollowShape = (HollowShape) obj.ProfileHollow; pbs.PCode = (byte) PCode.Prim; pbs.ProfileBegin = (ushort) obj.ProfileBegin; pbs.ProfileCurve = (byte) obj.ProfileCurve; pbs.ProfileEnd = (ushort) obj.ProfileEnd; pbs.Scale = obj.Scale; pbs.State = (byte) 0; pbs.LastAttachPoint = (byte) 0; SceneObjectPart prim = new SceneObjectPart(); prim.UUID = UUID.Random(); prim.CreatorID = AgentId; prim.OwnerID = AgentId; prim.GroupID = obj.GroupID; prim.LastOwnerID = prim.OwnerID; prim.CreationDate = Util.UnixTimeSinceEpoch(); prim.Name = obj.Name; prim.Description = ""; prim.PayPrice[0] = -2; prim.PayPrice[1] = -2; prim.PayPrice[2] = -2; prim.PayPrice[3] = -2; prim.PayPrice[4] = -2; Primitive.TextureEntry tmp = new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f")); for (int j = 0; j < obj.Faces.Length; j++) { UploadObjectAssetMessage.Object.Face face = obj.Faces[j]; Primitive.TextureEntryFace primFace = tmp.CreateFace((uint) j); primFace.Bump = face.Bump; primFace.RGBA = face.Color; primFace.Fullbright = face.Fullbright; primFace.Glow = face.Glow; primFace.TextureID = face.ImageID; primFace.Rotation = face.ImageRot; primFace.MediaFlags = ((face.MediaFlags & 1) != 0); primFace.OffsetU = face.OffsetS; primFace.OffsetV = face.OffsetT; primFace.RepeatU = face.ScaleS; primFace.RepeatV = face.ScaleT; primFace.TexMapType = (MappingType) (face.MediaFlags & 6); } pbs.TextureEntry = tmp.GetBytes(); prim.Shape = pbs; prim.Scale = obj.Scale; SceneObjectGroup grp = new SceneObjectGroup(); grp.SetRootPart(prim); prim.ParentID = 0; if (i == 0) { rootGroup = grp; } grp.AttachToScene(m_scene); grp.AbsolutePosition = obj.Position; prim.RotationOffset = obj.Rotation; // Required for linking grp.RootPart.ClearUpdateSchedule(); if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos)) { m_scene.AddSceneObject(grp); grp.AbsolutePosition = obj.Position; } allparts[i] = grp; } for (int j = 1; j < allparts.Length; j++) { // Required for linking rootGroup.RootPart.ClearUpdateSchedule(); allparts[j].RootPart.ClearUpdateSchedule(); rootGroup.LinkToGroup(allparts[j]); } rootGroup.ScheduleGroupForFullUpdate(); pos = m_scene.GetNewRezLocation( Vector3.Zero, rootpos, UUID.Zero, rot, (byte)1, 1, true, allparts[0].GroupScale, false); responsedata["int_response_code"] = 200; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(allparts[0].LocalId)); return responsedata; } private string ConvertUintToBytes(uint val) { byte[] resultbytes = Utils.UIntToBytes(val); if (BitConverter.IsLittleEndian) Array.Reverse(resultbytes); return String.Format("<binary encoding=\"base64\">{0}</binary>", Convert.ToBase64String(resultbytes)); } } }
/* * 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 OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; using Tools; namespace OpenSim.Region.ScriptEngine.Shared.CodeTools { public class CSCodeGenerator : ICodeConverter { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string m_coopTerminationCheck = "opensim_reserved_CheckForCoopTermination();"; private SYMBOL m_astRoot = null; private int m_braceCount; private IScriptModuleComms m_comms = null; private int m_CSharpCol; // for indentation private int m_CSharpLine; private int m_indentWidth = 4; private bool m_insertCoopTerminationChecks; private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_positionMap; // for indentation // the current line of generated C# code // the current column of generated C# code private List<string> m_warnings = new List<string>(); /// <summary> /// Keep a record of the previous node when we do the parsing. /// </summary> /// <remarks> /// We do this here because the parser generated by CSTools does not retain a reference to its parent node. /// The previous node is required so we can correctly insert co-op termination checks when required. /// </remarks> // private SYMBOL m_previousNode; /// <summary> /// Creates an 'empty' CSCodeGenerator instance. /// </summary> public CSCodeGenerator() { m_comms = null; ResetCounters(); } public CSCodeGenerator(IScriptModuleComms comms, bool insertCoopTerminationChecks) { m_comms = comms; m_insertCoopTerminationChecks = insertCoopTerminationChecks; ResetCounters(); } /// <summary> /// Get the mapping between LSL and C# line/column number. /// </summary> /// <returns>SYMBOL pointing to root of the abstract syntax tree.</returns> public SYMBOL ASTRoot { get { return m_astRoot; } } /// <summary> /// Get the mapping between LSL and C# line/column number. /// </summary> /// <returns>Dictionary\<KeyValuePair\<int, int\>, KeyValuePair\<int, int\>\>.</returns> public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> PositionMap { get { return m_positionMap; } } /// <summary> /// Generate the code from the AST we have. /// </summary> /// <param name="script">The LSL source as a string.</param> /// <returns>String containing the generated C# code.</returns> public string Convert(string script) { // m_log.DebugFormat("[CS CODE GENERATOR]: Converting to C#\n{0}", script); m_warnings.Clear(); ResetCounters(); Parser p = new LSLSyntax(new yyLSLSyntax(), new ErrorHandler(true)); LSL2CSCodeTransformer codeTransformer; try { codeTransformer = new LSL2CSCodeTransformer(p.Parse(script)); } catch (CSToolsException e) { string message; // LL start numbering lines at 0 - geeks! // Also need to subtract one line we prepend! // string emessage = e.Message; string slinfo = e.slInfo.ToString(); // Remove wrong line number info // if (emessage.StartsWith(slinfo + ": ")) emessage = emessage.Substring(slinfo.Length + 2); message = String.Format("({0},{1}) {2}", e.slInfo.lineNumber - 1, e.slInfo.charPosition - 1, emessage); throw new Exception(message); } m_astRoot = codeTransformer.Transform(); string retstr = String.Empty; // standard preamble //retstr = GenerateLine("using OpenSim.Region.ScriptEngine.Common;"); //retstr += GenerateLine("using System.Collections.Generic;"); //retstr += GenerateLine(""); //retstr += GenerateLine("namespace SecondLife"); //retstr += GenerateLine("{"); m_braceCount++; //retstr += GenerateIndentedLine("public class Script : OpenSim.Region.ScriptEngine.Common"); //retstr += GenerateIndentedLine("{"); m_braceCount++; // line number m_CSharpLine += 3; // here's the payload retstr += GenerateLine(); foreach (SYMBOL s in m_astRoot.kids) retstr += GenerateNode(m_astRoot, s); // close braces! m_braceCount--; //retstr += GenerateIndentedLine("}"); m_braceCount--; //retstr += GenerateLine("}"); // Removes all carriage return characters which may be generated in Windows platform. Is there // cleaner way of doing this? retstr = retstr.Replace("\r", ""); return retstr; } /// <summary> /// Get the set of warnings generated during compilation. /// </summary> /// <returns></returns> public string[] GetWarnings() { return m_warnings.ToArray(); } private void AddWarning(string warning) { if (!m_warnings.Contains(warning)) { m_warnings.Add(warning); } } // This code checks for LSL of the following forms, and generates a // warning if it finds them. // // list l = [ "foo" ]; // l = (l=[]) + l + ["bar"]; // (produces l=["foo","bar"] in SL but l=["bar"] in OS) // // integer i; // integer j; // i = (j = 3) + (j = 4) + (j = 5); // (produces j=3 in SL but j=5 in OS) // // Without this check, that code passes compilation, but does not do what // the end user expects, because LSL in SL evaluates right to left instead // of left to right. // // The theory here is that producing an error and alerting the end user that // something needs to change is better than silently generating incorrect code. private void checkForMultipleAssignments(List<string> identifiers, SYMBOL s) { if (s is Assignment) { Assignment a = (Assignment)s; string newident = null; if (a.kids[0] is Declaration) { newident = ((Declaration)a.kids[0]).Id; } else if (a.kids[0] is IDENT) { newident = ((IDENT)a.kids[0]).yytext; } else if (a.kids[0] is IdentDotExpression) { newident = ((IdentDotExpression)a.kids[0]).Name; // +"." + ((IdentDotExpression)a.kids[0]).Member; } else { AddWarning(String.Format("Multiple assignments checker internal error '{0}' at line {1} column {2}.", a.kids[0].GetType(), ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position)); } if (identifiers.Contains(newident)) { AddWarning(String.Format("Multiple assignments to '{0}' at line {1} column {2}; results may differ between LSL and OSSL.", newident, ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position)); } identifiers.Add(newident); } int index; for (index = 0; index < s.kids.Count; index++) { checkForMultipleAssignments(identifiers, (SYMBOL)s.kids[index]); } } /// <summary> /// Returns the passed name with an underscore prepended if that name is a reserved word in C# /// and not resevered in LSL otherwise it just returns the passed name. /// /// This makes no attempt to cache the results to minimise future lookups. For a non trivial /// scripts the number of unique identifiers could easily grow to the size of the reserved word /// list so maintaining a list or dictionary and doing the lookup there firstwould probably not /// give any real speed advantage. /// /// I believe there is a class Microsoft.CSharp.CSharpCodeProvider that has a function /// CreateValidIdentifier(str) that will return either the value of str if it is not a C# /// key word or "_"+str if it is. But availability under Mono? /// </summary> private string CheckName(string s) { if (CSReservedWords.IsReservedWord(s)) return "@" + s; else return s; } /// <summary> /// Prints text. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>String s.</returns> private string Generate(string s) { return Generate(s, null); } /// <summary> /// Prints text. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>String s.</returns> private string Generate(string s, SYMBOL sym) { if (null != sym) m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position)); m_CSharpCol += s.Length; return s; } /// <summary> /// Generates the code for an ArgumentDeclarationList node. /// </summary> /// <param name="adl">The ArgumentDeclarationList node.</param> /// <returns>String containing C# code for ArgumentDeclarationList adl.</returns> private string GenerateArgumentDeclarationList(ArgumentDeclarationList adl) { string retstr = String.Empty; int comma = adl.kids.Count - 1; // tells us whether to print a comma foreach (Declaration d in adl.kids) { retstr += Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d); if (0 < comma--) retstr += Generate(", "); } return retstr; } /// <summary> /// Generates the code for an ArgumentList node. /// </summary> /// <param name="al">The ArgumentList node.</param> /// <returns>String containing C# code for ArgumentList al.</returns> private string GenerateArgumentList(ArgumentList al) { string retstr = String.Empty; int comma = al.kids.Count - 1; // tells us whether to print a comma foreach (SYMBOL s in al.kids) { retstr += GenerateNode(al, s); if (0 < comma--) retstr += Generate(", "); } return retstr; } /// <summary> /// Generates the code for an Assignment node. /// </summary> /// <param name="a">The Assignment node.</param> /// <returns>String containing C# code for Assignment a.</returns> private string GenerateAssignment(Assignment a) { string retstr = String.Empty; List<string> identifiers = new List<string>(); checkForMultipleAssignments(identifiers, a); retstr += GenerateNode(a, (SYMBOL)a.kids.Pop()); retstr += Generate(String.Format(" {0} ", a.AssignmentType), a); foreach (SYMBOL kid in a.kids) retstr += GenerateNode(a, kid); return retstr; } /// <summary> /// Generates the code for a BinaryExpression node. /// </summary> /// <param name="be">The BinaryExpression node.</param> /// <returns>String containing C# code for BinaryExpression be.</returns> private string GenerateBinaryExpression(BinaryExpression be) { string retstr = String.Empty; if (be.ExpressionSymbol.Equals("&&") || be.ExpressionSymbol.Equals("||")) { // special case handling for logical and/or, see Mantis 3174 retstr += "((bool)("; retstr += GenerateNode(be, (SYMBOL)be.kids.Pop()); retstr += "))"; retstr += Generate(String.Format(" {0} ", be.ExpressionSymbol.Substring(0, 1)), be); retstr += "((bool)("; foreach (SYMBOL kid in be.kids) retstr += GenerateNode(be, kid); retstr += "))"; } else { retstr += GenerateNode(be, (SYMBOL)be.kids.Pop()); retstr += Generate(String.Format(" {0} ", be.ExpressionSymbol), be); foreach (SYMBOL kid in be.kids) retstr += GenerateNode(be, kid); } return retstr; } /// <summary> /// Generates the code for a CompoundStatement node. /// </summary> /// <param name="cs">The CompoundStatement node.</param> /// <returns>String containing C# code for CompoundStatement cs.</returns> private string GenerateCompoundStatement(SYMBOL previousSymbol, CompoundStatement cs) { string retstr = String.Empty; // opening brace retstr += GenerateIndentedLine("{"); m_braceCount++; if (m_insertCoopTerminationChecks) { // We have to check in event functions as well because the user can manually call these. if (previousSymbol is GlobalFunctionDefinition || previousSymbol is WhileStatement || previousSymbol is DoWhileStatement || previousSymbol is ForLoop || previousSymbol is StateEvent) retstr += GenerateIndentedLine(m_coopTerminationCheck); } foreach (SYMBOL kid in cs.kids) retstr += GenerateNode(cs, kid); // closing brace m_braceCount--; retstr += GenerateIndentedLine("}"); return retstr; } /// <summary> /// Generates the code for a Constant node. /// </summary> /// <param name="c">The Constant node.</param> /// <returns>String containing C# code for Constant c.</returns> private string GenerateConstant(Constant c) { string retstr = String.Empty; // Supprt LSL's weird acceptance of floats with no trailing digits // after the period. Turn float x = 10.; into float x = 10.0; if ("LSL_Types.LSLFloat" == c.Type) { int dotIndex = c.Value.IndexOf('.') + 1; if (0 < dotIndex && (dotIndex == c.Value.Length || !Char.IsDigit(c.Value[dotIndex]))) c.Value = c.Value.Insert(dotIndex, "0"); c.Value = "new LSL_Types.LSLFloat(" + c.Value + ")"; } else if ("LSL_Types.LSLInteger" == c.Type) { c.Value = "new LSL_Types.LSLInteger(" + c.Value + ")"; } else if ("LSL_Types.LSLString" == c.Type) { c.Value = "new LSL_Types.LSLString(\"" + c.Value + "\")"; } retstr += Generate(c.Value, c); return retstr; } /// <summary> /// Generates the code for a Declaration node. /// </summary> /// <param name="d">The Declaration node.</param> /// <returns>String containing C# code for Declaration d.</returns> private string GenerateDeclaration(Declaration d) { return Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d); } /// <summary> /// Generates the code for a DoWhileStatement node. /// </summary> /// <param name="dws">The DoWhileStatement node.</param> /// <returns>String containing C# code for DoWhileStatement dws.</returns> private string GenerateDoWhileStatement(DoWhileStatement dws) { string retstr = String.Empty; retstr += GenerateIndentedLine("do", dws); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = dws.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(dws, (SYMBOL)dws.kids.Pop()); if (indentHere) m_braceCount--; retstr += GenerateIndented("while (", dws); retstr += GenerateNode(dws, (SYMBOL)dws.kids.Pop()); retstr += GenerateLine(");"); return retstr; } /// <summary> /// Generates the code for a ForLoop node. /// </summary> /// <param name="fl">The ForLoop node.</param> /// <returns>String containing C# code for ForLoop fl.</returns> private string GenerateForLoop(ForLoop fl) { string retstr = String.Empty; retstr += GenerateIndented("for (", fl); // It's possible that we don't have an assignment, in which case // the child will be null and we only print the semicolon. // for (x = 0; x < 10; x++) // ^^^^^ ForLoopStatement s = (ForLoopStatement)fl.kids.Pop(); if (null != s) { retstr += GenerateForLoopStatement(s); } retstr += Generate("; "); // for (x = 0; x < 10; x++) // ^^^^^^ retstr += GenerateNode(fl, (SYMBOL)fl.kids.Pop()); retstr += Generate("; "); // for (x = 0; x < 10; x++) // ^^^ retstr += GenerateForLoopStatement((ForLoopStatement)fl.kids.Pop()); retstr += GenerateLine(")"); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = fl.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(fl, (SYMBOL)fl.kids.Pop()); if (indentHere) m_braceCount--; return retstr; } /// <summary> /// Generates the code for a ForLoopStatement node. /// </summary> /// <param name="fls">The ForLoopStatement node.</param> /// <returns>String containing C# code for ForLoopStatement fls.</returns> private string GenerateForLoopStatement(ForLoopStatement fls) { string retstr = String.Empty; int comma = fls.kids.Count - 1; // tells us whether to print a comma // It's possible that all we have is an empty Ident, for example: // // for (x; x < 10; x++) { ... } // // Which is illegal in C# (MONO). We'll skip it. if (fls.kids.Top is IdentExpression && 1 == fls.kids.Count) return retstr; for (int i = 0; i < fls.kids.Count; i++) { SYMBOL s = (SYMBOL)fls.kids[i]; // Statements surrounded by parentheses in for loops // // e.g. for ((i = 0), (j = 7); (i < 10); (++i)) // // are legal in LSL but not in C# so we need to discard the parentheses // // The following, however, does not appear to be legal in LLS // // for ((i = 0, j = 7); (i < 10); (++i)) // // As of Friday 20th November 2009, the Linden Lab simulators appear simply never to compile or run this // script but with no debug or warnings at all! Therefore, we won't deal with this yet (which looks // like it would be considerably more complicated to handle). while (s is ParenthesisExpression) s = (SYMBOL)s.kids.Pop(); retstr += GenerateNode(fls, s); if (0 < comma--) retstr += Generate(", "); } return retstr; } /// <summary> /// Generates the code for a FunctionCall node. /// </summary> /// <param name="fc">The FunctionCall node.</param> /// <returns>String containing C# code for FunctionCall fc.</returns> private string GenerateFunctionCall(FunctionCall fc) { string retstr = String.Empty; string modinvoke = null; if (m_comms != null) modinvoke = m_comms.LookupModInvocation(fc.Id); if (modinvoke != null) { if (fc.kids[0] is ArgumentList) { if ((fc.kids[0] as ArgumentList).kids.Count == 0) retstr += Generate(String.Format("{0}(\"{1}\"", modinvoke, fc.Id), fc); else retstr += Generate(String.Format("{0}(\"{1}\",", modinvoke, fc.Id), fc); } } else { retstr += Generate(String.Format("{0}(", CheckName(fc.Id)), fc); } foreach (SYMBOL kid in fc.kids) retstr += GenerateNode(fc, kid); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a GlobalFunctionDefinition node. /// </summary> /// <param name="gf">The GlobalFunctionDefinition node.</param> /// <returns>String containing C# code for GlobalFunctionDefinition gf.</returns> private string GenerateGlobalFunctionDefinition(GlobalFunctionDefinition gf) { string retstr = String.Empty; // we need to separate the argument declaration list from other kids List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>(); List<SYMBOL> remainingKids = new List<SYMBOL>(); foreach (SYMBOL kid in gf.kids) if (kid is ArgumentDeclarationList) argumentDeclarationListKids.Add(kid); else remainingKids.Add(kid); retstr += GenerateIndented(String.Format("{0} {1}(", gf.ReturnType, CheckName(gf.Name)), gf); // print the state arguments, if any foreach (SYMBOL kid in argumentDeclarationListKids) retstr += GenerateArgumentDeclarationList((ArgumentDeclarationList)kid); retstr += GenerateLine(")"); foreach (SYMBOL kid in remainingKids) retstr += GenerateNode(gf, kid); return retstr; } /// <summary> /// Generates the code for a GlobalVariableDeclaration node. /// </summary> /// <param name="gv">The GlobalVariableDeclaration node.</param> /// <returns>String containing C# code for GlobalVariableDeclaration gv.</returns> private string GenerateGlobalVariableDeclaration(GlobalVariableDeclaration gv) { string retstr = String.Empty; foreach (SYMBOL s in gv.kids) { retstr += Indent(); retstr += GenerateNode(gv, s); retstr += GenerateLine(";"); } return retstr; } /// <summary> /// Generates the code for an identifier /// </summary> /// <param name="id">The symbol name</param> /// <param name="s">The Symbol node.</param> /// <returns>String containing C# code for identifier reference.</returns> private string GenerateIdentifier(string id, SYMBOL s) { if (m_comms != null) { object value = m_comms.LookupModConstant(id); if (value != null) { string retval = null; if (value is int) retval = String.Format("new LSL_Types.LSLInteger({0})", ((int)value).ToString()); else if (value is float) retval = String.Format("new LSL_Types.LSLFloat({0})", ((float)value).ToString()); else if (value is string) retval = String.Format("new LSL_Types.LSLString(\"{0}\")", ((string)value)); else if (value is OpenMetaverse.UUID) retval = String.Format("new LSL_Types.key(\"{0}\")", ((OpenMetaverse.UUID)value).ToString()); else if (value is OpenMetaverse.Vector3) retval = String.Format("new LSL_Types.Vector3(\"{0}\")", ((OpenMetaverse.Vector3)value).ToString()); else if (value is OpenMetaverse.Quaternion) retval = String.Format("new LSL_Types.Quaternion(\"{0}\")", ((OpenMetaverse.Quaternion)value).ToString()); else retval = id; return Generate(retval, s); } } return Generate(CheckName(id), s); } /// <summary> /// Generates the code for an IfStatement node. /// </summary> /// <param name="ifs">The IfStatement node.</param> /// <returns>String containing C# code for IfStatement ifs.</returns> private string GenerateIfStatement(IfStatement ifs) { string retstr = String.Empty; retstr += GenerateIndented("if (", ifs); retstr += GenerateNode(ifs, (SYMBOL)ifs.kids.Pop()); retstr += GenerateLine(")"); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = ifs.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(ifs, (SYMBOL)ifs.kids.Pop()); if (indentHere) m_braceCount--; if (0 < ifs.kids.Count) // do it again for an else { retstr += GenerateIndentedLine("else", ifs); indentHere = ifs.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(ifs, (SYMBOL)ifs.kids.Pop()); if (indentHere) m_braceCount--; } return retstr; } /// <summary> /// Generates the code for a IncrementDecrementExpression node. /// </summary> /// <param name="ide">The IncrementDecrementExpression node.</param> /// <returns>String containing C# code for IncrementDecrementExpression ide.</returns> private string GenerateIncrementDecrementExpression(IncrementDecrementExpression ide) { string retstr = String.Empty; if (0 < ide.kids.Count) { IdentDotExpression dot = (IdentDotExpression)ide.kids.Top; retstr += Generate(String.Format("{0}", ide.PostOperation ? CheckName(dot.Name) + "." + dot.Member + ide.Operation : ide.Operation + CheckName(dot.Name) + "." + dot.Member), ide); } else retstr += Generate(String.Format("{0}", ide.PostOperation ? CheckName(ide.Name) + ide.Operation : ide.Operation + CheckName(ide.Name)), ide); return retstr; } /// <summary> /// Prints text correctly indented. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>Properly indented string s.</returns> private string GenerateIndented(string s, SYMBOL sym) { string retstr = Indent() + s; if (null != sym) m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position)); m_CSharpCol += s.Length; return retstr; } /// <summary> /// Prints text correctly indented, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>Properly indented string s followed by newline.</returns> private string GenerateIndentedLine(string s) { return GenerateIndentedLine(s, null); } /// <summary> /// Prints text correctly indented, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>Properly indented string s followed by newline.</returns> private string GenerateIndentedLine(string s, SYMBOL sym) { string retstr = GenerateIndented(s, sym) + "\n"; m_CSharpLine++; m_CSharpCol = 1; return retstr; } /// <summary> /// Generates the code for a JumpLabel node. /// </summary> /// <param name="jl">The JumpLabel node.</param> /// <returns>String containing C# code for JumpLabel jl.</returns> private string GenerateJumpLabel(JumpLabel jl) { string labelStatement; if (m_insertCoopTerminationChecks) labelStatement = m_coopTerminationCheck + "\n"; else labelStatement = "NoOp();\n"; return Generate(String.Format("{0}: ", CheckName(jl.LabelName)), jl) + labelStatement; } /// <summary> /// Generates the code for a JumpStatement node. /// </summary> /// <param name="js">The JumpStatement node.</param> /// <returns>String containing C# code for JumpStatement js.</returns> private string GenerateJumpStatement(JumpStatement js) { return Generate(String.Format("goto {0}", CheckName(js.TargetName)), js); } /// <summary> /// Prints a newline. /// </summary> /// <returns>A newline.</returns> private string GenerateLine() { return GenerateLine(""); } /// <summary> /// Prints text, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>String s followed by newline.</returns> private string GenerateLine(string s) { return GenerateLine(s, null); } /// <summary> /// Prints text, followed by a newline. /// </summary> /// <param name="s">String of text to print.</param> /// <param name="sym">Symbol being generated to extract original line /// number and column from.</param> /// <returns>String s followed by newline.</returns> private string GenerateLine(string s, SYMBOL sym) { string retstr = Generate(s, sym) + "\n"; m_CSharpLine++; m_CSharpCol = 1; return retstr; } /// <summary> /// Generates the code for a ListConstant node. /// </summary> /// <param name="lc">The ListConstant node.</param> /// <returns>String containing C# code for ListConstant lc.</returns> private string GenerateListConstant(ListConstant lc) { string retstr = String.Empty; retstr += Generate(String.Format("new {0}(", lc.Type), lc); foreach (SYMBOL kid in lc.kids) retstr += GenerateNode(lc, kid); retstr += Generate(")"); return retstr; } /// <summary> /// Recursively called to generate each type of node. Will generate this /// node, then all it's children. /// </summary> /// <param name="previousSymbol">The parent node.</param> /// <param name="s">The current node to generate code for.</param> /// <returns>String containing C# code for SYMBOL s.</returns> private string GenerateNode(SYMBOL previousSymbol, SYMBOL s) { string retstr = String.Empty; // make sure to put type lower in the inheritance hierarchy first // ie: since IdentArgument and ExpressionArgument inherit from // Argument, put IdentArgument and ExpressionArgument before Argument if (s is GlobalFunctionDefinition) retstr += GenerateGlobalFunctionDefinition((GlobalFunctionDefinition)s); else if (s is GlobalVariableDeclaration) retstr += GenerateGlobalVariableDeclaration((GlobalVariableDeclaration)s); else if (s is State) retstr += GenerateState((State)s); else if (s is CompoundStatement) retstr += GenerateCompoundStatement(previousSymbol, (CompoundStatement)s); else if (s is Declaration) retstr += GenerateDeclaration((Declaration)s); else if (s is Statement) retstr += GenerateStatement(previousSymbol, (Statement)s); else if (s is ReturnStatement) retstr += GenerateReturnStatement((ReturnStatement)s); else if (s is JumpLabel) retstr += GenerateJumpLabel((JumpLabel)s); else if (s is JumpStatement) retstr += GenerateJumpStatement((JumpStatement)s); else if (s is StateChange) retstr += GenerateStateChange((StateChange)s); else if (s is IfStatement) retstr += GenerateIfStatement((IfStatement)s); else if (s is WhileStatement) retstr += GenerateWhileStatement((WhileStatement)s); else if (s is DoWhileStatement) retstr += GenerateDoWhileStatement((DoWhileStatement)s); else if (s is ForLoop) retstr += GenerateForLoop((ForLoop)s); else if (s is ArgumentList) retstr += GenerateArgumentList((ArgumentList)s); else if (s is Assignment) retstr += GenerateAssignment((Assignment)s); else if (s is BinaryExpression) retstr += GenerateBinaryExpression((BinaryExpression)s); else if (s is ParenthesisExpression) retstr += GenerateParenthesisExpression((ParenthesisExpression)s); else if (s is UnaryExpression) retstr += GenerateUnaryExpression((UnaryExpression)s); else if (s is IncrementDecrementExpression) retstr += GenerateIncrementDecrementExpression((IncrementDecrementExpression)s); else if (s is TypecastExpression) retstr += GenerateTypecastExpression((TypecastExpression)s); else if (s is FunctionCall) retstr += GenerateFunctionCall((FunctionCall)s); else if (s is VectorConstant) retstr += GenerateVectorConstant((VectorConstant)s); else if (s is RotationConstant) retstr += GenerateRotationConstant((RotationConstant)s); else if (s is ListConstant) retstr += GenerateListConstant((ListConstant)s); else if (s is Constant) retstr += GenerateConstant((Constant)s); else if (s is IdentDotExpression) retstr += Generate(CheckName(((IdentDotExpression)s).Name) + "." + ((IdentDotExpression)s).Member, s); else if (s is IdentExpression) retstr += GenerateIdentifier(((IdentExpression)s).Name, s); else if (s is IDENT) retstr += Generate(CheckName(((TOKEN)s).yytext), s); else { foreach (SYMBOL kid in s.kids) retstr += GenerateNode(s, kid); } return retstr; } /// <summary> /// Generates the code for a ParenthesisExpression node. /// </summary> /// <param name="pe">The ParenthesisExpression node.</param> /// <returns>String containing C# code for ParenthesisExpression pe.</returns> private string GenerateParenthesisExpression(ParenthesisExpression pe) { string retstr = String.Empty; retstr += Generate("("); foreach (SYMBOL kid in pe.kids) retstr += GenerateNode(pe, kid); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a ReturnStatement node. /// </summary> /// <param name="rs">The ReturnStatement node.</param> /// <returns>String containing C# code for ReturnStatement rs.</returns> private string GenerateReturnStatement(ReturnStatement rs) { string retstr = String.Empty; retstr += Generate("return ", rs); foreach (SYMBOL kid in rs.kids) retstr += GenerateNode(rs, kid); return retstr; } /// <summary> /// Generates the code for a RotationConstant node. /// </summary> /// <param name="rc">The RotationConstant node.</param> /// <returns>String containing C# code for RotationConstant rc.</returns> private string GenerateRotationConstant(RotationConstant rc) { string retstr = String.Empty; retstr += Generate(String.Format("new {0}(", rc.Type), rc); retstr += GenerateNode(rc, (SYMBOL)rc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(rc, (SYMBOL)rc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(rc, (SYMBOL)rc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(rc, (SYMBOL)rc.kids.Pop()); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a State node. /// </summary> /// <param name="s">The State node.</param> /// <returns>String containing C# code for State s.</returns> private string GenerateState(State s) { string retstr = String.Empty; foreach (SYMBOL kid in s.kids) if (kid is StateEvent) retstr += GenerateStateEvent((StateEvent)kid, s.Name); return retstr; } /// <summary> /// Generates the code for a StateChange node. /// </summary> /// <param name="sc">The StateChange node.</param> /// <returns>String containing C# code for StateChange sc.</returns> private string GenerateStateChange(StateChange sc) { return Generate(String.Format("state(\"{0}\")", sc.NewState), sc); } /// <summary> /// Generates the code for a StateEvent node. /// </summary> /// <param name="se">The StateEvent node.</param> /// <param name="parentStateName">The name of the parent state.</param> /// <returns>String containing C# code for StateEvent se.</returns> private string GenerateStateEvent(StateEvent se, string parentStateName) { string retstr = String.Empty; // we need to separate the argument declaration list from other kids List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>(); List<SYMBOL> remainingKids = new List<SYMBOL>(); foreach (SYMBOL kid in se.kids) if (kid is ArgumentDeclarationList) argumentDeclarationListKids.Add(kid); else remainingKids.Add(kid); // "state" (function) declaration retstr += GenerateIndented(String.Format("public void {0}_event_{1}(", parentStateName, se.Name), se); // print the state arguments, if any foreach (SYMBOL kid in argumentDeclarationListKids) retstr += GenerateArgumentDeclarationList((ArgumentDeclarationList)kid); retstr += GenerateLine(")"); foreach (SYMBOL kid in remainingKids) retstr += GenerateNode(se, kid); return retstr; } /// <summary> /// Generates the code for a Statement node. /// </summary> /// <param name="s">The Statement node.</param> /// <returns>String containing C# code for Statement s.</returns> private string GenerateStatement(SYMBOL previousSymbol, Statement s) { string retstr = String.Empty; bool printSemicolon = true; bool transformToBlock = false; if (m_insertCoopTerminationChecks) { // A non-braced single line do while structure cannot contain multiple statements. // So to insert the termination check we change this to a braced control structure instead. if (previousSymbol is WhileStatement || previousSymbol is DoWhileStatement || previousSymbol is ForLoop) { transformToBlock = true; // FIXME: This will be wrongly indented because the previous for/while/dowhile will have already indented. retstr += GenerateIndentedLine("{"); retstr += GenerateIndentedLine(m_coopTerminationCheck); } } retstr += Indent(); if (0 < s.kids.Count) { // Jump label prints its own colon, we don't need a semicolon. printSemicolon = !(s.kids.Top is JumpLabel); // If we encounter a lone Ident, we skip it, since that's a C# // (MONO) error. if (!(s.kids.Top is IdentExpression && 1 == s.kids.Count)) foreach (SYMBOL kid in s.kids) retstr += GenerateNode(s, kid); } if (printSemicolon) retstr += GenerateLine(";"); if (transformToBlock) { // FIXME: This will be wrongly indented because the for/while/dowhile is currently handling the unindent retstr += GenerateIndentedLine("}"); } return retstr; } /// <summary> /// Generates the code for a TypecastExpression node. /// </summary> /// <param name="te">The TypecastExpression node.</param> /// <returns>String containing C# code for TypecastExpression te.</returns> private string GenerateTypecastExpression(TypecastExpression te) { string retstr = String.Empty; // we wrap all typecasted statements in parentheses retstr += Generate(String.Format("({0}) (", te.TypecastType), te); retstr += GenerateNode(te, (SYMBOL)te.kids.Pop()); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a UnaryExpression node. /// </summary> /// <param name="ue">The UnaryExpression node.</param> /// <returns>String containing C# code for UnaryExpression ue.</returns> private string GenerateUnaryExpression(UnaryExpression ue) { string retstr = String.Empty; retstr += Generate(ue.UnarySymbol, ue); retstr += GenerateNode(ue, (SYMBOL)ue.kids.Pop()); return retstr; } /// <summary> /// Generates the code for a VectorConstant node. /// </summary> /// <param name="vc">The VectorConstant node.</param> /// <returns>String containing C# code for VectorConstant vc.</returns> private string GenerateVectorConstant(VectorConstant vc) { string retstr = String.Empty; retstr += Generate(String.Format("new {0}(", vc.Type), vc); retstr += GenerateNode(vc, (SYMBOL)vc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(vc, (SYMBOL)vc.kids.Pop()); retstr += Generate(", "); retstr += GenerateNode(vc, (SYMBOL)vc.kids.Pop()); retstr += Generate(")"); return retstr; } /// <summary> /// Generates the code for a WhileStatement node. /// </summary> /// <param name="ws">The WhileStatement node.</param> /// <returns>String containing C# code for WhileStatement ws.</returns> private string GenerateWhileStatement(WhileStatement ws) { string retstr = String.Empty; retstr += GenerateIndented("while (", ws); retstr += GenerateNode(ws, (SYMBOL)ws.kids.Pop()); retstr += GenerateLine(")"); // CompoundStatement handles indentation itself but we need to do it // otherwise. bool indentHere = ws.kids.Top is Statement; if (indentHere) m_braceCount++; retstr += GenerateNode(ws, (SYMBOL)ws.kids.Pop()); if (indentHere) m_braceCount--; return retstr; } /// <summary> /// Prints text correctly indented. /// </summary> /// <param name="s">String of text to print.</param> /// <returns>Properly indented string s.</returns> //private string GenerateIndented(string s) //{ // return GenerateIndented(s, null); //} // THIS FUNCTION IS COMMENTED OUT TO SUPPRESS WARNINGS /// <summary> /// Prints correct indentation. /// </summary> /// <returns>Indentation based on brace count.</returns> private string Indent() { string retstr = String.Empty; for (int i = 0; i < m_braceCount; i++) for (int j = 0; j < m_indentWidth; j++) { retstr += " "; m_CSharpCol++; } return retstr; } /// <summary> /// Resets various counters and metadata. /// </summary> private void ResetCounters() { m_braceCount = 0; m_CSharpLine = 0; m_CSharpCol = 1; m_positionMap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>(); m_astRoot = null; } } }
/* * 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.Text; using OpenSim.Region.Framework.Scenes; using OpenMetaverse; using System.Drawing; using log4net; using System.Reflection; using OpenSim.Framework.Serialization; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// The regions included in an OAR file. /// </summary> public class DearchiveScenesInfo { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// One region in the archive. /// </summary> public class RegionInfo { /// <summary> /// The subdirectory in which the region is stored. /// </summary> public string Directory { get; set; } /// <summary> /// The region's coordinates (relative to the South-West corner of the block). /// </summary> public Point Location { get; set; } /// <summary> /// The UUID of the original scene from which this archived region was saved. /// </summary> public string OriginalID { get; set; } /// <summary> /// The scene in the current simulator into which this region is loaded. /// If null then the region doesn't have a corresponding scene, and it won't be loaded. /// </summary> public Scene Scene { get; set; } /// <summary> /// The size of the region being loaded. /// </summary> public Vector3 RegionSize { get; set; } public RegionInfo() { RegionSize = new Vector3(256f,256f,float.MaxValue); } } /// <summary> /// Whether this archive uses the multi-region format. /// </summary> public Boolean MultiRegionFormat { get; set; } /// <summary> /// Maps (Region directory -> region) /// </summary> protected Dictionary<string, RegionInfo> m_directory2region = new Dictionary<string, RegionInfo>(); /// <summary> /// Maps (UUID of the scene in the simulator where the region will be loaded -> region) /// </summary> protected Dictionary<UUID, RegionInfo> m_newId2region = new Dictionary<UUID, RegionInfo>(); public int LoadedCreationDateTime { get; set; } public string DefaultOriginalID { get; set; } // These variables are used while reading the archive control file protected int? m_curY = null; protected int? m_curX = null; protected RegionInfo m_curRegion; public DearchiveScenesInfo() { MultiRegionFormat = false; } // The following methods are used while reading the archive control file public void StartRow() { m_curY = (m_curY == null) ? 0 : m_curY + 1; m_curX = null; } public void StartRegion() { m_curX = (m_curX == null) ? 0 : m_curX + 1; // Note: this doesn't mean we have a real region in this location; this could just be a "hole" } public void SetRegionOriginalID(string id) { m_curRegion = new RegionInfo(); int x = (int)((m_curX == null) ? 0 : m_curX); int y = (int)((m_curY == null) ? 0 : m_curY); m_curRegion.Location = new Point(x, y); m_curRegion.OriginalID = id; // 'curRegion' will be saved in 'm_directory2region' when SetRegionDir() is called } public void SetRegionDirectory(string directory) { if(m_curRegion != null) { m_curRegion.Directory = directory; m_directory2region[directory] = m_curRegion; } } public void SetRegionSize(Vector3 size) { if(m_curRegion != null) m_curRegion.RegionSize = size; } /// <summary> /// Sets all the scenes present in the simulator. /// </summary> /// <remarks> /// This method matches regions in the archive to scenes in the simulator according to /// their relative position. We only load regions if there's an existing Scene in the /// grid location where the region should be loaded. /// </remarks> /// <param name="rootScene">The scene where the Load OAR operation was run</param> /// <param name="simulatorScenes">All the scenes in the simulator</param> public void SetSimulatorScenes(Scene rootScene, ArchiveScenesGroup simulatorScenes) { foreach (RegionInfo archivedRegion in m_directory2region.Values) { Point location = new Point((int)rootScene.RegionInfo.RegionLocX, (int)rootScene.RegionInfo.RegionLocY); location.Offset(archivedRegion.Location); Scene scene; if (simulatorScenes.TryGetScene(location, out scene)) { archivedRegion.Scene = scene; m_newId2region[scene.RegionInfo.RegionID] = archivedRegion; } else { m_log.WarnFormat("[ARCHIVER]: Not loading archived region {0} because there's no existing region at location {1},{2}", archivedRegion.Directory, location.X, location.Y); } } } /// <summary> /// Returns the archived region according to the path of a file in the archive. /// Also, converts the full path into a path that is relative to the region's directory. /// </summary> /// <param name="fullPath">The path of a file in the archive</param> /// <param name="scene">The corresponding Scene, or null if none</param> /// <param name="relativePath">The path relative to the region's directory. (Or the original /// path, if this file doesn't belong to a region.)</param> /// <returns>True: use this file; False: skip it</returns> public bool GetRegionFromPath(string fullPath, out Scene scene, out string relativePath) { scene = null; relativePath = fullPath; if (!MultiRegionFormat) { if (m_newId2region.Count > 0) scene = m_newId2region.First().Value.Scene; return true; } if (!fullPath.StartsWith(ArchiveConstants.REGIONS_PATH)) return true; // this file doesn't belong to a region string[] parts = fullPath.Split(new Char[] { '/' }, 3); if (parts.Length != 3) return false; string regionDirectory = parts[1]; relativePath = parts[2]; RegionInfo region; if (m_directory2region.TryGetValue(regionDirectory, out region)) { scene = region.Scene; return (scene != null); } else { return false; } } /// <summary> /// Returns the original UUID of a region (from the simulator where the OAR was saved), /// given the UUID of the scene it was loaded into in the current simulator. /// </summary> /// <param name="newID"></param> /// <returns></returns> public string GetOriginalRegionID(UUID newID) { RegionInfo region; if (m_newId2region.TryGetValue(newID, out region)) return region.OriginalID; else return DefaultOriginalID; } /// <summary> /// Returns the scenes that have been (or will be) loaded. /// </summary> /// <returns></returns> public List<UUID> GetLoadedScenes() { return m_newId2region.Keys.ToList(); } public int GetScenesCount() { return m_directory2region.Count; } } }
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using OrchardCore.Environment.Shell; using OrchardCore.ResourceManagement; using OrchardCore.Settings; namespace OrchardCore.Resources { public class ResourceManagementOptionsConfiguration : IConfigureOptions<ResourceManagementOptions> { private readonly ISiteService _siteService; private readonly IHostEnvironment _env; private readonly IHttpContextAccessor _httpContextAccessor; private readonly string _tenantPrefix; private const string cloudflareUrl = "https://cdnjs.cloudflare.com/ajax/libs/"; // Versions private const string codeMirrorVersion = "5.65.0"; private const string monacoEditorVersion = "0.31.1"; // URLs private const string codeMirrorUrl = cloudflareUrl + "codemirror/" + codeMirrorVersion + "/"; public ResourceManagementOptionsConfiguration(ISiteService siteService, IHostEnvironment env, IHttpContextAccessor httpContextAccessor, ShellSettings shellSettings) { _siteService = siteService; _env = env; _httpContextAccessor = httpContextAccessor; _tenantPrefix = string.IsNullOrEmpty(shellSettings.RequestUrlPrefix) ? string.Empty : "/" + shellSettings.RequestUrlPrefix; } ResourceManifest BuildManifest() { var manifest = new ResourceManifest(); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.min.js", "~/OrchardCore.Resources/Scripts/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.6.0.min.js", "https://code.jquery.com/jquery-3.6.0.js") .SetCdnIntegrity("sha384-vtXRMe3mGCbOeY7l30aIg8H9p3GdeSe4IFlP6G8JMa7o7lXvnz3GFKzPxzJdPfGK", "sha384-S58meLBGKxIiQmJ/pJ8ilvFUcGcqgla+mWH9EEKGm6i6rKxSTA2kpXJQJ8n7XK4w") .SetVersion("3.6.0"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.slim.min.js", "~/OrchardCore.Resources/Scripts/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.6.0.slim.min.js", "https://code.jquery.com/jquery-3.6.0.slim.js") .SetCdnIntegrity("sha384-Qg00WFl9r0Xr6rUqNLv1ffTSSKEFFCDCKVyHZ+sVt8KuvG99nWw5RNvbhuKgif9z", "sha384-fuUlMletgG/KCb0NwIZTW6aMv/YBbXe0Wt71nwLRreZZpesG/N/aURjEZCG6mtYn") .SetVersion("3.6.0"); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.5.1.min.js", "https://code.jquery.com/jquery-3.5.1.js") .SetCdnIntegrity("sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2", "sha384-/LjQZzcpTzaYn7qWqRIWYC5l8FWEZ2bIHIz0D73Uzba4pShEcdLdZyZkI4Kv676E") .SetVersion("3.5.1"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.slim.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.5.1.slim.min.js", "https://code.jquery.com/jquery-3.5.1.slim.js") .SetCdnIntegrity("sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj", "sha384-x6NENSfxadikq2gB4e6/qompriNc+y1J3eqWg3hAAMNBs4dFU303XMTcU3uExJgZ") .SetVersion("3.5.1"); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.4.1.min.js", "https://code.jquery.com/jquery-3.4.1.js") .SetCdnIntegrity("sha384-vk5WoKIaW/vJyUAd9n/wmopsmNhiy+L2Z+SBxGYnUkunIxVxAv/UtMOhba/xskxh", "sha384-mlceH9HlqLp7GMKHrj5Ara1+LvdTZVMx4S1U43/NxCvAkzIo8WJ0FE7duLel3wVo") .SetVersion("3.4.1"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.slim.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.4.1.slim.min.js", "https://code.jquery.com/jquery-3.4.1.slim.js") .SetCdnIntegrity("sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n", "sha384-teRaFq/YbXOM/9FZ1qTavgUgTagWUPsk6xapwcjkrkBHoWvKdZZuAeV8hhaykl+G") .SetVersion("3.4.1"); manifest .DefineScript("jQuery.easing") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.easing.min.js", "~/OrchardCore.Resources/Scripts/jquery.easing.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/jquery.easing.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/jquery.easing.js") .SetCdnIntegrity("sha384-leGYpHE9Tc4N9OwRd98xg6YFpB9shlc/RkilpFi0ljr3QD4tFoFptZvgnnzzwG4Q", "sha384-fwPA0FyfPOiDsglgAC4ZWmBGwpXSZNkq9IG+cM9HL4CkpNQo4xgCDkOIPdWypLMX") .SetVersion("1.4.1"); manifest .DefineScript("jQuery-ui") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui.js") .SetCdn("https://code.jquery.com/ui/1.12.1/jquery-ui.min.js", "https://code.jquery.com/ui/1.12.1/jquery-ui.js") .SetCdnIntegrity("sha384-Dziy8F2VlJQLMShA6FHWNul/veM9bCkRUaLqr199K94ntO5QUrLJBEbYegdSkkqX", "sha384-JPbtLYL10d/Z1crlc6GGGGM3PavCzzoUJ1UxH0bXHOfguWHQ6XAWrIzW+MBGGXe5") .SetVersion("1.12.1"); manifest .DefineStyle("jQuery-ui") .SetUrl("~/OrchardCore.Resources/Styles/jquery-ui.min.css", "~/OrchardCore.Resources/Styles/jquery-ui.css") .SetCdn("https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.min.css", "https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css") .SetCdnIntegrity("sha384-kcAOn9fN4XSd+TGsNu2OQKSuV5ngOwt7tg73O4EpaD91QXvrfgvf0MR7/2dUjoI6", "sha384-xewr6kSkq3dBbEtB6Z/3oFZmknWn7nHqhLVLrYgzEFRbU/DHSxW7K3B44yWUN60D") .SetVersion("1.12.1"); manifest .DefineScript("jQuery-ui-i18n") .SetDependencies("jQuery-ui") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui-i18n.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui-i18n.js") .SetCdn("https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js", "https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js") .SetCdnIntegrity("sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd", "sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd") .SetVersion("1.7.2"); manifest .DefineScript("bootstrap") .SetDependencies("jQuery") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.js") .SetCdnIntegrity("sha384-vhJnz1OVIdLktyixHY4Uk3OHEwdQqPppqYR8+5mjsauETgLOcEynD9oPHhhz18Nw", "sha384-it0Suwx+VjMafDIVf5t+ozEbrflmNjEddSX5LstI/Xdw3nv4qP/a4e8K4k5hH6l4") .SetVersion("3.4.0"); manifest .DefineStyle("bootstrap") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.css") .SetCdnIntegrity("sha384-PmY9l28YgO4JwMKbTvgaS7XNZJ30MK9FAZjjzXtlqyZCqBY6X6bXIkM++IkyinN+", "sha384-/5bQ8UYbZnrNY3Mfy6zo9QLgIQD/0CximLKk733r8/pQnXn2mgvhvKhcy43gZtJV") .SetVersion("3.4.0"); manifest .DefineStyle("bootstrap-theme") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.css") .SetCdnIntegrity("sha384-jzngWsPS6op3fgRCDTESqrEJwRKck+CILhJVO5VvaAZCq8JYf8HsR/HPpBOOPZfR", "sha384-RtiWe5OsslAYZ9AVyorBziI2VQL7E27rzWygBJh7wrZuVPyK5jeQLLytnJIpJqfD") .SetVersion("3.4.0"); manifest .DefineScript("popper") .SetUrl("~/OrchardCore.Resources/Vendor/popper-1.16.1/popper.min.js", "~/OrchardCore.Resources/Vendor/popper-1.16.1/popper.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.js") .SetCdnIntegrity("sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN", "sha384-cpSm/ilDFOWiMuF2bj03ZzJinb48NO9IGCXcYDtUzdP5y64Ober65chnoOj1XFoA") .SetVersion("1.16.1"); manifest .DefineScript("bootstrap") .SetDependencies("jQuery", "popper") .SetUrl("~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.min.js", "~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.js") .SetCdnIntegrity("sha256-SyTu6CwrfOhaznYZPoolVw2rxoY7lKYKQvqbtqN93HI=", "sha256-6+FBBJrY8QbYNs6AeCP3JSnzmmTX/+YFtN4iSOtYSKY=") .SetVersion("4.6.1"); manifest .DefineScript("bootstrap-bundle") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.bundle.min.js", "~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.bundle.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.js") .SetCdnIntegrity("sha256-fgLAgv7fyCGopR/gBNq2iW3ZKIdqIcyshnUULC4vex8=", "sha256-eKb5bRTtGi7f8XfWkjxVGyJWtw9gS1X+9yqhNHklfWI=") .SetVersion("4.6.1"); manifest .DefineStyle("bootstrap") .SetUrl("~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.min.css", "~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.css") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css", "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.css") .SetCdnIntegrity("sha256-DF7Zhf293AJxJNTmh5zhoYYIMs2oXitRfBjY+9L//AY=", "sha256-YQxBfLfP0/QyffXZNTDFES5IFXrxv+hYE9b2NK5TGcw=") .SetVersion("4.6.1"); manifest .DefineScript("popperjs") .SetUrl("~/OrchardCore.Resources/Scripts/popper.min.js", "~/OrchardCore.Resources/Scripts/popper.js") .SetCdn("https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js", "https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.js") .SetCdnIntegrity("sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB", "sha384-7bLhHCLchQRw474eiNFHP0txk38fyqbVOG/RohbcYXnTrdd9mNPQrVkOcY14iscj") .SetVersion("2.10.2"); manifest .DefineScript("bootstrap") .SetDependencies("popperjs") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.js") .SetCdnIntegrity("sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13", "sha384-4S2sRpwEfE5rUaiRVP4sETrP8WMo4pOHkAoMmvuju/2ycHM/QW1J7YQOjrPNpd5h") .SetVersion("5.1.3"); manifest .DefineScript("bootstrap-bundle") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.bundle.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.bundle.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.js") .SetCdnIntegrity("sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p", "sha384-8fq7CZc5BnER+jVlJI2Jafpbn4A9320TKhNJfYP33nneHep7sUg/OD30x7fK09pS") .SetVersion("5.1.3"); manifest .DefineStyle("bootstrap") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap.min.css", "~/OrchardCore.Resources/Styles/bootstrap.css") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css", "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.css") .SetCdnIntegrity("sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3", "sha384-BNKxVsQUv1K6rV5WJumgbzW1t/UsyFWm/uP4I8rr9T3PeBkcRGGApJv+rOjBpEdF") .SetVersion("5.1.3"); manifest .DefineStyle("bootstrap-select") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap-select.min.css", "~/OrchardCore.Resources/Styles/bootstrap-select.css") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-select.min.css", "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-select.css") .SetCdnIntegrity("sha384-dTqTc7d5t+FKhTIaMmda32pZNoXY/Y0ui0hRl5GzDQp4aARfEzbP1jzX6+KRuGKg", "sha384-OlTrhEtwZzUzVXapTUO8s6QryXzpD8mFyNVA8kyAi8KMgfOKSJYvielvExM+dNPR") .SetVersion("1.13.18"); manifest .DefineScript("bootstrap-select") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap-select.min.js", "~/OrchardCore.Resources/Scripts/bootstrap-select.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.js") .SetCdnIntegrity("sha384-x8fxIWvLdZnkRaCvkDXOlxd6UP+qga975FjnbRp6NRpL9jjXjY9TwF9y7z4AccxS", "sha384-6BZTOUHC4e3nWcy5gveLqAu52vwy5TX8zBIvvfZFVDzIjYDgprdXRMK/hsypxdpQ") .SetVersion("1.13.18"); manifest .DefineStyle("bootstrap-slider") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap-slider.min.css", "~/OrchardCore.Resources/Styles/bootstrap-slider.css") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/css/bootstrap-slider.min.css", "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/css/bootstrap-slider.css") .SetCdnIntegrity("sha384-Ot7O5p8Ws9qngwQOA1DP7acHuGIfK63cYbVJRYzrrMXhT3syEYhEsg+uqPsPpRhZ", "sha384-x1BbAB1QrM4/ZjT+vJzuI/NdvRo4tINKqg7lTN9jCq0bWrr/nelp9KfroZWd3UJu") .SetVersion("11.0.2"); manifest .DefineScript("bootstrap-slider") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap-slider.min.js", "~/OrchardCore.Resources/Scripts/bootstrap-slider.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/bootstrap-slider.min.js", "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/bootstrap-slider.js") .SetCdnIntegrity("sha384-lZLZ1uMNIkCnScGXQrJ+PzUR2utC/FgaxJLMMrQD3Fbra1AwGXvshEIedqCmqXTM", "sha384-3kfvdN8W/a8p/9S6Gy69uVsacwuNxyvFVJXxZa/Qe00tkNfZw63n/4snM1u646YU") .SetVersion("11.0.2"); manifest .DefineStyle("codemirror") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/codemirror.min.css", "~/OrchardCore.Resources/Styles/codemirror/codemirror.css") .SetCdn(codeMirrorUrl + "codemirror.min.css", codeMirrorUrl + "codemirror.css") .SetCdnIntegrity("sha384-KoxwpPPg4NMA10DxiUgtUyRWwpky7/582Ua4fbpJj6bNHAOqOiqSJfRZ+GLArzSR", "sha384-CQoQE99ffnItQimoAYyaWSR3jOs54zfOQ/PUaS7dycVqenh7FJWKca5xa260ehrV") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/codemirror.min.js", "~/OrchardCore.Resources/Scripts/codemirror/codemirror.js") .SetCdn(codeMirrorUrl + "codemirror.min.js", codeMirrorUrl + "codemirror.js") .SetCdnIntegrity("sha384-PUGzdyI4n4aIOAbYGObxFYnmOpapiEx7SgYJ3ShL9REjK3MiEZHxhXNDCARRDoSu", "sha384-wIqlyiDCjoeMxHMs808s9W1r5ylkiI6fQiLs56TXm8GhWCO8TRzHzen8tbpdF6X8") .SetVersion(codeMirrorVersion); manifest .DefineStyle("codemirror-addon-display-fullscreen") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/addon/display/fullscreen.min.css", "~/OrchardCore.Resources/Styles/codemirror/addon/display/fullscreen.css") .SetCdn(codeMirrorUrl + "addon/display/fullscreen.min.css", codeMirrorUrl + "addon/display/fullscreen.css") .SetCdnIntegrity("sha384-uuIczW2AGKADJpvg6YiNBJQWE7duDkgQDkndYEsbUGaLm8SPJZzlly6hcEo0aTlW", "sha384-+glu1jsbG+T5ocmkeMvIYh5w07IXKxmJZaCdkNbVfpEr3xi+M0gopFSR/oLKXxio") .SetVersion(codeMirrorVersion); manifest .DefineStyle("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/addon/hint/show-hint.min.css", "~/OrchardCore.Resources/Styles/codemirror/addon/hint/show-hint.css") .SetCdn(codeMirrorUrl + "addon/hint/show-hint.min.css", codeMirrorUrl + "addon/hint/show-hint.css") .SetCdnIntegrity("sha384-qqTWkykzuDLx4yDYa7bVrwNwBHuqVvklDUMVaU4eezgNUEgGbP8Zv6i3u8OmtuWg", "sha384-ZZbLvEvLoXKrHo3Tkh7W8amMgoHFkDzWe8IAm1ZgxsG5y35H+fJCVMWwr0YBAEGA") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-selection-active-line") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.js") .SetCdn(codeMirrorUrl + "addon/selection/active-line.min.js", codeMirrorUrl + "addon/selection/active-line.js") .SetCdnIntegrity("sha384-G0dW669yzC7wSAJf0Tqu4PyeHKXY0vAX9xZtaTPnK/+EHjtucblXS/5GHR55j1mx", "sha384-kKz13r+qZMgTNgXROGNHQ0/0/J1FtvIvRZ9yjOHo1YLUCd+KF8r9R+su/B+f6C0U") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-display-autorefresh") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.js") .SetCdn(codeMirrorUrl + "addon/display/autorefresh.min.js", codeMirrorUrl + "addon/display/autorefresh.js") .SetCdnIntegrity("sha384-pn83o6MtS8kicn/sV6AhRaBqXQ5tau8NzA2ovcobkcc1uRFP7D8CMhRx231QwKST", "sha384-5wrQkkCzj5dJInF+DDDYjE1itTGaIxO+TL6gMZ2eZBo9OyWLczkjolFX8kixX/9X") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-display-fullscreen") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.js") .SetCdn(codeMirrorUrl + "addon/display/fullscreen.min.js", codeMirrorUrl + "addon/display/fullscreen.js") .SetCdnIntegrity("sha384-3dGKkIriAGFyl5yMW9W6ogQCxVZgAR4oBBNPex1FNAl70+iLE0LpRwJCFCKkKl4l", "sha384-kuwHYEheDAp0NlPye2VXyxJ6J54CeVky9tH+e0mn6/gP4PJ50MF4FGKkrGAxIyCW") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-edit-closetag") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/edit/closetag.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.js") .SetCdn(codeMirrorUrl + "addon/edit/closetag.min.js", codeMirrorUrl + "addon/edit/closetag.js") .SetCdnIntegrity("sha384-MWjKXjBsdRdF/BS6d0C/gumTxJxeqVUfriOb0LJTP2/NmkFYz8nSY/AJZppi+fRQ", "sha384-jR3Qxv7tHnv4TLLymC5s7Tl3aQGWNayqUHHBNxnnA/NjIyewLGSmNPQuDcMxnPKY") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/hint/show-hint.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/hint/show-hint.js") .SetCdn(codeMirrorUrl + "addon/hint/show-hint.min.js", codeMirrorUrl + "addon/hint/show-hint.js") .SetCdnIntegrity("sha384-pFJF3GAZ6kaXHIeHTe2ecWeeBzFVuVF2QXccnazviREKim+uL3lm/voyytwY71bQ", "sha384-RzmY798hMmzDwNL4d5ZkSaygnsA6Rq2ROY7awxW1t9NV+8XPpnXivbcD+EI1r2Ij") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-hint-sql-hint") .SetDependencies("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/hint/sql-hint.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/hint/sql-hint.js") .SetCdn(codeMirrorUrl + "addon/hint/sql-hint.min.js", codeMirrorUrl + "addon/hint/sql-hint.js") .SetCdnIntegrity("sha384-s+MbgbBZ249zyKdf4x7EwFAXXLbK0yk3eVVd+GpWeSsd4SjKiC/H1GxT/gMZB9Lx", "sha384-CnIooEvOzoAsliTWO+BYwoTVFeqhBCympzDuwlhTlP7TWeAHB2h4Q0OeOqVkL5dP") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-mode-multiplex") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.js") .SetCdn(codeMirrorUrl + "addon/mode/multiplex.min.js", codeMirrorUrl + "addon/mode/multiplex.js") .SetCdnIntegrity("sha384-/JERLTKv3TwdPmZug8zm4X4NktLA8QsyjIybae/5aO9MeLkyzyP4NN3wpabXsbdq", "sha384-kZLDZbOp+G4qzGg8vy4P5DlIIPPnoSdO6G1puag9t/QjRDDfeANKKNIhMA+Yq+J1") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-mode-simple") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.js") .SetCdn(codeMirrorUrl + "addon/mode/simple.min.js", codeMirrorUrl + "addon/mode/simple.js") .SetCdnIntegrity("sha384-EnymP1wIjc1AsZM6f29pxT0z5VkDoUJ22Jx34tiDzvRvy7OiqviBVtw/evVWEaT5", "sha384-Foc3817k/CG8PVkPQtWgpBPcO0w2Noaep609FulvP/EwVUhv4JqNakD8UAORWA/s") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-css") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.js") .SetCdn(codeMirrorUrl + "mode/css/css.min.js", codeMirrorUrl + "mode/css/css.js") .SetCdnIntegrity("sha384-IkA5dwHN+lGrX/ZxO+sktNF+wGXL06QJAVUag0yEBb7QDNM59YKsI5qWYc7SKPtN", "sha384-bZYw0+OmoeFivaUT4/YNXLYKX7+hahkNA64LcETceaOhHFqbNqetu6c0vIhMPqXy") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-htmlmixed") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.js") .SetCdn(codeMirrorUrl + "mode/htmlmixed/htmlmixed.min.js", codeMirrorUrl + "mode/htmlmixed/htmlmixed.js") .SetCdnIntegrity("sha384-C4oV1iL5nO+MmIRm+JoD2sZ03wIafv758LRO92kyg7AFvpvn8oQAra4g3mrw5+53", "sha384-vM5dpc39AxwLWe2WC/4ZNAw81WDwmu5CoPw9uw7XfDMLtUKrHFEsz4ofeaRWVIEP") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-javascript") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.js") .SetCdn(codeMirrorUrl + "mode/javascript/javascript.min.js", codeMirrorUrl + "mode/javascript/javascript.js") .SetCdnIntegrity("sha384-vuxa41RhbUbqWstjjDqkCzQ5jZ9NybJWK0M1ntCoO8V5YVOPUjJ0Xz65kxAIkAnO", "sha384-//Bn5ksI7NmNsgwMl5TEImM0XBhLe/SAhg/OlWtAvE7anPJo3bDKN1adMUKG3qpg") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-sql") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.js") .SetCdn(codeMirrorUrl + "mode/sql/sql.min.js", codeMirrorUrl + "mode/sql/sql.js") .SetCdnIntegrity("sha384-LnNQf6kxsWRUR1gIJto9AsloUow3HzeE1WLOBNFh2snAy3cTlGK8VFVw7v5TvFfN", "sha384-x+5PPG+/GfZmN/pSGwtvsFLaYMv8FnmX+xpWs1BTM3RNGrISCEMF9gatNn4tSuhl") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-xml") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.js") .SetCdn(codeMirrorUrl + "mode/xml/xml.min.js", codeMirrorUrl + "mode/xml/xml.js") .SetCdnIntegrity("sha384-c3NXS9t3umqhEaScj8N4yz8EafssGBhJLbwjhLgON3PHr5AUoeKQWrdngj9sxoDJ", "sha384-fnrvkyvE4Ut04qDu6kFoulvy6uuBXr8YoD8rk13BCDTODAyMB5HTeBHKV+oq86Cl") .SetVersion(codeMirrorVersion); manifest .DefineStyle("font-awesome") .SetUrl("~/OrchardCore.Resources/Styles/font-awesome.min.css", "~/OrchardCore.Resources/Styles/font-awesome.css") .SetCdn("https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css") .SetCdnIntegrity("sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN", "sha384-FckWOBo7yuyMS7In0aXZ0aoVvnInlnFMwCv77x9sZpFgOonQgnBj1uLwenWVtsEj") .SetVersion("4.7.0"); manifest .DefineStyle("font-awesome") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.min.css", "~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.css") .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/css/all.min.css", "https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/css/all.css") .SetCdnIntegrity("sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm", "sha384-7rgjkhkxJ95zOzIjk97UrBOe14KgYpH9+zQm5BdgzjQELBU6kHf4WwoQzHfTx5sw") .SetVersion("5.15.4"); manifest .DefineScript("font-awesome") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.js") .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/js/all.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/js/all.js") .SetCdnIntegrity("sha384-rOA1PnstxnOBLzCLMcre8ybwbTmemjzdNlILg8O7z1lUkLXozs4DHonlDtnE7fpc", "sha384-HfU7cInvKb8zxQuLKtKr/suuRgcSH1OYsdJU+8lGA/t8nyNgdJF09UIkRzg1iefj") .SetVersion("5.15.4"); manifest .DefineScript("font-awesome-v4-shims") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.js") .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/js/v4-shims.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/js/v4-shims.js") .SetCdnIntegrity("sha384-bx00wqJq+zY9QLCMa/zViZPu1f0GJ3VXwF4GSw3GbfjwO28QCFr4qadCrNmJQ/9N", "sha384-SGuqaGE4bcW7Xl5T06BsUPUA91qaNtT53uGOcGpavQMje3goIFJbDsC0VAwtgL5g") .SetVersion("5.15.4"); manifest .DefineScript("jquery-resizable") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-resizable.min.js", "~/OrchardCore.Resources/Scripts/jquery-resizable.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery-resizable.min.js") .SetCdnIntegrity("sha384-1LMjDEezsSgzlRgsyFIAvLW7FWSdFIHqBGjUa+ad5EqtK1FORC8XpTJ/pahxj5GB", "sha384-0yk9X0IG0cXxuN9yTTkps/3TNNI9ZcaKKhh8dgqOEAWGXxIYS5xaY2as6b32Ov3P") .SetVersion("0.35.0"); manifest .DefineStyle("trumbowyg") .SetUrl("~/OrchardCore.Resources/Styles/trumbowyg.min.css", "~/OrchardCore.Resources/Styles/trumbowyg.css") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/ui/trumbowyg.min.css", "https://cdn.jsdelivr.net/npm/[email protected]/dist/ui/trumbowyg.css") .SetCdnIntegrity("sha384-kTb2zOBw/Vng2V8SH/LF2llnbNnFpSMVTOrSN0W8Z0zzE8LMM+w/vFqhD9b+esLV", "sha384-qaIYw5IcvXvWBzXq2NPvCMucQerh0hReNg45Qas5X71KWzZmGuPp+VTW5zywbg0x") .SetVersion("2.25.1"); manifest .DefineScript("trumbowyg") .SetDependencies("jquery-resizable") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg.min.js", "~/OrchardCore.Resources/Scripts/trumbowyg.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/trumbowyg.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/trumbowyg.js") .SetCdnIntegrity("sha384-wwt6vSsdmnPNAuXp11Jjm37wAA+b/Rm33Jhd3QE/5E4oDLeNoCTLU3kxQYsdOtdW", "sha384-N2uP/HqSD9qptuEGY2J1Iq0G5jqaYUcuMGUnyWiS6giy4adYptw2Co8hT7LQJKcT") .SetVersion("2.25.1"); manifest .DefineScript("trumbowyg-shortcodes") .SetDependencies("trumbowyg") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg.shortcodes.min.js", "~/OrchardCore.Resources/Scripts/trumbowyg.shortcodes.js") .SetVersion("1.0.0"); manifest .DefineStyle("trumbowyg-plugins") .SetDependencies("trumbowyg") .SetUrl("~/OrchardCore.Resources/Styles/trumbowyg-plugins.min.css", "~/OrchardCore.Resources/Styles/trumbowyg-plugins.css") .SetVersion("2.25.1"); manifest .DefineScript("trumbowyg-plugins") .SetDependencies("trumbowyg") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg-plugins.min.js", "~/OrchardCore.Resources/Scripts/trumbowyg-plugins.js") .SetVersion("2.25.1"); manifest .DefineScript("vuejs") .SetUrl("~/OrchardCore.Resources/Scripts/vue.min.js", "~/OrchardCore.Resources/Scripts/vue.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js") .SetCdnIntegrity("sha384-ULpZhk1pvhc/UK5ktA9kwb2guy9ovNSTyxPNHANnA35YjBQgdwI+AhLkixDvdlw4", "sha384-t1tHLsbM7bYMJCXlhr0//00jSs7ZhsAhxgm191xFsyzvieTMCbUWKMhFg9I6ci8q") .SetVersion("2.6.14"); manifest .DefineScript("vue-multiselect") .SetDependencies("vuejs") .SetUrl("~/OrchardCore.Resources/Scripts/vue-multiselect.min.js", "~/OrchardCore.Resources/Scripts/vue-multiselect.min.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-multiselect.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-multiselect.min.js") .SetCdnIntegrity("sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU", "sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU") .SetVersion("2.1.6"); manifest .DefineStyle("vue-multiselect") .SetUrl("~/OrchardCore.Resources/Styles/vue-multiselect.min.css", "~/OrchardCore.Resources/Styles/vue-multiselect.min.css") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-multiselect.min.css", "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-multiselect.min.css") .SetCdnIntegrity("sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM", "sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM") .SetVersion("2.1.6"); manifest .DefineScript("Sortable") .SetUrl("~/OrchardCore.Resources/Scripts/Sortable.min.js", "~/OrchardCore.Resources/Scripts/Sortable.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/Sortable.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/Sortable.js") .SetCdnIntegrity("sha384-vxc713BCZYoMxC6DlBK6K4M+gLAS8+63q7TtgB2+KZVn8GNafLKZCJ7Wk2S6ZEl1", "sha384-6dbyp5R22OLsNh2CMeCLIc+s0ZPLpCtBG2f38vvi5ghQIfUvVHIzKpz2S3qLx83I") .SetVersion("1.14.0"); manifest .DefineScript("vuedraggable") .SetDependencies("vuejs", "Sortable") .SetUrl("~/OrchardCore.Resources/Scripts/vuedraggable.umd.min.js", "~/OrchardCore.Resources/Scripts/vuedraggable.umd.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/vuedraggable.umd.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/vuedraggable.umd.js") .SetCdnIntegrity("sha384-qUA1xXJiX23E4GOeW/XHtsBkV9MUcHLSjhi3FzO08mv8+W8bv5AQ1cwqLskycOTs", "sha384-+jB9vXc/EaIJTlNiZG2tv+TUpKm6GR9HCRZb3VkI3lscZWqrCYDbX2ZXffNJldL9") .SetVersion("2.24.3"); manifest .DefineScript("js-cookie") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/js.cookie.min.js", "~/OrchardCore.Resources/Scripts/js.cookie.js") .SetCdn("https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js", "https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.js") .SetCdnIntegrity("sha384-ETDm/j6COkRSUfVFsGNM5WYE4WjyRgfDhy4Pf4Fsc8eNw/eYEMqYZWuxTzMX6FBa", "sha384-wAGdUDEOVO9JhMpvNh7mkYd0rL2EM0bLb1+VY5R+jDfVBxYFJNfzkinHfbRfxT2s") .SetVersion("3.0.1"); manifest .DefineScript("monaco-loader") .SetUrl("~/OrchardCore.Resources/Scripts/monaco/vs/loader.js") .SetPosition(ResourcePosition.Last) .SetVersion(monacoEditorVersion); manifest .DefineScript("monaco") .SetAttribute("data-tenant-prefix", _tenantPrefix) .SetUrl("~/OrchardCore.Resources/Scripts/monaco/ocmonaco.js") .SetDependencies("monaco-loader") .SetVersion(monacoEditorVersion); return manifest; } public void Configure(ResourceManagementOptions options) { options.ResourceManifests.Add(BuildManifest()); var settings = _siteService.GetSiteSettingsAsync().GetAwaiter().GetResult(); switch (settings.ResourceDebugMode) { case ResourceDebugMode.Enabled: options.DebugMode = true; break; case ResourceDebugMode.Disabled: options.DebugMode = false; break; case ResourceDebugMode.FromConfiguration: options.DebugMode = !_env.IsProduction(); break; } options.UseCdn = settings.UseCdn; options.CdnBaseUrl = settings.CdnBaseUrl; options.AppendVersion = settings.AppendVersion; options.ContentBasePath = _httpContextAccessor.HttpContext.Request.PathBase.Value; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using SinglePageAppAndWebApi.Areas.HelpPage.ModelDescriptions; using SinglePageAppAndWebApi.Areas.HelpPage.Models; namespace SinglePageAppAndWebApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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.Diagnostics; using System.IO; using System.Text; using System.Xml.Schema; using System.Xml.XPath; using System.Security; using System.Globalization; using System.Runtime.Versioning; namespace System.Xml { // Represents an entire document. An XmlDocument contains XML data. public class XmlDocument : XmlNode { private XmlImplementation _implementation; private DomNameTable _domNameTable; // hash table of XmlName private XmlLinkedNode _lastChild; private XmlNamedNodeMap _entities; private Hashtable _htElementIdMap; private Hashtable _htElementIDAttrDecl; //key: id; object: the ArrayList of the elements that have the same id (connected or disconnected) private SchemaInfo _schemaInfo; private XmlSchemaSet _schemas; // schemas associated with the cache private bool _reportValidity; //This variable represents the actual loading status. Since, IsLoading will //be manipulated sometimes for adding content to EntityReference this variable //has been added which would always represent the loading status of document. private bool _actualLoadingStatus; private XmlNodeChangedEventHandler _onNodeInsertingDelegate; private XmlNodeChangedEventHandler _onNodeInsertedDelegate; private XmlNodeChangedEventHandler _onNodeRemovingDelegate; private XmlNodeChangedEventHandler _onNodeRemovedDelegate; private XmlNodeChangedEventHandler _onNodeChangingDelegate; private XmlNodeChangedEventHandler _onNodeChangedDelegate; // false if there are no ent-ref present, true if ent-ref nodes are or were present (i.e. if all ent-ref were removed, the doc will not clear this flag) internal bool fEntRefNodesPresent; internal bool fCDataNodesPresent; private bool _preserveWhitespace; private bool _isLoading; // special name strings for internal string strDocumentName; internal string strDocumentFragmentName; internal string strCommentName; internal string strTextName; internal string strCDataSectionName; internal string strEntityName; internal string strID; internal string strXmlns; internal string strXml; internal string strSpace; internal string strLang; internal string strEmpty; internal string strNonSignificantWhitespaceName; internal string strSignificantWhitespaceName; internal string strReservedXmlns; internal string strReservedXml; internal String baseURI; private XmlResolver _resolver; internal bool bSetResolver; internal object objLock; private XmlAttribute _namespaceXml; internal static EmptyEnumerator EmptyEnumerator = new EmptyEnumerator(); internal static IXmlSchemaInfo NotKnownSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.NotKnown); internal static IXmlSchemaInfo ValidSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.Valid); internal static IXmlSchemaInfo InvalidSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.Invalid); // Initializes a new instance of the XmlDocument class. public XmlDocument() : this(new XmlImplementation()) { } // Initializes a new instance // of the XmlDocument class with the specified XmlNameTable. public XmlDocument(XmlNameTable nt) : this(new XmlImplementation(nt)) { } protected internal XmlDocument(XmlImplementation imp) : base() { _implementation = imp; _domNameTable = new DomNameTable(this); // force the following string instances to be default in the nametable XmlNameTable nt = this.NameTable; nt.Add(string.Empty); strDocumentName = nt.Add("#document"); strDocumentFragmentName = nt.Add("#document-fragment"); strCommentName = nt.Add("#comment"); strTextName = nt.Add("#text"); strCDataSectionName = nt.Add("#cdata-section"); strEntityName = nt.Add("#entity"); strID = nt.Add("id"); strNonSignificantWhitespaceName = nt.Add("#whitespace"); strSignificantWhitespaceName = nt.Add("#significant-whitespace"); strXmlns = nt.Add("xmlns"); strXml = nt.Add("xml"); strSpace = nt.Add("space"); strLang = nt.Add("lang"); strReservedXmlns = nt.Add(XmlReservedNs.NsXmlNs); strReservedXml = nt.Add(XmlReservedNs.NsXml); strEmpty = nt.Add(String.Empty); baseURI = String.Empty; objLock = new object(); } internal SchemaInfo DtdSchemaInfo { get { return _schemaInfo; } set { _schemaInfo = value; } } // NOTE: This does not correctly check start name char, but we cannot change it since it would be a breaking change. internal static void CheckName(String name) { int endPos = ValidateNames.ParseNmtoken(name, 0); if (endPos < name.Length) { throw new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos)); } } internal XmlName AddXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo) { XmlName n = _domNameTable.AddName(prefix, localName, namespaceURI, schemaInfo); Debug.Assert((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix)); Debug.Assert(n.LocalName == localName); Debug.Assert((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI)); return n; } internal XmlName GetXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo) { XmlName n = _domNameTable.GetName(prefix, localName, namespaceURI, schemaInfo); Debug.Assert(n == null || ((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix))); Debug.Assert(n == null || n.LocalName == localName); Debug.Assert(n == null || ((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI))); return n; } internal XmlName AddAttrXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo) { XmlName xmlName = AddXmlName(prefix, localName, namespaceURI, schemaInfo); Debug.Assert((prefix == null) ? (xmlName.Prefix.Length == 0) : (prefix == xmlName.Prefix)); Debug.Assert(xmlName.LocalName == localName); Debug.Assert((namespaceURI == null) ? (xmlName.NamespaceURI.Length == 0) : (xmlName.NamespaceURI == namespaceURI)); if (!this.IsLoading) { // Use atomized versions instead of prefix, localName and nsURI object oPrefix = xmlName.Prefix; object oNamespaceURI = xmlName.NamespaceURI; object oLocalName = xmlName.LocalName; if ((oPrefix == (object)strXmlns || (oPrefix == (object)strEmpty && oLocalName == (object)strXmlns)) ^ (oNamespaceURI == (object)strReservedXmlns)) throw new ArgumentException(SR.Format(SR.Xdom_Attr_Reserved_XmlNS, namespaceURI)); } return xmlName; } internal bool AddIdInfo(XmlName eleName, XmlName attrName) { //when XmlLoader call XmlDocument.AddInfo, the element.XmlName and attr.XmlName //have already been replaced with the ones that don't have namespace values (or just //string.Empty) because in DTD, the namespace is not supported if (_htElementIDAttrDecl == null || _htElementIDAttrDecl[eleName] == null) { if (_htElementIDAttrDecl == null) _htElementIDAttrDecl = new Hashtable(); _htElementIDAttrDecl.Add(eleName, attrName); return true; } return false; } private XmlName GetIDInfoByElement_(XmlName eleName) { //When XmlDocument is getting the IDAttribute for a given element, //we need only compare the prefix and localname of element.XmlName with //the registered htElementIDAttrDecl. XmlName newName = GetXmlName(eleName.Prefix, eleName.LocalName, string.Empty, null); if (newName != null) { return (XmlName)(_htElementIDAttrDecl[newName]); } return null; } internal XmlName GetIDInfoByElement(XmlName eleName) { if (_htElementIDAttrDecl == null) return null; else return GetIDInfoByElement_(eleName); } private WeakReference GetElement(ArrayList elementList, XmlElement elem) { ArrayList gcElemRefs = new ArrayList(); foreach (WeakReference elemRef in elementList) { if (!elemRef.IsAlive) //take notes on the garbage collected nodes gcElemRefs.Add(elemRef); else { if ((XmlElement)(elemRef.Target) == elem) return elemRef; } } //Clear out the gced elements foreach (WeakReference elemRef in gcElemRefs) elementList.Remove(elemRef); return null; } internal void AddElementWithId(string id, XmlElement elem) { if (_htElementIdMap == null || !_htElementIdMap.Contains(id)) { if (_htElementIdMap == null) _htElementIdMap = new Hashtable(); ArrayList elementList = new ArrayList(); elementList.Add(new WeakReference(elem)); _htElementIdMap.Add(id, elementList); } else { // there are other element(s) that has the same id ArrayList elementList = (ArrayList)(_htElementIdMap[id]); if (GetElement(elementList, elem) == null) elementList.Add(new WeakReference(elem)); } } internal void RemoveElementWithId(string id, XmlElement elem) { if (_htElementIdMap != null && _htElementIdMap.Contains(id)) { ArrayList elementList = (ArrayList)(_htElementIdMap[id]); WeakReference elemRef = GetElement(elementList, elem); if (elemRef != null) { elementList.Remove(elemRef); if (elementList.Count == 0) _htElementIdMap.Remove(id); } } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { XmlDocument clone = Implementation.CreateDocument(); clone.SetBaseURI(this.baseURI); if (deep) clone.ImportChildren(this, clone, deep); return clone; } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.Document; } } public override XmlNode ParentNode { get { return null; } } // Gets the node for the DOCTYPE declaration. public virtual XmlDocumentType DocumentType { get { return (XmlDocumentType)FindChild(XmlNodeType.DocumentType); } } internal virtual XmlDeclaration Declaration { get { if (HasChildNodes) { XmlDeclaration dec = FirstChild as XmlDeclaration; return dec; } return null; } } // Gets the XmlImplementation object for this document. public XmlImplementation Implementation { get { return _implementation; } } // Gets the name of the node. public override String Name { get { return strDocumentName; } } // Gets the name of the current node without the namespace prefix. public override String LocalName { get { return strDocumentName; } } // Gets the root XmlElement for the document. public XmlElement DocumentElement { get { return (XmlElement)FindChild(XmlNodeType.Element); } } internal override bool IsContainer { get { return true; } } internal override XmlLinkedNode LastNode { get { return _lastChild; } set { _lastChild = value; } } // Gets the XmlDocument that contains this node. public override XmlDocument OwnerDocument { get { return null; } } public XmlSchemaSet Schemas { get { if (_schemas == null) { _schemas = new XmlSchemaSet(NameTable); } return _schemas; } set { _schemas = value; } } internal bool CanReportValidity { get { return _reportValidity; } } internal bool HasSetResolver { get { return bSetResolver; } } internal XmlResolver GetResolver() { return _resolver; } public virtual XmlResolver XmlResolver { set { _resolver = value; if (!bSetResolver) bSetResolver = true; XmlDocumentType dtd = this.DocumentType; if (dtd != null) { dtd.DtdSchemaInfo = null; } } } internal override bool IsValidChildType(XmlNodeType type) { switch (type) { case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return true; case XmlNodeType.DocumentType: if (DocumentType != null) throw new InvalidOperationException(SR.Xdom_DualDocumentTypeNode); return true; case XmlNodeType.Element: if (DocumentElement != null) throw new InvalidOperationException(SR.Xdom_DualDocumentElementNode); return true; case XmlNodeType.XmlDeclaration: if (Declaration != null) throw new InvalidOperationException(SR.Xdom_DualDeclarationNode); return true; default: return false; } } // the function examines all the siblings before the refNode // if any of the nodes has type equals to "nt", return true; otherwise, return false; private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode refNode) { if (refNode == null) return false; XmlNode node = null; if (refNode.ParentNode != null) node = refNode.ParentNode.FirstChild; while (node != null) { if (node.NodeType == nt) return true; if (node == refNode) break; node = node.NextSibling; } return false; } // the function examines all the siblings after the refNode // if any of the nodes has the type equals to "nt", return true; otherwise, return false; private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode refNode) { XmlNode node = refNode; while (node != null) { if (node.NodeType == nt) return true; node = node.NextSibling; } return false; } internal override bool CanInsertBefore(XmlNode newChild, XmlNode refChild) { if (refChild == null) refChild = FirstChild; if (refChild == null) return true; switch (newChild.NodeType) { case XmlNodeType.XmlDeclaration: return (refChild == FirstChild); case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: return refChild.NodeType != XmlNodeType.XmlDeclaration; case XmlNodeType.DocumentType: { if (refChild.NodeType != XmlNodeType.XmlDeclaration) { //if refChild is not the XmlDeclaration node, only need to go through the sibling before and including refChild to // make sure no Element ( rootElem node ) before the current position return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild.PreviousSibling); } } break; case XmlNodeType.Element: { if (refChild.NodeType != XmlNodeType.XmlDeclaration) { //if refChild is not the XmlDeclaration node, only need to go through the siblings after and including the refChild to // make sure no DocType node and XmlDeclaration node after the current position. return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild); } } break; } return false; } internal override bool CanInsertAfter(XmlNode newChild, XmlNode refChild) { if (refChild == null) refChild = LastChild; if (refChild == null) return true; switch (newChild.NodeType) { case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return true; case XmlNodeType.DocumentType: { //we will have to go through all the siblings before the refChild just to make sure no Element node ( rootElem ) // before the current position return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild); } case XmlNodeType.Element: { return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild.NextSibling); } } return false; } // Creates an XmlAttribute with the specified name. public XmlAttribute CreateAttribute(String name) { String prefix = String.Empty; String localName = String.Empty; String namespaceURI = String.Empty; SplitName(name, out prefix, out localName); SetDefaultNamespace(prefix, localName, ref namespaceURI); return CreateAttribute(prefix, localName, namespaceURI); } internal void SetDefaultNamespace(String prefix, String localName, ref String namespaceURI) { if (prefix == strXmlns || (prefix.Length == 0 && localName == strXmlns)) { namespaceURI = strReservedXmlns; } else if (prefix == strXml) { namespaceURI = strReservedXml; } } // Creates a XmlCDataSection containing the specified data. public virtual XmlCDataSection CreateCDataSection(String data) { fCDataNodesPresent = true; return new XmlCDataSection(data, this); } // Creates an XmlComment containing the specified data. public virtual XmlComment CreateComment(String data) { return new XmlComment(data, this); } // Returns a new XmlDocumentType object. public virtual XmlDocumentType CreateDocumentType(string name, string publicId, string systemId, string internalSubset) { return new XmlDocumentType(name, publicId, systemId, internalSubset, this); } // Creates an XmlDocumentFragment. public virtual XmlDocumentFragment CreateDocumentFragment() { return new XmlDocumentFragment(this); } // Creates an element with the specified name. public XmlElement CreateElement(String name) { string prefix = String.Empty; string localName = String.Empty; SplitName(name, out prefix, out localName); return CreateElement(prefix, localName, string.Empty); } internal void AddDefaultAttributes(XmlElement elem) { SchemaInfo schInfo = DtdSchemaInfo; SchemaElementDecl ed = GetSchemaElementDecl(elem); if (ed != null && ed.AttDefs != null) { IDictionaryEnumerator attrDefs = ed.AttDefs.GetEnumerator(); while (attrDefs.MoveNext()) { SchemaAttDef attdef = (SchemaAttDef)attrDefs.Value; if (attdef.Presence == SchemaDeclBase.Use.Default || attdef.Presence == SchemaDeclBase.Use.Fixed) { //build a default attribute and return string attrPrefix = string.Empty; string attrLocalname = attdef.Name.Name; string attrNamespaceURI = string.Empty; if (schInfo.SchemaType == SchemaType.DTD) attrPrefix = attdef.Name.Namespace; else { attrPrefix = attdef.Prefix; attrNamespaceURI = attdef.Name.Namespace; } XmlAttribute defattr = PrepareDefaultAttribute(attdef, attrPrefix, attrLocalname, attrNamespaceURI); elem.SetAttributeNode(defattr); } } } } private SchemaElementDecl GetSchemaElementDecl(XmlElement elem) { SchemaInfo schInfo = DtdSchemaInfo; if (schInfo != null) { //build XmlQualifiedName used to identify the element schema declaration XmlQualifiedName qname = new XmlQualifiedName(elem.LocalName, schInfo.SchemaType == SchemaType.DTD ? elem.Prefix : elem.NamespaceURI); //get the schema info for the element SchemaElementDecl elemDecl; if (schInfo.ElementDecls.TryGetValue(qname, out elemDecl)) { return elemDecl; } } return null; } //Will be used by AddDeafulatAttributes() and GetDefaultAttribute() methods private XmlAttribute PrepareDefaultAttribute(SchemaAttDef attdef, string attrPrefix, string attrLocalname, string attrNamespaceURI) { SetDefaultNamespace(attrPrefix, attrLocalname, ref attrNamespaceURI); XmlAttribute defattr = CreateDefaultAttribute(attrPrefix, attrLocalname, attrNamespaceURI); //parsing the default value for the default attribute defattr.InnerXml = attdef.DefaultValueRaw; //during the expansion of the tree, the flag could be set to true, we need to set it back. XmlUnspecifiedAttribute unspAttr = defattr as XmlUnspecifiedAttribute; if (unspAttr != null) { unspAttr.SetSpecified(false); } return defattr; } // Creates an XmlEntityReference with the specified name. public virtual XmlEntityReference CreateEntityReference(String name) { return new XmlEntityReference(name, this); } // Creates a XmlProcessingInstruction with the specified name // and data strings. public virtual XmlProcessingInstruction CreateProcessingInstruction(String target, String data) { return new XmlProcessingInstruction(target, data, this); } // Creates a XmlDeclaration node with the specified values. public virtual XmlDeclaration CreateXmlDeclaration(String version, string encoding, string standalone) { return new XmlDeclaration(version, encoding, standalone, this); } // Creates an XmlText with the specified text. public virtual XmlText CreateTextNode(String text) { return new XmlText(text, this); } // Creates a XmlSignificantWhitespace node. public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string text) { return new XmlSignificantWhitespace(text, this); } public override XPathNavigator CreateNavigator() { return CreateNavigator(this); } protected internal virtual XPathNavigator CreateNavigator(XmlNode node) { XmlNodeType nodeType = node.NodeType; XmlNode parent; XmlNodeType parentType; switch (nodeType) { case XmlNodeType.EntityReference: case XmlNodeType.Entity: case XmlNodeType.DocumentType: case XmlNodeType.Notation: case XmlNodeType.XmlDeclaration: return null; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: parent = node.ParentNode; if (parent != null) { do { parentType = parent.NodeType; if (parentType == XmlNodeType.Attribute) { return null; } else if (parentType == XmlNodeType.EntityReference) { parent = parent.ParentNode; } else { break; } } while (parent != null); } node = NormalizeText(node); break; case XmlNodeType.Whitespace: parent = node.ParentNode; if (parent != null) { do { parentType = parent.NodeType; if (parentType == XmlNodeType.Document || parentType == XmlNodeType.Attribute) { return null; } else if (parentType == XmlNodeType.EntityReference) { parent = parent.ParentNode; } else { break; } } while (parent != null); } node = NormalizeText(node); break; default: break; } return new DocumentXPathNavigator(this, node); } internal static bool IsTextNode(XmlNodeType nt) { switch (nt) { case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return true; default: return false; } } private XmlNode NormalizeText(XmlNode n) { XmlNode retnode = null; while (IsTextNode(n.NodeType)) { retnode = n; n = n.PreviousSibling; if (n == null) { XmlNode intnode = retnode; while (true) { if (intnode.ParentNode != null && intnode.ParentNode.NodeType == XmlNodeType.EntityReference) { if (intnode.ParentNode.PreviousSibling != null) { n = intnode.ParentNode.PreviousSibling; break; } else { intnode = intnode.ParentNode; if (intnode == null) break; } } else break; } } if (n == null) break; while (n.NodeType == XmlNodeType.EntityReference) { n = n.LastChild; } } return retnode; } // Creates a XmlWhitespace node. public virtual XmlWhitespace CreateWhitespace(string text) { return new XmlWhitespace(text, this); } // Returns an XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(String name) { return new XmlElementList(this, name); } // DOM Level 2 // Creates an XmlAttribute with the specified LocalName // and NamespaceURI. public XmlAttribute CreateAttribute(String qualifiedName, String namespaceURI) { string prefix = String.Empty; string localName = String.Empty; SplitName(qualifiedName, out prefix, out localName); return CreateAttribute(prefix, localName, namespaceURI); } // Creates an XmlElement with the specified LocalName and // NamespaceURI. public XmlElement CreateElement(String qualifiedName, String namespaceURI) { string prefix = String.Empty; string localName = String.Empty; SplitName(qualifiedName, out prefix, out localName); return CreateElement(prefix, localName, namespaceURI); } // Returns a XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(String localName, String namespaceURI) { return new XmlElementList(this, localName, namespaceURI); } // Returns the XmlElement with the specified ID. public virtual XmlElement GetElementById(string elementId) { if (_htElementIdMap != null) { ArrayList elementList = (ArrayList)(_htElementIdMap[elementId]); if (elementList != null) { foreach (WeakReference elemRef in elementList) { XmlElement elem = (XmlElement)elemRef.Target; if (elem != null && elem.IsConnected()) return elem; } } } return null; } // Imports a node from another document to this document. public virtual XmlNode ImportNode(XmlNode node, bool deep) { return ImportNodeInternal(node, deep); } private XmlNode ImportNodeInternal(XmlNode node, bool deep) { XmlNode newNode = null; if (node == null) { throw new InvalidOperationException(SR.Xdom_Import_NullNode); } else { switch (node.NodeType) { case XmlNodeType.Element: newNode = CreateElement(node.Prefix, node.LocalName, node.NamespaceURI); ImportAttributes(node, newNode); if (deep) ImportChildren(node, newNode, deep); break; case XmlNodeType.Attribute: Debug.Assert(((XmlAttribute)node).Specified); newNode = CreateAttribute(node.Prefix, node.LocalName, node.NamespaceURI); ImportChildren(node, newNode, true); break; case XmlNodeType.Text: newNode = CreateTextNode(node.Value); break; case XmlNodeType.Comment: newNode = CreateComment(node.Value); break; case XmlNodeType.ProcessingInstruction: newNode = CreateProcessingInstruction(node.Name, node.Value); break; case XmlNodeType.XmlDeclaration: XmlDeclaration decl = (XmlDeclaration)node; newNode = CreateXmlDeclaration(decl.Version, decl.Encoding, decl.Standalone); break; case XmlNodeType.CDATA: newNode = CreateCDataSection(node.Value); break; case XmlNodeType.DocumentType: XmlDocumentType docType = (XmlDocumentType)node; newNode = CreateDocumentType(docType.Name, docType.PublicId, docType.SystemId, docType.InternalSubset); break; case XmlNodeType.DocumentFragment: newNode = CreateDocumentFragment(); if (deep) ImportChildren(node, newNode, deep); break; case XmlNodeType.EntityReference: newNode = CreateEntityReference(node.Name); // we don't import the children of entity reference because they might result in different // children nodes given different namespace context in the new document. break; case XmlNodeType.Whitespace: newNode = CreateWhitespace(node.Value); break; case XmlNodeType.SignificantWhitespace: newNode = CreateSignificantWhitespace(node.Value); break; default: throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, SR.Xdom_Import, node.NodeType.ToString())); } } return newNode; } private void ImportAttributes(XmlNode fromElem, XmlNode toElem) { int cAttr = fromElem.Attributes.Count; for (int iAttr = 0; iAttr < cAttr; iAttr++) { if (fromElem.Attributes[iAttr].Specified) toElem.Attributes.SetNamedItem(ImportNodeInternal(fromElem.Attributes[iAttr], true)); } } private void ImportChildren(XmlNode fromNode, XmlNode toNode, bool deep) { Debug.Assert(toNode.NodeType != XmlNodeType.EntityReference); for (XmlNode n = fromNode.FirstChild; n != null; n = n.NextSibling) { toNode.AppendChild(ImportNodeInternal(n, deep)); } } // Microsoft extensions // Gets the XmlNameTable associated with this // implementation. public XmlNameTable NameTable { get { return _implementation.NameTable; } } // Creates a XmlAttribute with the specified Prefix, LocalName, // and NamespaceURI. public virtual XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI) { return new XmlAttribute(AddAttrXmlName(prefix, localName, namespaceURI, null), this); } protected internal virtual XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI) { return new XmlUnspecifiedAttribute(prefix, localName, namespaceURI, this); } public virtual XmlElement CreateElement(string prefix, string localName, string namespaceURI) { XmlElement elem = new XmlElement(AddXmlName(prefix, localName, namespaceURI, null), true, this); if (!IsLoading) AddDefaultAttributes(elem); return elem; } // Gets or sets a value indicating whether to preserve whitespace. public bool PreserveWhitespace { get { return _preserveWhitespace; } set { _preserveWhitespace = value; } } // Gets a value indicating whether the node is read-only. public override bool IsReadOnly { get { return false; } } internal XmlNamedNodeMap Entities { get { if (_entities == null) _entities = new XmlNamedNodeMap(this); return _entities; } set { _entities = value; } } internal bool IsLoading { get { return _isLoading; } set { _isLoading = value; } } internal bool ActualLoadingStatus { get { return _actualLoadingStatus; } set { _actualLoadingStatus = value; } } // Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI. public virtual XmlNode CreateNode(XmlNodeType type, string prefix, string name, string namespaceURI) { switch (type) { case XmlNodeType.Element: if (prefix != null) return CreateElement(prefix, name, namespaceURI); else return CreateElement(name, namespaceURI); case XmlNodeType.Attribute: if (prefix != null) return CreateAttribute(prefix, name, namespaceURI); else return CreateAttribute(name, namespaceURI); case XmlNodeType.Text: return CreateTextNode(string.Empty); case XmlNodeType.CDATA: return CreateCDataSection(string.Empty); case XmlNodeType.EntityReference: return CreateEntityReference(name); case XmlNodeType.ProcessingInstruction: return CreateProcessingInstruction(name, string.Empty); case XmlNodeType.XmlDeclaration: return CreateXmlDeclaration("1.0", null, null); case XmlNodeType.Comment: return CreateComment(string.Empty); case XmlNodeType.DocumentFragment: return CreateDocumentFragment(); case XmlNodeType.DocumentType: return CreateDocumentType(name, string.Empty, string.Empty, string.Empty); case XmlNodeType.Document: return new XmlDocument(); case XmlNodeType.SignificantWhitespace: return CreateSignificantWhitespace(string.Empty); case XmlNodeType.Whitespace: return CreateWhitespace(string.Empty); default: throw new ArgumentException(SR.Format(SR.Arg_CannotCreateNode, type)); } } // Creates an XmlNode with the specified node type, Name, and // NamespaceURI. public virtual XmlNode CreateNode(string nodeTypeString, string name, string namespaceURI) { return CreateNode(ConvertToNodeType(nodeTypeString), name, namespaceURI); } // Creates an XmlNode with the specified XmlNodeType, Name, and // NamespaceURI. public virtual XmlNode CreateNode(XmlNodeType type, string name, string namespaceURI) { return CreateNode(type, null, name, namespaceURI); } // Creates an XmlNode object based on the information in the XmlReader. // The reader must be positioned on a node or attribute. public virtual XmlNode ReadNode(XmlReader reader) { XmlNode node = null; try { IsLoading = true; XmlLoader loader = new XmlLoader(); node = loader.ReadCurrentNode(this, reader); } finally { IsLoading = false; } return node; } internal XmlNodeType ConvertToNodeType(string nodeTypeString) { if (nodeTypeString == "element") { return XmlNodeType.Element; } else if (nodeTypeString == "attribute") { return XmlNodeType.Attribute; } else if (nodeTypeString == "text") { return XmlNodeType.Text; } else if (nodeTypeString == "cdatasection") { return XmlNodeType.CDATA; } else if (nodeTypeString == "entityreference") { return XmlNodeType.EntityReference; } else if (nodeTypeString == "entity") { return XmlNodeType.Entity; } else if (nodeTypeString == "processinginstruction") { return XmlNodeType.ProcessingInstruction; } else if (nodeTypeString == "comment") { return XmlNodeType.Comment; } else if (nodeTypeString == "document") { return XmlNodeType.Document; } else if (nodeTypeString == "documenttype") { return XmlNodeType.DocumentType; } else if (nodeTypeString == "documentfragment") { return XmlNodeType.DocumentFragment; } else if (nodeTypeString == "notation") { return XmlNodeType.Notation; } else if (nodeTypeString == "significantwhitespace") { return XmlNodeType.SignificantWhitespace; } else if (nodeTypeString == "whitespace") { return XmlNodeType.Whitespace; } throw new ArgumentException(SR.Format(SR.Xdom_Invalid_NT_String, nodeTypeString)); } private XmlTextReader SetupReader(XmlTextReader tr) { tr.XmlValidatingReaderCompatibilityMode = true; tr.EntityHandling = EntityHandling.ExpandCharEntities; if (this.HasSetResolver) tr.XmlResolver = GetResolver(); return tr; } // Loads the XML document from the specified URL. public virtual void Load(string filename) { XmlTextReader reader = SetupReader(new XmlTextReader(filename, NameTable)); try { Load(reader); } finally { reader.Close(); } } public virtual void Load(Stream inStream) { XmlTextReader reader = SetupReader(new XmlTextReader(inStream, NameTable)); try { Load(reader); } finally { reader.Impl.Close(false); } } // Loads the XML document from the specified TextReader. public virtual void Load(TextReader txtReader) { XmlTextReader reader = SetupReader(new XmlTextReader(txtReader, NameTable)); try { Load(reader); } finally { reader.Impl.Close(false); } } // Loads the XML document from the specified XmlReader. public virtual void Load(XmlReader reader) { try { IsLoading = true; _actualLoadingStatus = true; RemoveAll(); fEntRefNodesPresent = false; fCDataNodesPresent = false; _reportValidity = true; XmlLoader loader = new XmlLoader(); loader.Load(this, reader, _preserveWhitespace); } finally { IsLoading = false; _actualLoadingStatus = false; // Ensure the bit is still on after loading a dtd _reportValidity = true; } } // Loads the XML document from the specified string. public virtual void LoadXml(string xml) { XmlTextReader reader = SetupReader(new XmlTextReader(new StringReader(xml), NameTable)); try { Load(reader); } finally { reader.Close(); } } //TextEncoding is the one from XmlDeclaration if there is any internal Encoding TextEncoding { get { if (Declaration != null) { string value = Declaration.Encoding; if (value.Length > 0) { return System.Text.Encoding.GetEncoding(value); } } return null; } } public override string InnerText { set { throw new InvalidOperationException(SR.Xdom_Document_Innertext); } } public override string InnerXml { get { return base.InnerXml; } set { LoadXml(value); } } // Saves the XML document to the specified file. //Saves out the to the file with exact content in the XmlDocument. public virtual void Save(string filename) { if (DocumentElement == null) throw new XmlException(SR.Xml_InvalidXmlDocument, SR.Xdom_NoRootEle); XmlDOMTextWriter xw = new XmlDOMTextWriter(filename, TextEncoding); try { if (_preserveWhitespace == false) xw.Formatting = Formatting.Indented; WriteTo(xw); xw.Flush(); } finally { xw.Close(); } } //Saves out the to the file with exact content in the XmlDocument. public virtual void Save(Stream outStream) { XmlDOMTextWriter xw = new XmlDOMTextWriter(outStream, TextEncoding); if (_preserveWhitespace == false) xw.Formatting = Formatting.Indented; WriteTo(xw); xw.Flush(); } // Saves the XML document to the specified TextWriter. // //Saves out the file with xmldeclaration which has encoding value equal to //that of textwriter's encoding public virtual void Save(TextWriter writer) { XmlDOMTextWriter xw = new XmlDOMTextWriter(writer); if (_preserveWhitespace == false) xw.Formatting = Formatting.Indented; Save(xw); } // Saves the XML document to the specified XmlWriter. // //Saves out the file with xmldeclaration which has encoding value equal to //that of textwriter's encoding public virtual void Save(XmlWriter w) { XmlNode n = this.FirstChild; if (n == null) return; if (w.WriteState == WriteState.Start) { if (n is XmlDeclaration) { if (Standalone.Length == 0) w.WriteStartDocument(); else if (Standalone == "yes") w.WriteStartDocument(true); else if (Standalone == "no") w.WriteStartDocument(false); n = n.NextSibling; } else { w.WriteStartDocument(); } } while (n != null) { n.WriteTo(w); n = n.NextSibling; } w.Flush(); } // Saves the node to the specified XmlWriter. // //Writes out the to the file with exact content in the XmlDocument. public override void WriteTo(XmlWriter w) { WriteContentTo(w); } // Saves all the children of the node to the specified XmlWriter. // //Writes out the to the file with exact content in the XmlDocument. public override void WriteContentTo(XmlWriter xw) { foreach (XmlNode n in this) { n.WriteTo(xw); } } public void Validate(ValidationEventHandler validationEventHandler) { Validate(validationEventHandler, this); } public void Validate(ValidationEventHandler validationEventHandler, XmlNode nodeToValidate) { if (_schemas == null || _schemas.Count == 0) { //Should we error throw new InvalidOperationException(SR.XmlDocument_NoSchemaInfo); } XmlDocument parentDocument = nodeToValidate.Document; if (parentDocument != this) { throw new ArgumentException(SR.Format(SR.XmlDocument_NodeNotFromDocument, nameof(nodeToValidate))); } if (nodeToValidate == this) { _reportValidity = false; } DocumentSchemaValidator validator = new DocumentSchemaValidator(this, _schemas, validationEventHandler); validator.Validate(nodeToValidate); if (nodeToValidate == this) { _reportValidity = true; } } public event XmlNodeChangedEventHandler NodeInserting { add { _onNodeInsertingDelegate += value; } remove { _onNodeInsertingDelegate -= value; } } public event XmlNodeChangedEventHandler NodeInserted { add { _onNodeInsertedDelegate += value; } remove { _onNodeInsertedDelegate -= value; } } public event XmlNodeChangedEventHandler NodeRemoving { add { _onNodeRemovingDelegate += value; } remove { _onNodeRemovingDelegate -= value; } } public event XmlNodeChangedEventHandler NodeRemoved { add { _onNodeRemovedDelegate += value; } remove { _onNodeRemovedDelegate -= value; } } public event XmlNodeChangedEventHandler NodeChanging { add { _onNodeChangingDelegate += value; } remove { _onNodeChangingDelegate -= value; } } public event XmlNodeChangedEventHandler NodeChanged { add { _onNodeChangedDelegate += value; } remove { _onNodeChangedDelegate -= value; } } internal override XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action) { _reportValidity = false; switch (action) { case XmlNodeChangedAction.Insert: if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null) { return null; } break; case XmlNodeChangedAction.Remove: if (_onNodeRemovingDelegate == null && _onNodeRemovedDelegate == null) { return null; } break; case XmlNodeChangedAction.Change: if (_onNodeChangingDelegate == null && _onNodeChangedDelegate == null) { return null; } break; } return new XmlNodeChangedEventArgs(node, oldParent, newParent, oldValue, newValue, action); } internal XmlNodeChangedEventArgs GetInsertEventArgsForLoad(XmlNode node, XmlNode newParent) { if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null) { return null; } string nodeValue = node.Value; return new XmlNodeChangedEventArgs(node, null, newParent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); } internal override void BeforeEvent(XmlNodeChangedEventArgs args) { if (args != null) { switch (args.Action) { case XmlNodeChangedAction.Insert: if (_onNodeInsertingDelegate != null) _onNodeInsertingDelegate(this, args); break; case XmlNodeChangedAction.Remove: if (_onNodeRemovingDelegate != null) _onNodeRemovingDelegate(this, args); break; case XmlNodeChangedAction.Change: if (_onNodeChangingDelegate != null) _onNodeChangingDelegate(this, args); break; } } } internal override void AfterEvent(XmlNodeChangedEventArgs args) { if (args != null) { switch (args.Action) { case XmlNodeChangedAction.Insert: if (_onNodeInsertedDelegate != null) _onNodeInsertedDelegate(this, args); break; case XmlNodeChangedAction.Remove: if (_onNodeRemovedDelegate != null) _onNodeRemovedDelegate(this, args); break; case XmlNodeChangedAction.Change: if (_onNodeChangedDelegate != null) _onNodeChangedDelegate(this, args); break; } } } // The function such through schema info to find out if there exists a default attribute with passed in names in the passed in element // If so, return the newly created default attribute (with children tree); // Otherwise, return null. internal XmlAttribute GetDefaultAttribute(XmlElement elem, string attrPrefix, string attrLocalname, string attrNamespaceURI) { SchemaInfo schInfo = DtdSchemaInfo; SchemaElementDecl ed = GetSchemaElementDecl(elem); if (ed != null && ed.AttDefs != null) { IDictionaryEnumerator attrDefs = ed.AttDefs.GetEnumerator(); while (attrDefs.MoveNext()) { SchemaAttDef attdef = (SchemaAttDef)attrDefs.Value; if (attdef.Presence == SchemaDeclBase.Use.Default || attdef.Presence == SchemaDeclBase.Use.Fixed) { if (attdef.Name.Name == attrLocalname) { if ((schInfo.SchemaType == SchemaType.DTD && attdef.Name.Namespace == attrPrefix) || (schInfo.SchemaType != SchemaType.DTD && attdef.Name.Namespace == attrNamespaceURI)) { //find a def attribute with the same name, build a default attribute and return XmlAttribute defattr = PrepareDefaultAttribute(attdef, attrPrefix, attrLocalname, attrNamespaceURI); return defattr; } } } } } return null; } internal String Version { get { XmlDeclaration decl = Declaration; if (decl != null) return decl.Version; return null; } } internal String Encoding { get { XmlDeclaration decl = Declaration; if (decl != null) return decl.Encoding; return null; } } internal String Standalone { get { XmlDeclaration decl = Declaration; if (decl != null) return decl.Standalone; return null; } } internal XmlEntity GetEntityNode(String name) { if (DocumentType != null) { XmlNamedNodeMap entites = DocumentType.Entities; if (entites != null) return (XmlEntity)(entites.GetNamedItem(name)); } return null; } public override IXmlSchemaInfo SchemaInfo { get { if (_reportValidity) { XmlElement documentElement = DocumentElement; if (documentElement != null) { switch (documentElement.SchemaInfo.Validity) { case XmlSchemaValidity.Valid: return ValidSchemaInfo; case XmlSchemaValidity.Invalid: return InvalidSchemaInfo; } } } return NotKnownSchemaInfo; } } public override String BaseURI { get { return baseURI; } } internal void SetBaseURI(String inBaseURI) { baseURI = inBaseURI; } internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { Debug.Assert(doc == this); if (!IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); if (!CanInsertAfter(newChild, LastChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); XmlNodeChangedEventArgs args = GetInsertEventArgsForLoad(newChild, this); if (args != null) BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (_lastChild == null) { newNode.next = newNode; } else { newNode.next = _lastChild.next; _lastChild.next = newNode; } _lastChild = newNode; newNode.SetParentForLoad(this); if (args != null) AfterEvent(args); return newNode; } internal override XPathNodeType XPNodeType { get { return XPathNodeType.Root; } } internal bool HasEntityReferences { get { return fEntRefNodesPresent; } } internal XmlAttribute NamespaceXml { get { if (_namespaceXml == null) { _namespaceXml = new XmlAttribute(AddAttrXmlName(strXmlns, strXml, strReservedXmlns, null), this); _namespaceXml.Value = strReservedXml; } return _namespaceXml; } } } }
// 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.IO; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using Internal.Reflection.Core; using Internal.Runtime.TypeLoader; using Internal.Metadata.NativeFormat; namespace Internal.Reflection.Execution { //============================================================================================================================= // The assembly resolution policy for Project N's emulation of "classic reflection." // // The policy is very simple: the only assemblies that can be "loaded" are those that are statically linked into the running // native process. There is no support for probing for assemblies in directories, user-supplied files, GACs, NICs or any // other repository. //============================================================================================================================= public sealed partial class AssemblyBinderImplementation : AssemblyBinder { private AssemblyBinderImplementation() { _scopeGroups = new KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[0]; ModuleList.AddModuleRegistrationCallback(RegisterModule); } public static AssemblyBinderImplementation Instance { get; } = new AssemblyBinderImplementation(); partial void BindEcmaByteArray(byte[] rawAssembly, byte[] rawSymbolStore, ref AssemblyBindResult bindResult, ref Exception exception, ref bool? result); partial void BindEcmaAssemblyName(RuntimeAssemblyName refName, bool cacheMissedLookups, ref AssemblyBindResult result, ref Exception exception, ref Exception preferredException, ref bool resultBoolean); partial void InsertEcmaLoadedAssemblies(List<AssemblyBindResult> loadedAssemblies); public sealed override bool Bind(byte[] rawAssembly, byte[] rawSymbolStore, out AssemblyBindResult bindResult, out Exception exception) { bool? result = null; exception = null; bindResult = default(AssemblyBindResult); BindEcmaByteArray(rawAssembly, rawSymbolStore, ref bindResult, ref exception, ref result); // If the Ecma assembly binder isn't linked in, simply throw PlatformNotSupportedException if (!result.HasValue) throw new PlatformNotSupportedException(); else return result.Value; } public sealed override bool Bind(RuntimeAssemblyName refName, bool cacheMissedLookups, out AssemblyBindResult result, out Exception exception) { bool foundMatch = false; result = default(AssemblyBindResult); exception = null; Exception preferredException = null; refName = refName.CanonicalizePublicKeyToken(); // At least one real-world app calls Type.GetType() for "char" using the assembly name "mscorlib". To accomodate this, // we will adopt the desktop CLR rule that anything named "mscorlib" automatically binds to the core assembly. bool useMscorlibNameCompareFunc = false; RuntimeAssemblyName compareRefName = refName; if (refName.Name == "mscorlib") { useMscorlibNameCompareFunc = true; compareRefName = AssemblyNameParser.Parse(AssemblyBinder.DefaultAssemblyNameForGetType); } foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> group in ScopeGroups) { bool nameMatches; if (useMscorlibNameCompareFunc) { nameMatches = MscorlibAssemblyNameMatches(compareRefName, group.Key); } else { nameMatches = AssemblyNameMatches(refName, group.Key, ref preferredException); } if (nameMatches) { if (foundMatch) { exception = new AmbiguousMatchException(); return false; } foundMatch = true; ScopeDefinitionGroup scopeDefinitionGroup = group.Value; result.Reader = scopeDefinitionGroup.CanonicalScope.Reader; result.ScopeDefinitionHandle = scopeDefinitionGroup.CanonicalScope.Handle; result.OverflowScopes = scopeDefinitionGroup.OverflowScopes; } } BindEcmaAssemblyName(refName, cacheMissedLookups, ref result, ref exception, ref preferredException, ref foundMatch); if (exception != null) return false; if (!foundMatch) { exception = preferredException ?? new FileNotFoundException(SR.Format(SR.FileNotFound_AssemblyNotFound, refName.FullName)); return false; } return true; } public sealed override IList<AssemblyBindResult> GetLoadedAssemblies() { List<AssemblyBindResult> loadedAssemblies = new List<AssemblyBindResult>(ScopeGroups.Length); foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> group in ScopeGroups) { ScopeDefinitionGroup scopeDefinitionGroup = group.Value; AssemblyBindResult result = default(AssemblyBindResult); result.Reader = scopeDefinitionGroup.CanonicalScope.Reader; result.ScopeDefinitionHandle = scopeDefinitionGroup.CanonicalScope.Handle; result.OverflowScopes = scopeDefinitionGroup.OverflowScopes; loadedAssemblies.Add(result); } InsertEcmaLoadedAssemblies(loadedAssemblies); return loadedAssemblies; } // // Name match routine for mscorlib references // private bool MscorlibAssemblyNameMatches(RuntimeAssemblyName coreAssemblyName, RuntimeAssemblyName defName) { // // The defName came from trusted metadata so it should be fully specified. // Debug.Assert(defName.Version != null); Debug.Assert(defName.CultureName != null); Debug.Assert((coreAssemblyName.Flags & AssemblyNameFlags.PublicKey) == 0); Debug.Assert((defName.Flags & AssemblyNameFlags.PublicKey) == 0); if (defName.Name != coreAssemblyName.Name) return false; byte[] defPkt = defName.PublicKeyOrToken; if (defPkt == null) return false; if (!ArePktsEqual(defPkt, coreAssemblyName.PublicKeyOrToken)) return false; return true; } // // Encapsulates the assembly ref->def matching policy. // private bool AssemblyNameMatches(RuntimeAssemblyName refName, RuntimeAssemblyName defName, ref Exception preferredException) { // // The defName came from trusted metadata so it should be fully specified. // Debug.Assert(defName.Version != null); Debug.Assert(defName.CultureName != null); Debug.Assert((defName.Flags & AssemblyNameFlags.PublicKey) == 0); Debug.Assert((refName.Flags & AssemblyNameFlags.PublicKey) == 0); if (!(refName.Name.Equals(defName.Name, StringComparison.OrdinalIgnoreCase))) return false; if (refName.Version != null) { if (!AssemblyVersionMatches(refVersion: refName.Version, defVersion: defName.Version)) { preferredException = new FileLoadException(SR.Format(SR.FileLoadException_RefDefMismatch, refName.FullName, defName.Version, refName.Version)); return false; } } if (refName.CultureName != null) { if (!(refName.CultureName.Equals(defName.CultureName))) return false; } AssemblyNameFlags materialRefNameFlags = refName.Flags.ExtractAssemblyNameFlags(); AssemblyNameFlags materialDefNameFlags = defName.Flags.ExtractAssemblyNameFlags(); if (materialRefNameFlags != materialDefNameFlags) { return false; } byte[] refPublicKeyToken = refName.PublicKeyOrToken; if (refPublicKeyToken != null) { byte[] defPublicKeyToken = defName.PublicKeyOrToken; if (defPublicKeyToken == null) return false; if (!ArePktsEqual(refPublicKeyToken, defPublicKeyToken)) return false; } return true; } private static bool AssemblyVersionMatches(Version refVersion, Version defVersion) { if (defVersion.Major < refVersion.Major) return false; if (defVersion.Major > refVersion.Major) return true; if (defVersion.Minor < refVersion.Minor) return false; if (defVersion.Minor > refVersion.Minor) return true; if (refVersion.Build == -1) return true; if (defVersion.Build < refVersion.Build) return false; if (defVersion.Build > refVersion.Build) return true; if (refVersion.Revision == -1) return true; if (defVersion.Revision < refVersion.Revision) return false; return true; } /// <summary> /// This callback gets called whenever a module gets registered. It adds the metadata reader /// for the new module to the available scopes. The lock in ExecutionEnvironmentImplementation ensures /// that this function may never be called concurrently so that we can assume that two threads /// never update the reader and scope list at the same time. /// </summary> /// <param name="moduleInfo">Module to register</param> private void RegisterModule(ModuleInfo moduleInfo) { NativeFormatModuleInfo nativeFormatModuleInfo = moduleInfo as NativeFormatModuleInfo; if (nativeFormatModuleInfo == null) { return; } LowLevelDictionaryWithIEnumerable<RuntimeAssemblyName, ScopeDefinitionGroup> scopeGroups = new LowLevelDictionaryWithIEnumerable<RuntimeAssemblyName, ScopeDefinitionGroup>(); foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> oldGroup in _scopeGroups) { scopeGroups.Add(oldGroup.Key, oldGroup.Value); } AddScopesFromReaderToGroups(scopeGroups, nativeFormatModuleInfo.MetadataReader); // Update reader and scope list KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[] scopeGroupsArray = new KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[scopeGroups.Count]; int i = 0; foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> data in scopeGroups) { scopeGroupsArray[i] = data; i++; } _scopeGroups = scopeGroupsArray; } private KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[] ScopeGroups { get { return _scopeGroups; } } private void AddScopesFromReaderToGroups(LowLevelDictionaryWithIEnumerable<RuntimeAssemblyName, ScopeDefinitionGroup> groups, MetadataReader reader) { foreach (ScopeDefinitionHandle scopeDefinitionHandle in reader.ScopeDefinitions) { RuntimeAssemblyName defName = scopeDefinitionHandle.ToRuntimeAssemblyName(reader).CanonicalizePublicKeyToken(); ScopeDefinitionGroup scopeDefinitionGroup; if (groups.TryGetValue(defName, out scopeDefinitionGroup)) { scopeDefinitionGroup.AddOverflowScope(new QScopeDefinition(reader, scopeDefinitionHandle)); } else { scopeDefinitionGroup = new ScopeDefinitionGroup(new QScopeDefinition(reader, scopeDefinitionHandle)); groups.Add(defName, scopeDefinitionGroup); } } } private static bool ArePktsEqual(byte[] pkt1, byte[] pkt2) { if (pkt1.Length != pkt2.Length) return false; for (int i = 0; i < pkt1.Length; i++) { if (pkt1[i] != pkt2[i]) return false; } return true; } private volatile KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[] _scopeGroups; private class ScopeDefinitionGroup { public ScopeDefinitionGroup(QScopeDefinition canonicalScope) { _canonicalScope = canonicalScope; } public QScopeDefinition CanonicalScope { get { return _canonicalScope; } } public IEnumerable<QScopeDefinition> OverflowScopes { get { return _overflowScopes.ToArray(); } } public void AddOverflowScope(QScopeDefinition overflowScope) { _overflowScopes.Add(overflowScope); } private readonly QScopeDefinition _canonicalScope; private ArrayBuilder<QScopeDefinition> _overflowScopes; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- /// Returns true if the current quality settings equal /// this graphics quality level. function GraphicsQualityLevel::isCurrent( %this ) { // Test each pref to see if the current value // equals our stored value. for ( %i=0; %i < %this.count(); %i++ ) { %pref = %this.getKey( %i ); %value = %this.getValue( %i ); if ( getVariable( %pref ) !$= %value ) return false; } return true; } /// Applies the graphics quality settings and calls /// 'onApply' on itself or its parent group if its /// been overloaded. function GraphicsQualityLevel::apply( %this ) { for ( %i=0; %i < %this.count(); %i++ ) { %pref = %this.getKey( %i ); %value = %this.getValue( %i ); setVariable( %pref, %value ); } // If we have an overloaded onApply method then // call it now to finalize the changes. if ( %this.isMethod( "onApply" ) ) %this.onApply(); else { %group = %this.getGroup(); if ( isObject( %group ) && %group.isMethod( "onApply" ) ) %group.onApply( %this ); } } function GraphicsQualityPopup::init( %this, %qualityGroup ) { assert( isObject( %this ) ); assert( isObject( %qualityGroup ) ); // Clear the existing content first. %this.clear(); // Fill it. %select = -1; for ( %i=0; %i < %qualityGroup.getCount(); %i++ ) { %level = %qualityGroup.getObject( %i ); if ( %level.isCurrent() ) %select = %i; %this.add( %level.getInternalName(), %i ); } // Setup a default selection. if ( %select == -1 ) %this.setText( "Custom" ); else %this.setSelected( %select ); } function GraphicsQualityPopup::apply( %this, %qualityGroup, %testNeedApply ) { assert( isObject( %this ) ); assert( isObject( %qualityGroup ) ); %quality = %this.getText(); %index = %this.findText( %quality ); if ( %index == -1 ) return false; %level = %qualityGroup.getObject( %index ); if ( isObject( %level ) && !%level.isCurrent() ) { if ( %testNeedApply ) return true; %level.apply(); } return false; } function OptionsDlg::setPane(%this, %pane) { %this-->OptAudioPane.setVisible(false); %this-->OptGraphicsPane.setVisible(false); %this-->OptNetworkPane.setVisible(false); %this-->OptControlsPane.setVisible(false); %this.findObjectByInternalName( "Opt" @ %pane @ "Pane", true ).setVisible(true); %this.fillRemapList(); // Update the state of the apply button. %this._updateApplyState(); } function OptionsDlg::onWake(%this) { if ( isFunction("getWebDeployment") && getWebDeployment() ) { // Cannot enable full screen under web deployment %this-->OptGraphicsFullscreenToggle.setStateOn( false ); %this-->OptGraphicsFullscreenToggle.setVisible( false ); } else { %this-->OptGraphicsFullscreenToggle.setStateOn( Canvas.isFullScreen() ); } %this-->OptGraphicsVSyncToggle.setStateOn( !$pref::Video::disableVerticalSync ); OptionsDlg.initResMenu(); %resSelId = OptionsDlg-->OptGraphicsResolutionMenu.findText( _makePrettyResString( $pref::Video::mode ) ); if( %resSelId != -1 ) OptionsDlg-->OptGraphicsResolutionMenu.setSelected( %resSelId ); OptGraphicsDriverMenu.clear(); %buffer = getDisplayDeviceList(); %count = getFieldCount( %buffer ); for(%i = 0; %i < %count; %i++) OptGraphicsDriverMenu.add(getField(%buffer, %i), %i); %selId = OptGraphicsDriverMenu.findText( getDisplayDeviceInformation() ); if ( %selId == -1 ) OptGraphicsDriverMenu.setFirstSelected(); else OptGraphicsDriverMenu.setSelected( %selId ); // Setup the graphics quality dropdown menus. %this-->OptMeshQualityPopup.init( MeshQualityGroup ); %this-->OptTextureQualityPopup.init( TextureQualityGroup ); %this-->OptLightingQualityPopup.init( LightingQualityGroup ); %this-->OptShaderQualityPopup.init( ShaderQualityGroup ); // Setup the anisotropic filtering menu. %ansioCtrl = %this-->OptAnisotropicPopup; %ansioCtrl.clear(); %ansioCtrl.add( "Off", 0 ); %ansioCtrl.add( "4X", 4 ); %ansioCtrl.add( "8X", 8 ); %ansioCtrl.add( "16X", 16 ); %ansioCtrl.setSelected( $pref::Video::defaultAnisotropy, false ); // set up the Refresh Rate menu. %refreshMenu = %this-->OptRefreshSelectMenu; %refreshMenu.clear(); // %refreshMenu.add("Auto", 60); %refreshMenu.add("60", 60); %refreshMenu.add("75", 75); %refreshMenu.setSelected( getWord( $pref::Video::mode, $WORD::REFRESH ) ); // Audio //OptAudioHardwareToggle.setStateOn($pref::SFX::useHardware); //OptAudioHardwareToggle.setActive( true ); %this-->OptAudioVolumeMaster.setValue( $pref::SFX::masterVolume ); %this-->OptAudioVolumeShell.setValue( $pref::SFX::channelVolume[ $GuiAudioType] ); %this-->OptAudioVolumeSim.setValue( $pref::SFX::channelVolume[ $SimAudioType ] ); %this-->OptAudioVolumeMusic.setValue( $pref::SFX::channelVolume[ $MusicAudioType ] ); OptAudioProviderList.clear(); %buffer = sfxGetAvailableDevices(); %count = getRecordCount( %buffer ); for(%i = 0; %i < %count; %i++) { %record = getRecord(%buffer, %i); %provider = getField(%record, 0); if ( OptAudioProviderList.findText( %provider ) == -1 ) OptAudioProviderList.add( %provider, %i ); } OptAudioProviderList.sort(); %selId = OptAudioProviderList.findText($pref::SFX::provider); if ( %selId == -1 ) OptAudioProviderList.setFirstSelected(); else OptAudioProviderList.setSelected( %selId ); // Populate the Anti-aliasing popup. %aaMenu = %this-->OptAAQualityPopup; %aaMenu.clear(); %aaMenu.Add( "Off", 0 ); %aaMenu.Add( "1x", 1 ); %aaMenu.Add( "2x", 2 ); %aaMenu.Add( "4x", 4 ); %aaMenu.setSelected( getWord( $pref::Video::mode, $WORD::AA ) ); OptMouseSensitivity.value = $pref::Input::LinkMouseSensitivity; // Set the graphics pane to start. %this-->OptGraphicsButton.performClick(); } function OptionsDlg::onSleep(%this) { // write out the control config into the rw/config.cs file moveMap.save( "scripts/client/config.cs" ); } function OptGraphicsDriverMenu::onSelect( %this, %id, %text ) { // Attempt to keep the same resolution settings: %resMenu = OptionsDlg-->OptGraphicsResolutionMenu; %currRes = %resMenu.getText(); // If its empty the use the current. if ( %currRes $= "" ) %currRes = _makePrettyResString( Canvas.getVideoMode() ); // Fill the resolution list. optionsDlg.initResMenu(); // Try to select the previous settings: %selId = %resMenu.findText( %currRes ); if ( %selId == -1 ) %selId = 0; %resMenu.setSelected( %selId ); OptionsDlg._updateApplyState(); } function _makePrettyResString( %resString ) { %width = getWord( %resString, $WORD::RES_X ); %height = getWord( %resString, $WORD::RES_Y ); %aspect = %width / %height; %aspect = mRound( %aspect * 100 ) * 0.01; switch$( %aspect ) { case "1.33": %aspect = "4:3"; case "1.78": %aspect = "16:9"; default: %aspect = ""; } %outRes = %width @ " x " @ %height; if ( %aspect !$= "" ) %outRes = %outRes @ " (" @ %aspect @ ")"; return %outRes; } function OptionsDlg::initResMenu( %this ) { // Clear out previous values %resMenu = %this-->OptGraphicsResolutionMenu; %resMenu.clear(); // If we are in a browser then we can't change our resolution through // the options dialog if (getWebDeployment()) { %count = 0; %currRes = getWords(Canvas.getVideoMode(), $WORD::RES_X, $WORD::RES_Y); %resMenu.add(%currRes, %count); %count++; return; } // Loop through all and add all valid resolutions %count = 0; %resCount = Canvas.getModeCount(); for (%i = 0; %i < %resCount; %i++) { %testResString = Canvas.getMode( %i ); %testRes = _makePrettyResString( %testResString ); // Only add to list if it isn't there already. if (%resMenu.findText(%testRes) == -1) { %resMenu.add(%testRes, %i); %count++; } } %resMenu.sort(); } function OptionsDlg::applyGraphics( %this, %testNeedApply ) { %newAdapter = OptGraphicsDriverMenu.getText(); %numAdapters = GFXInit::getAdapterCount(); %newDevice = $pref::Video::displayDevice; for( %i = 0; %i < %numAdapters; %i ++ ) if( GFXInit::getAdapterName( %i ) $= %newAdapter ) { %newDevice = GFXInit::getAdapterType( %i ); break; } // Change the device. if ( %newDevice !$= $pref::Video::displayDevice ) { if ( %testNeedApply ) return true; $pref::Video::displayDevice = %newDevice; if( %newAdapter !$= getDisplayDeviceInformation() ) MessageBoxOK( "Change requires restart", "Please restart the game for a display device change to take effect." ); } // Gather the new video mode. if ( isFunction("getWebDeployment") && getWebDeployment() ) { // Under web deployment, we use the custom resolution rather than a Canvas // defined one. %newRes = %this-->OptGraphicsResolutionMenu.getText(); } else { %newRes = getWords( Canvas.getMode( %this-->OptGraphicsResolutionMenu.getSelected() ), $WORD::RES_X, $WORD::RES_Y ); } %newBpp = 32; // ... its not 1997 anymore. %newFullScreen = %this-->OptGraphicsFullscreenToggle.getValue() ? "true" : "false"; %newRefresh = %this-->OptRefreshSelectMenu.getSelected(); %newVsync = !%this-->OptGraphicsVSyncToggle.getValue(); %newFSAA = %this-->OptAAQualityPopup.getSelected(); // Under web deployment we can't be full screen. if ( isFunction("getWebDeployment") && getWebDeployment() ) { %newFullScreen = false; } else if ( %newFullScreen $= "false" ) { // If we're in windowed mode switch the fullscreen check // if the resolution is bigger than the desktop. %deskRes = getDesktopResolution(); %deskResX = getWord(%deskRes, $WORD::RES_X); %deskResY = getWord(%deskRes, $WORD::RES_Y); if ( getWord( %newRes, $WORD::RES_X ) > %deskResX || getWord( %newRes, $WORD::RES_Y ) > %deskResY ) { %newFullScreen = "true"; %this-->OptGraphicsFullscreenToggle.setStateOn( true ); } } // Build the final mode string. %newMode = %newRes SPC %newFullScreen SPC %newBpp SPC %newRefresh SPC %newFSAA; // Change the video mode. if ( %newMode !$= $pref::Video::mode || %newVsync != $pref::Video::disableVerticalSync ) { if ( %testNeedApply ) return true; $pref::Video::mode = %newMode; $pref::Video::disableVerticalSync = %newVsync; configureCanvas(); } // Test and apply the graphics settings. if ( %this-->OptMeshQualityPopup.apply( MeshQualityGroup, %testNeedApply ) ) return true; if ( %this-->OptTextureQualityPopup.apply( TextureQualityGroup, %testNeedApply ) ) return true; if ( %this-->OptLightingQualityPopup.apply( LightingQualityGroup, %testNeedApply ) ) return true; if ( %this-->OptShaderQualityPopup.apply( ShaderQualityGroup, %testNeedApply ) ) return true; // Check the anisotropic filtering. %level = %this-->OptAnisotropicPopup.getSelected(); if ( %level != $pref::Video::defaultAnisotropy ) { if ( %testNeedApply ) return true; $pref::Video::defaultAnisotropy = %level; } // If we're applying the state then recheck the // state to update the apply button. if ( !%testNeedApply ) %this._updateApplyState(); return false; } function OptionsDlg::_updateApplyState( %this ) { %applyCtrl = %this-->Apply; %graphicsPane = %this-->OptGraphicsPane; assert( isObject( %applyCtrl ) ); assert( isObject( %graphicsPane ) ); %applyCtrl.active = %graphicsPane.isVisible() && %this.applyGraphics( true ); } function OptionsDlg::_autoDetectQuality( %this ) { %msg = GraphicsQualityAutodetect(); %this.onWake(); if ( %msg !$= "" ) { MessageBoxOK( "Notice", %msg ); } } $RemapCount = 0; $RemapName[$RemapCount] = "Forward"; $RemapCmd[$RemapCount] = "moveforward"; $RemapCount++; $RemapName[$RemapCount] = "Backward"; $RemapCmd[$RemapCount] = "movebackward"; $RemapCount++; $RemapName[$RemapCount] = "Strafe Left"; $RemapCmd[$RemapCount] = "moveleft"; $RemapCount++; $RemapName[$RemapCount] = "Strafe Right"; $RemapCmd[$RemapCount] = "moveright"; $RemapCount++; $RemapName[$RemapCount] = "Turn Left"; $RemapCmd[$RemapCount] = "turnLeft"; $RemapCount++; $RemapName[$RemapCount] = "Turn Right"; $RemapCmd[$RemapCount] = "turnRight"; $RemapCount++; $RemapName[$RemapCount] = "Look Up"; $RemapCmd[$RemapCount] = "panUp"; $RemapCount++; $RemapName[$RemapCount] = "Look Down"; $RemapCmd[$RemapCount] = "panDown"; $RemapCount++; $RemapName[$RemapCount] = "Jump"; $RemapCmd[$RemapCount] = "jump"; $RemapCount++; $RemapName[$RemapCount] = "Fire Weapon"; $RemapCmd[$RemapCount] = "mouseFire"; $RemapCount++; $RemapName[$RemapCount] = "Adjust Zoom"; $RemapCmd[$RemapCount] = "setZoomFov"; $RemapCount++; $RemapName[$RemapCount] = "Toggle Zoom"; $RemapCmd[$RemapCount] = "toggleZoom"; $RemapCount++; $RemapName[$RemapCount] = "Free Look"; $RemapCmd[$RemapCount] = "toggleFreeLook"; $RemapCount++; $RemapName[$RemapCount] = "Switch 1st/3rd"; $RemapCmd[$RemapCount] = "toggleFirstPerson"; $RemapCount++; $RemapName[$RemapCount] = "Chat to Everyone"; $RemapCmd[$RemapCount] = "toggleMessageHud"; $RemapCount++; $RemapName[$RemapCount] = "Message Hud PageUp"; $RemapCmd[$RemapCount] = "pageMessageHudUp"; $RemapCount++; $RemapName[$RemapCount] = "Message Hud PageDown"; $RemapCmd[$RemapCount] = "pageMessageHudDown"; $RemapCount++; $RemapName[$RemapCount] = "Resize Message Hud"; $RemapCmd[$RemapCount] = "resizeMessageHud"; $RemapCount++; $RemapName[$RemapCount] = "Show Scores"; $RemapCmd[$RemapCount] = "showPlayerList"; $RemapCount++; $RemapName[$RemapCount] = "Animation - Wave"; $RemapCmd[$RemapCount] = "celebrationWave"; $RemapCount++; $RemapName[$RemapCount] = "Animation - Salute"; $RemapCmd[$RemapCount] = "celebrationSalute"; $RemapCount++; $RemapName[$RemapCount] = "Suicide"; $RemapCmd[$RemapCount] = "suicide"; $RemapCount++; $RemapName[$RemapCount] = "Toggle Camera"; $RemapCmd[$RemapCount] = "toggleCamera"; $RemapCount++; $RemapName[$RemapCount] = "Drop Camera at Player"; $RemapCmd[$RemapCount] = "dropCameraAtPlayer"; $RemapCount++; $RemapName[$RemapCount] = "Drop Player at Camera"; $RemapCmd[$RemapCount] = "dropPlayerAtCamera"; $RemapCount++; $RemapName[$RemapCount] = "Bring up Options Dialog"; $RemapCmd[$RemapCount] = "bringUpOptions"; $RemapCount++; function restoreDefaultMappings() { moveMap.delete(); exec( "scripts/client/default.bind.cs" ); optionsDlg.fillRemapList(); } function getMapDisplayName( %device, %action ) { if ( %device $= "keyboard" ) return( %action ); else if ( strstr( %device, "mouse" ) != -1 ) { // Substitute "mouse" for "button" in the action string: %pos = strstr( %action, "button" ); if ( %pos != -1 ) { %mods = getSubStr( %action, 0, %pos ); %object = getSubStr( %action, %pos, 1000 ); %instance = getSubStr( %object, strlen( "button" ), 1000 ); return( %mods @ "mouse" @ ( %instance + 1 ) ); } else error( "Mouse input object other than button passed to getDisplayMapName!" ); } else if ( strstr( %device, "joystick" ) != -1 ) { // Substitute "joystick" for "button" in the action string: %pos = strstr( %action, "button" ); if ( %pos != -1 ) { %mods = getSubStr( %action, 0, %pos ); %object = getSubStr( %action, %pos, 1000 ); %instance = getSubStr( %object, strlen( "button" ), 1000 ); return( %mods @ "joystick" @ ( %instance + 1 ) ); } else { %pos = strstr( %action, "pov" ); if ( %pos != -1 ) { %wordCount = getWordCount( %action ); %mods = %wordCount > 1 ? getWords( %action, 0, %wordCount - 2 ) @ " " : ""; %object = getWord( %action, %wordCount - 1 ); switch$ ( %object ) { case "upov": %object = "POV1 up"; case "dpov": %object = "POV1 down"; case "lpov": %object = "POV1 left"; case "rpov": %object = "POV1 right"; case "upov2": %object = "POV2 up"; case "dpov2": %object = "POV2 down"; case "lpov2": %object = "POV2 left"; case "rpov2": %object = "POV2 right"; default: %object = "??"; } return( %mods @ %object ); } else error( "Unsupported Joystick input object passed to getDisplayMapName!" ); } } return( "??" ); } function buildFullMapString( %index ) { %name = $RemapName[%index]; %cmd = $RemapCmd[%index]; %temp = moveMap.getBinding( %cmd ); if ( %temp $= "" ) return %name TAB ""; %mapString = ""; %count = getFieldCount( %temp ); for ( %i = 0; %i < %count; %i += 2 ) { if ( %mapString !$= "" ) %mapString = %mapString @ ", "; %device = getField( %temp, %i + 0 ); %object = getField( %temp, %i + 1 ); %mapString = %mapString @ getMapDisplayName( %device, %object ); } return %name TAB %mapString; } function OptionsDlg::fillRemapList( %this ) { %remapList = %this-->OptRemapList; %remapList.clear(); for ( %i = 0; %i < $RemapCount; %i++ ) %remapList.addRow( %i, buildFullMapString( %i ) ); } function OptionsDlg::doRemap( %this ) { %remapList = %this-->OptRemapList; %selId = %remapList.getSelectedId(); %name = $RemapName[%selId]; RemapDlg-->OptRemapText.setValue( "Re-bind \"" @ %name @ "\" to..." ); OptRemapInputCtrl.index = %selId; Canvas.pushDialog( RemapDlg ); } function redoMapping( %device, %action, %cmd, %oldIndex, %newIndex ) { //%actionMap.bind( %device, %action, $RemapCmd[%newIndex] ); moveMap.bind( %device, %action, %cmd ); %remapList = %this-->OptRemapList; %remapList.setRowById( %oldIndex, buildFullMapString( %oldIndex ) ); %remapList.setRowById( %newIndex, buildFullMapString( %newIndex ) ); } function findRemapCmdIndex( %command ) { for ( %i = 0; %i < $RemapCount; %i++ ) { if ( %command $= $RemapCmd[%i] ) return( %i ); } return( -1 ); } /// This unbinds actions beyond %count associated to the /// particular moveMap %commmand. function unbindExtraActions( %command, %count ) { %temp = moveMap.getBinding( %command ); if ( %temp $= "" ) return; %count = getFieldCount( %temp ) - ( %count * 2 ); for ( %i = 0; %i < %count; %i += 2 ) { %device = getField( %temp, %i + 0 ); %action = getField( %temp, %i + 1 ); moveMap.unbind( %device, %action ); } } function OptRemapInputCtrl::onInputEvent( %this, %device, %action ) { //error( "** onInputEvent called - device = " @ %device @ ", action = " @ %action @ " **" ); Canvas.popDialog( RemapDlg ); // Test for the reserved keystrokes: if ( %device $= "keyboard" ) { // Cancel... if ( %action $= "escape" ) { // Do nothing... return; } } %cmd = $RemapCmd[%this.index]; %name = $RemapName[%this.index]; // Grab the friendly display name for this action // which we'll use when prompting the user below. %mapName = getMapDisplayName( %device, %action ); // Get the current command this action is mapped to. %prevMap = moveMap.getCommand( %device, %action ); // If nothing was mapped to the previous command // mapping then it's easy... just bind it. if ( %prevMap $= "" ) { unbindExtraActions( %cmd, 1 ); moveMap.bind( %device, %action, %cmd ); optionsDlg-->OptRemapList.setRowById( %this.index, buildFullMapString( %this.index ) ); return; } // If the previous command is the same as the // current then they hit the same input as what // was already assigned. if ( %prevMap $= %cmd ) { unbindExtraActions( %cmd, 0 ); moveMap.bind( %device, %action, %cmd ); optionsDlg-->OptRemapList.setRowById( %this.index, buildFullMapString( %this.index ) ); return; } // Look for the index of the previous mapping. %prevMapIndex = findRemapCmdIndex( %prevMap ); // If we get a negative index then the previous // mapping was to an item that isn't included in // the mapping list... so we cannot unmap it. if ( %prevMapIndex == -1 ) { MessageBoxOK( "Remap Failed", "\"" @ %mapName @ "\" is already bound to a non-remappable command!" ); return; } // Setup the forced remapping callback command. %callback = "redoMapping(" @ %device @ ", \"" @ %action @ "\", \"" @ %cmd @ "\", " @ %prevMapIndex @ ", " @ %this.index @ ");"; // Warn that we're about to remove the old mapping and // replace it with another. %prevCmdName = $RemapName[%prevMapIndex]; MessageBoxYesNo( "Warning", "\"" @ %mapName @ "\" is already bound to \"" @ %prevCmdName @ "\"!\nDo you wish to replace this mapping?", %callback, "" ); } $AudioTestHandle = 0; // Description to use for playing the volume test sound. This isn't // played with the description of the channel that has its volume changed // because we know nothing about the playback state of the channel. If it // is paused or stopped, the test sound would not play then. $AudioTestDescription = new SFXDescription() { sourceGroup = AudioChannelMaster; }; function OptAudioUpdateMasterVolume( %volume ) { if( %volume == $pref::SFX::masterVolume ) return; sfxSetMasterVolume( %volume ); $pref::SFX::masterVolume = %volume; if( !isObject( $AudioTestHandle ) ) $AudioTestHandle = sfxPlayOnce( AudioChannel, "core/art/sound/volumeTest.wav" ); } function OptAudioUpdateChannelVolume( %description, %volume ) { %channel = sfxGroupToOldChannel( %description.sourceGroup ); if( %volume == $pref::SFX::channelVolume[ %channel ] ) return; sfxSetChannelVolume( %channel, %volume ); $pref::SFX::channelVolume[ %channel ] = %volume; if( !isObject( $AudioTestHandle ) ) { $AudioTestDescription.volume = %volume; $AudioTestHandle = sfxPlayOnce( $AudioTestDescription, "core/art/sound/volumeTest.wav" ); } } function OptAudioProviderList::onSelect( %this, %id, %text ) { // Skip empty provider selections. if ( %text $= "" ) return; $pref::SFX::provider = %text; OptAudioDeviceList.clear(); %buffer = sfxGetAvailableDevices(); %count = getRecordCount( %buffer ); for(%i = 0; %i < %count; %i++) { %record = getRecord(%buffer, %i); %provider = getField(%record, 0); %device = getField(%record, 1); if (%provider !$= %text) continue; if ( OptAudioDeviceList.findText( %device ) == -1 ) OptAudioDeviceList.add( %device, %i ); } // Find the previous selected device. %selId = OptAudioDeviceList.findText($pref::SFX::device); if ( %selId == -1 ) OptAudioDeviceList.setFirstSelected(); else OptAudioDeviceList.setSelected( %selId ); } function OptAudioDeviceList::onSelect( %this, %id, %text ) { // Skip empty selections. if ( %text $= "" ) return; $pref::SFX::device = %text; if ( !sfxCreateDevice( $pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, -1 ) ) error( "Unable to create SFX device: " @ $pref::SFX::provider SPC $pref::SFX::device SPC $pref::SFX::useHardware ); } function OptMouseSetSensitivity(%value) { $pref::Input::LinkMouseSensitivity = %value; } /* function OptAudioHardwareToggle::onClick(%this) { if (!sfxCreateDevice($pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, -1)) error("Unable to create SFX device: " @ $pref::SFX::provider SPC $pref::SFX::device SPC $pref::SFX::useHardware); } */
/** * Copyright 2015-2016 GetSocial B.V. * * 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. */ #if UNITY_IOS using System; using UnityEngine; using System.Collections.Generic; using System.Runtime.InteropServices; namespace GetSocialSdk.Core { class GetSocialNativeBridgeIOS : IGetSocialNativeBridge { public delegate bool IsAvailableForDeviceDelegate(); private static IGetSocialNativeBridge instance; #region initialization private GetSocialNativeBridgeIOS() { } public static IGetSocialNativeBridge GetInstance() { if(instance == null) { instance = new GetSocialNativeBridgeIOS(); } MainThreadExecutor.Init(); return instance; } #endregion public bool IsInitialized { get { return _isInitialized(); } } public IConfiguration Configuration { get { return ConfigurationIOS.GetInstance(); } } public int UnreadNotificationsCount { get { return _getUnreadNotificationsCount(); } } public string Version { get { return _getVersion(); } } public string ApiVersion { get { return _getApiVersion(); } } public string Environment { get { return _getEnvironment(); } } #region current_user public string UserGuid { get { return _getUserGuid(); } } public string UserDisplayName { get { return _getUserDisplayName(); } } public string UserAvatarUrl { get { return _getUserAvatarUrl(); } } public bool IsUserAnonymous { get { return _isUserAnonymous(); } } public string[] UserIdentities { get { // TODO Replace with JSON array serialization var providers = _getUserIdentities(); if(string.IsNullOrEmpty(providers)) { return new string[] { }; } return providers.Split(','); } } public bool UserHasIdentityForProvider(string provider) { return _userHasIdentityForProvider(provider); } public string GetUserIdForProvider(string provider) { return _userHasIdentityForProvider(provider) ? _getUserIdForProvider(provider) : null; } public void SetDisplayName(string displayName, Action onSuccess, Action<string> onFailure) { _setUserDisplayName(displayName, onSuccess.GetPointer(), onFailure.GetPointer(), CompleteCallback, FailureCallback); } public void SetAvatarUrl(string avatarUrl, Action onSuccess, Action<string> onFailure) { _setUserAvatarUrl(avatarUrl, onSuccess.GetPointer(), onFailure.GetPointer(), CompleteCallback, FailureCallback); } public void AddUserIdentity(string serializedIdentity, Action<CurrentUser.AddIdentityResult> onComplete, Action<string> onFailure, CurrentUser.OnAddIdentityConflictDelegate onConflict) { _addUserIdentity(serializedIdentity, onComplete.GetPointer(), onFailure.GetPointer(), onConflict.GetPointer(), OnAddUserIdentityCompleteProxy.OnAddUserIdentityComplete, FailureCallback, OnAddUserIdentityConflictProxy.OnUserIdentityConflict); } public void RemoveUserIdentity(string provider, Action onSuccess, Action<string> onFailure) { _removeUserIdentity(provider, onSuccess.GetPointer(), onFailure.GetPointer(), CompleteCallback, FailureCallback); } public void ResetUser(Action onSuccess, Action<string> onFailure) { _resetUser(onSuccess.GetPointer(), onFailure.GetPointer(), CompleteCallback, FailureCallback); } public void FollowUser(String guid, Action onSuccess, Action<string> onFailure) { _followUser(guid, onSuccess.GetPointer(), onFailure.GetPointer(), CompleteCallback, FailureCallback); } public void FollowUser(string provider, string userId, Action onSuccess, Action<string> onFailure) { _followUserOnProvider(provider, userId, onSuccess.GetPointer(), onFailure.GetPointer(), CompleteCallback, FailureCallback); } public void UnfollowUser(String guid, Action onSuccess, Action<string> onFailure) { _unfollowUser(guid, onSuccess.GetPointer(), onFailure.GetPointer(), CompleteCallback, FailureCallback); } public void UnfollowUser(string provider, string userId, Action onSuccess, Action<string> onFailure) { _unfollowUserOnProvider(provider, userId, onSuccess.GetPointer(), onFailure.GetPointer(), CompleteCallback, FailureCallback); } public void GetFollowing(int offset, int count, Action<List<User>> onSuccess, Action<string> onFailure) { _getFollowingUsers(offset, count, onSuccess.GetPointer(), onFailure.GetPointer(), UserListCallback.OnUserListReceived, FailureCallback); } public void GetFollowers(int offset, int count, Action<List<User>> onSuccess, Action<string> onFailure) { _getFollowerUsers(offset, count, onSuccess.GetPointer(), onFailure.GetPointer(), UserListCallback.OnUserListReceived, FailureCallback); } #endregion public void Init(string key, Action onSuccess = null, Action onFailure = null) { if(!GetSocialSettings.IsAutoRegisrationForPushesEnabledIOS) { _disableAutoRegistrationForPushNotifications(); } _initWithKey(key, CompleteCallback, onSuccess.GetPointer(), onFailure.GetPointer()); } public void RegisterPlugin(string providerId, IPlugin plugin) { if(plugin is IInvitePlugin) { _registerInvitePlugin(providerId, plugin.GetPointer(), UnityInvitePluginProxy.InviteFriends, UnityPluginProxy.IsAvailableForDevice); } else { Debug.LogWarning("For now, GetSocial support only Invite plugins"); } } public void ShowView(string serializedViewBuilder, ViewBuilder.OnViewActionDelegate onViewAction = null) { _showView(serializedViewBuilder, onViewAction.GetPointer(), OnViewActionProxy.OnViewBuilderActionCallback); } public void CloseView(bool saveViewState) { _closeView(saveViewState); } public void RestoreView() { _restoreView(); } public void Save(string state, Action onSuccess = null, Action<string> onFailure = null) { _save(state, onSuccess.GetPointer(), onFailure.GetPointer(), CompleteCallback, FailureCallback); } public void GetLastSave(Action<string> onSuccess, Action<string> onFailure) { _getLastSave(onSuccess.GetPointer(), onFailure.GetPointer(), StringResultCallaback, FailureCallback); } public void PostActivity(string text, byte[] image, string buttonText, string actionId, string[] tags, Action<string> onSuccess, Action onFailure) { var tagsCount = tags != null ? tags.Length : 0; var base64image = image != null ? Convert.ToBase64String(image) : null; _postActivity(text, base64image, buttonText, actionId, tagsCount, tags, onSuccess.GetPointer(), onFailure.GetPointer(), StringResultCallaback, CompleteCallback); } public void SetOnWindowStateChangeListener(Action onOpen, Action onClose) { Action<bool> onWindowStateChangedAction = (isOpen) => { if(isOpen) { onOpen(); } else { onClose(); } }; _setOnWindowStateChangeListener(onWindowStateChangedAction.GetPointer(), OnWindowStateChangeListenerProxy.OnWindowStateChange); } public void SetOnInviteFriendsListener(Action onInviteFriendsIntent, Action<int> onFriendsInvited) { _setOnInviteFriendsListener(onInviteFriendsIntent.GetPointer(), onFriendsInvited.GetPointer(), InviteFriendsListenerProxy.OnInviteFriendsIntent, InviteFriendsListenerProxy.OnFriendsInvited); } public void SetOnUserActionPerformedListener(OnUserActionPerformed onUserActionPerformed) { _setOnUserActionPerformedListener(onUserActionPerformed.GetPointer(), OnUserActionPerformedListenerProxy.OnUserActionPerformedCallback); } public void SetOnUserAvatarClickListener(OnUserAvatarClick onUserAvatarClick) { _setOnUserAvatarClickListener(onUserAvatarClick.GetPointer(), OnUserAvatarClickProxy.OnUserAvatarClickCallback); } public void SetOnAppAvatarClickListener(OnAppAvatarClick onAppAvatarClick) { _setOnAppAvatarClickListener(onAppAvatarClick.GetPointer(), OnAppAvatarClickListenerProxy.OnAppAvatarClickCallback); } public void SetOnActivityActionClickListener(OnActivityActionClick onActivityActionClick) { _setOnActivityActionClickListener(onActivityActionClick.GetPointer(), OnActivityActionClickListenerProxy.OnActivityActionClickCallback); } public void SetOnInviteButtonClickListener(OnInviteButtonClick onInviteButtonClick) { _setOnInviteButtonClickListener(onInviteButtonClick.GetPointer(), OnInviteButtonClickListenerProxy.OnInviteButtonClickCallback); } public void SetOnUserGeneratedContentListener(OnUserGeneratedContent onUserGeneratedContent) { _setOnUserGeneratedContentListener(onUserGeneratedContent.GetPointer(), OnUserGeneratedContentListenerProxy.OnUserGeneratedContentCallback); } public void SetOnReferralDataReceivedListener(OnReferralDataReceived onReferralDataReceived) { _setOnReferralDataReceivedListener(onReferralDataReceived.GetPointer(), OnReferralDataReceivedListenerProxy.OnReferralDataReceivedCallback); } public void SetOnUnreadNotificationsCountChangeListener(Action<int> onUnreadNotificationsCountChange) { _setOnUnreadNotificationsCountChangeListener(onUnreadNotificationsCountChange.GetPointer(), OnUnreadNotificationsCountChangedListenerProxy.OnUnreadNotificationsCountChange); } public void SetLanguage(string languageCode) { _setLanguage(languageCode); } public string[] GetSupportedInviteProviders() { // TODO Replace with JSON array serialization var providersString = _getSupportedInviteProviders(); if(string.IsNullOrEmpty(providersString)) { return new string[] { }; } return providersString.Split(','); } public void InviteFriendsUsingProvider(string provider, String subject = null, string text = null, byte[] image = null, IDictionary<string, string> referralData = null) { var base64image = image != null ? Convert.ToBase64String(image) : null; string referralDataJSON = null; if(referralData != null) { referralDataJSON = new JSONObject(referralData).ToString(); } _inviteFriendsUsingProvider(provider, subject, text, base64image, referralDataJSON); } public void GetLeaderboard(string leaderboardId, Action<string> onSuccess, Action<string> onFailure = null) { _getLeaderboard(leaderboardId, onSuccess.GetPointer(), onFailure.GetPointer(), StringResultCallaback); } public void GetLeaderboards(HashSet<string> leaderboardIds, Action<string> onSuccess, Action<string> onFailure = null) { var leaderboardIdsArray = new string[leaderboardIds.Count]; leaderboardIds.CopyTo(leaderboardIdsArray); _getLeaderboards(leaderboardIdsArray.Length, leaderboardIdsArray, onSuccess.GetPointer(), onFailure.GetPointer(), StringResultCallaback); } public void GetLeaderboards(int offset, int count, Action<string> onSuccess, Action<string> onFailure = null) { _getLeaderboardsWithOffset(offset, count, onSuccess.GetPointer(), onFailure.GetPointer(), StringResultCallaback); } public void GetLeaderboardScores(string leaderboardId, int offset, int count, LeaderboardScoreType scoreType, Action<string> onSuccess, Action<string> onFailure = null) { _getLeaderboardScores(leaderboardId, offset, count, (int)scoreType, onSuccess.GetPointer(), onFailure.GetPointer(), StringResultCallaback); } public void SubmitLeaderboardScore(string leaderboardId, int score, Action<int> onSuccess, Action onFailure) { _submitLeaderboardScore(leaderboardId, score, onSuccess.GetPointer(), onFailure.GetPointer(), SubmitLeaderboardScoreListenerProxy.OnRankChange, CompleteCallback); } #region init_internal [DllImport("__Internal")] private static extern void _initWithKey(string key, CompleteCallbackDelegate actionExecutor, IntPtr onSuccessActionPtr, IntPtr onFailureActionPtr); [DllImport("__Internal")] private static extern bool _isInitialized(); [DllImport("__Internal")] private static extern void _disableAutoRegistrationForPushNotifications(); #endregion [DllImport("__Internal")] private static extern int _getUnreadNotificationsCount(); [DllImport("__Internal")] private static extern string _getVersion(); [DllImport("__Internal")] private static extern string _getApiVersion(); [DllImport("__Internal")] private static extern string _getEnvironment(); [DllImport("__Internal")] private static extern void _registerInvitePlugin(string providerId, IntPtr pluginPtr, UnityInvitePluginProxy.InviteFriendsDelegate inviteFriends, UnityPluginProxy.IsAvailableForDeviceDelegate isAvailableForDevice); [DllImport("__Internal")] private static extern void _showView(string serializedViewBuilder, IntPtr onViewActionPtr, OnViewActionProxy.ExecuteViewActionDelegate executeViewAction); [DllImport("__Internal")] private static extern void _closeView(bool saveViewState); [DllImport("__Internal")] private static extern void _restoreView(); #region current_user_internal [DllImport("__Internal")] private static extern string _getUserGuid(); [DllImport("__Internal")] private static extern string _getUserDisplayName(); [DllImport("__Internal")] private static extern void _setUserDisplayName(string displayName, IntPtr onSuccessPtr, IntPtr onFailurePtr, CompleteCallbackDelegate executeCompleteAction, FailureCallbackDelegate failureCallback); [DllImport("__Internal")] private static extern string _getUserAvatarUrl(); [DllImport("__Internal")] private static extern void _setUserAvatarUrl(string avatarUrl, IntPtr onSuccessPtr, IntPtr onFailurePtr, CompleteCallbackDelegate executeCompleteAction, FailureCallbackDelegate failureCallback); [DllImport("__Internal")] private static extern bool _isUserAnonymous(); [DllImport("__Internal")] private static extern string _getUserIdentities(); [DllImport("__Internal")] private static extern bool _userHasIdentityForProvider(string provider); [DllImport("__Internal")] private static extern string _getUserIdForProvider(string provider); [DllImport("__Internal")] private static extern void _addUserIdentity(string serializedIdentityInfo, IntPtr onCompletePtr, IntPtr onFailurePtr, IntPtr onConflictPtr, OnAddUserIdentityCompleteProxy.OnAddUserIdentityCompleteDelegate onAddUserIdentityComplete, FailureCallbackDelegate failureCallback, OnAddUserIdentityConflictProxy.OnAddUserIdentityConflictDelegate onConflict); [DllImport("__Internal")] private static extern void _removeUserIdentity(string providerId, IntPtr onSuccessPtr, IntPtr onFailurePtr, CompleteCallbackDelegate completeCallback, FailureCallbackDelegate failureCallback); [DllImport("__Internal")] private static extern void _resetUser(IntPtr onSuccessPtr, IntPtr onFailurePtr, CompleteCallbackDelegate completeCallback, FailureCallbackDelegate failureCallback); // follow-unfollow [DllImport("__Internal")] private static extern void _followUser(string guid, IntPtr onSuccessPtr, IntPtr onFailurePtr, CompleteCallbackDelegate completeCallback, FailureCallbackDelegate failureCallback); [DllImport("__Internal")] private static extern void _followUserOnProvider(string provider, string userId, IntPtr onSuccessPtr, IntPtr onFailurePtr, CompleteCallbackDelegate completeCallback, FailureCallbackDelegate failureCallback); [DllImport("__Internal")] private static extern void _unfollowUser(string guid, IntPtr onSuccessPtr, IntPtr onFailurePtr, CompleteCallbackDelegate completeCallback, FailureCallbackDelegate failureCallback); [DllImport("__Internal")] private static extern void _unfollowUserOnProvider(string provider, string userId, IntPtr onSuccessPtr, IntPtr onFailurePtr, CompleteCallbackDelegate completeCallback, FailureCallbackDelegate failureCallback); // get users [DllImport("__Internal")] private static extern void _getFollowingUsers(int offset, int count, IntPtr onSuccessPtr, IntPtr onFailurePtr, UserListCallback.GetUserListCallbackDelegate getUserListCallback, FailureCallbackDelegate failureCallback); [DllImport("__Internal")] private static extern void _getFollowerUsers(int offset, int count, IntPtr onSuccessPtr, IntPtr onFailurePtr, UserListCallback.GetUserListCallbackDelegate getUserListCallback, FailureCallbackDelegate failureCallback); #endregion [DllImport("__Internal")] private static extern void _save(string state, IntPtr onSuccessPtr, IntPtr onFailurePtr, CompleteCallbackDelegate executeSuccessAction, FailureCallbackDelegate failureCallback); [DllImport("__Internal")] private static extern void _getLastSave(IntPtr onSuccessPtr, IntPtr onFailurePtr, StringResultCallbackDelegate executeSuccessAction, FailureCallbackDelegate executeCompleteAction); [DllImport("__Internal")] private static extern void _postActivity(string text, string base64image, string buttonText, string actionId, int tagsCount, string[] tags, IntPtr onSuccessPtr, IntPtr onFailurePtr, StringResultCallbackDelegate executeSuccessAction, CompleteCallbackDelegate executeCompleteAction); [DllImport("__Internal")] private static extern void _setOnWindowStateChangeListener(IntPtr onWindowStateChangedPtr, OnWindowStateChangeListenerProxy.OnWindowStateChangeDelegate onWIndowStateChange); [DllImport("__Internal")] private static extern void _setOnInviteFriendsListener(IntPtr onInviteFriendsIntentPtr, IntPtr onFriendsInvitedPtr, InviteFriendsListenerProxy.OnInviteFriendsIntentDelegate onInviteFriendsIntent, InviteFriendsListenerProxy.OnFriendsInvitedDelegate onFriendsInvited); [DllImport("__Internal")] private static extern void _setOnUserActionPerformedListener(IntPtr onUserActionPerformedPtr, OnUserActionPerformedListenerProxy.OnUserActionPerformedDelegate onUserActionPerformedCallback); [DllImport("__Internal")] private static extern void _setOnUserAvatarClickListener(IntPtr onUserAvatarClickPtr, OnUserAvatarClickProxy.OnUserAvatarClickDelegate onUserAvatarClick); [DllImport("__Internal")] private static extern void _setOnAppAvatarClickListener(IntPtr onGameAvatarClickPtr, OnAppAvatarClickListenerProxy.OnAppAvatarClickDelegate onGameAvatarClick); [DllImport("__Internal")] private static extern void _setOnActivityActionClickListener(IntPtr onActivityActionClickPtr, OnActivityActionClickListenerProxy.OnActivityActionClickDelegate onActivityActionClick); [DllImport("__Internal")] private static extern void _setOnInviteButtonClickListener(IntPtr onInviteButtonClickPtr, OnInviteButtonClickListenerProxy.OnInviteButtonClickDelegate onInviteButtonClick); [DllImport("__Internal")] private static extern void _setOnUserGeneratedContentListener(IntPtr onUserGeneratedContent, OnUserGeneratedContentListenerProxy.OnUserGeneratedContentDelegate onUserGeneratedContentCallback); [DllImport("__Internal")] private static extern void _setOnReferralDataReceivedListener(IntPtr onReferralDataReceivedPtr, OnReferralDataReceivedListenerProxy.OnReferralDataReceivedDelegate onReferralDataReceived); [DllImport("__Internal")] private static extern void _setOnUnreadNotificationsCountChangeListener(IntPtr onOpenProfilePtr, OnUnreadNotificationsCountChangedListenerProxy.OnUnreadNotificationsCountChangedListenerDelegate onUnreadNotificationCountChange); [DllImport("__Internal")] private static extern void _setLanguage(string languageCode); [DllImport("__Internal")] private static extern string _getSupportedInviteProviders(); [DllImport("__Internal")] private static extern void _inviteFriendsUsingProvider(string provider, string subject, string text, string base64image, string referralDataJSON); #region leaderboards_internal [DllImport("__Internal")] private static extern void _getLeaderboard(string leaderboardId, IntPtr onSuccessPtr, IntPtr onFailurePtr, StringResultCallbackDelegate callback); [DllImport("__Internal")] private static extern void _getLeaderboards(int leaderboardsCount, string[] leaderboardIdsArray, IntPtr onSuccessPtr, IntPtr onFailurePtr, StringResultCallbackDelegate callback); [DllImport("__Internal")] private static extern void _getLeaderboardsWithOffset(int offset, int count, IntPtr onSuccessPtr, IntPtr onFailurePtr, StringResultCallbackDelegate callback); [DllImport("__Internal")] private static extern void _getLeaderboardScores(string leaderboardId, int offset, int count, int scoreType, IntPtr onSuccessPtr, IntPtr onFailurePtr, StringResultCallbackDelegate callback); [DllImport("__Internal")] private static extern void _submitLeaderboardScore(string leaderboardId, int score, IntPtr onSuccessPtr, IntPtr onFailurePtr, SubmitLeaderboardScoreListenerProxy.OnRankChangeDelegate onRankChange, CompleteCallbackDelegate failureCallback); #endregion #region execute_actions_internal [DllImport("__Internal")] internal static extern void _executeCompleteCallback(IntPtr callbackPtr); [DllImport("__Internal")] internal static extern void _executeErrorCallback(IntPtr callbackPtr, string errorMessage); [DllImport("__Internal")] internal static extern void _executeInvitedFriendsCallback(IntPtr onSuccessPtr, string requestId, int invitedFriendsCount, string[] invitedFriends); [DllImport("__Internal")] internal static extern void _executeAddUserIndentityConflictResolver(IntPtr callbackPtr, int resolutionStrategy); [DllImport("__Internal")] internal static extern void _executeOnUserPerformedActionFinalize(IntPtr callbackPtr, bool shouldPerformAction); #endregion #region common_native_callbacks internal delegate void CompleteCallbackDelegate(IntPtr actionPtr); internal delegate void StringResultCallbackDelegate(IntPtr actionPtr, string data); internal delegate void BoolResultCallbackDelegate(IntPtr actionPtr, bool result); internal delegate void FailureCallbackDelegate(IntPtr actionPtr, string error); [MonoPInvokeCallback(typeof(CompleteCallbackDelegate))] public static void CompleteCallback(IntPtr actionPtr) { #if DEVELOPMENT_BUILD Debug.Log("CompleteCallback"); #endif if(actionPtr != IntPtr.Zero) { var action = actionPtr.Cast<Action>(); action(); } } [MonoPInvokeCallback(typeof(StringResultCallbackDelegate))] public static void StringResultCallaback(IntPtr actionPtr, string data) { #if DEVELOPMENT_BUILD Debug.Log("StringResultCallaback: " + data); #endif if(actionPtr != IntPtr.Zero) { var action = actionPtr.Cast<Action<string>>(); action(data); } } [MonoPInvokeCallback(typeof(BoolResultCallbackDelegate))] public static void BoolResultCallback(IntPtr actionPtr, bool result) { #if DEVELOPMENT_BUILD Debug.Log("BoolResultCallback: " + result); #endif if(actionPtr != IntPtr.Zero) { var action = actionPtr.Cast<Action<bool>>(); action(result); } } [MonoPInvokeCallback(typeof(FailureCallbackDelegate))] public static void FailureCallback(IntPtr actionPtr, string errorMessage) { #if DEVELOPMENT_BUILD Debug.Log("FailureCallback: " + errorMessage); #endif if(actionPtr != IntPtr.Zero) { var action = actionPtr.Cast<Action<string>>(); action(errorMessage); } } #endregion } } #endif
using OpenSim.Framework; using OpenSim.Region.Physics.Manager; /* * 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 copyrightD * 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 OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { /* * Class to wrap all objects. * The rest of BulletSim doesn't need to keep checking for avatars or prims * unless the difference is significant. * * Variables in the physicsl objects are in three forms: * VariableName: used by the simulator and performs taint operations, etc * RawVariableName: direct reference to the BulletSim storage for the variable value * ForceVariableName: direct reference (store and fetch) to the value in the physics engine. * The last one should only be referenced in taint-time. */ /* * As of 20121221, the following are the call sequences (going down) for different script physical functions: * llApplyImpulse llApplyRotImpulse llSetTorque llSetForce * SOP.ApplyImpulse SOP.ApplyAngularImpulse SOP.SetAngularImpulse SOP.SetForce * SOG.ApplyImpulse SOG.ApplyAngularImpulse SOG.SetAngularImpulse * PA.AddForce PA.AddAngularForce PA.Torque = v PA.Force = v * BS.ApplyCentralForce BS.ApplyTorque */ // Flags used to denote which properties updates when making UpdateProperties calls to linksets, etc. public enum UpdatedProperties : uint { Position = 1 << 0, Orientation = 1 << 1, Velocity = 1 << 2, Acceleration = 1 << 3, RotationalVelocity = 1 << 4, EntPropUpdates = Position | Orientation | Velocity | Acceleration | RotationalVelocity, } public abstract class BSPhysObject : PhysicsActor { protected BSPhysObject() { } protected BSPhysObject(BSScene parentScene, uint localID, string name, string typeName) { IsInitialized = false; PhysScene = parentScene; LocalID = localID; PhysObjectName = name; Name = name; // PhysicsActor also has the name of the object. Someday consolidate. TypeName = typeName; // The collection of things that push me around PhysicalActors = new BSActorCollection(PhysScene); // Initialize variables kept in base. GravModifier = 1.0f; Gravity = new OMV.Vector3(0f, 0f, BSParam.Gravity); HoverActive = false; // We don't have any physical representation yet. PhysBody = new BulletBody(localID); PhysShape = new BSShapeNull(); UserSetCenterOfMassDisplacement = null; PrimAssetState = PrimAssetCondition.Unknown; // Default material type. Also sets Friction, Restitution and Density. SetMaterial((int)MaterialAttributes.Material.Wood); CollisionCollection = new CollisionEventUpdate(); CollisionsLastReported = CollisionCollection; CollisionsLastTick = new CollisionEventUpdate(); CollisionsLastTickStep = -1; SubscribedEventsMs = 0; // Crazy values that will never be true CollidingStep = BSScene.NotASimulationStep; CollidingGroundStep = BSScene.NotASimulationStep; CollisionAccumulation = BSScene.NotASimulationStep; ColliderIsMoving = false; CollisionScore = 0; // All axis free. LockedLinearAxis = LockedAxisFree; LockedAngularAxis = LockedAxisFree; } // Tell the object to clean up. public virtual void Destroy() { PhysicalActors.Enable(false); PhysScene.TaintedObject(LocalID, "BSPhysObject.Destroy", delegate() { PhysicalActors.Dispose(); }); } public BSScene PhysScene { get; protected set; } // public override uint LocalID { get; set; } // Use the LocalID definition in PhysicsActor public string PhysObjectName { get; protected set; } public string TypeName { get; protected set; } // Set to 'true' when the object is completely initialized. // This mostly prevents property updates and collisions until the object is completely here. public bool IsInitialized { get; protected set; } // Return the object mass without calculating it or having side effects public abstract float RawMass { get; } // Set the raw mass but also update physical mass properties (inertia, ...) // 'inWorld' true if the object has already been added to the dynamic world. public abstract void UpdatePhysicalMassProperties(float mass, bool inWorld); // The gravity being applied to the object. A function of default grav, GravityModifier and Buoyancy. public virtual OMV.Vector3 Gravity { get; set; } // The last value calculated for the prim's inertia public OMV.Vector3 Inertia { get; set; } // Reference to the physical body (btCollisionObject) of this object public BulletBody PhysBody; // Reference to the physical shape (btCollisionShape) of this object public BSShape PhysShape; // The physical representation of the prim might require an asset fetch. // The asset state is first 'Unknown' then 'Waiting' then either 'Failed' or 'Fetched'. public enum PrimAssetCondition { Unknown, Waiting, FailedAssetFetch, FailedMeshing, Fetched } public PrimAssetCondition PrimAssetState { get; set; } public virtual bool AssetFailed() { return ( (this.PrimAssetState == PrimAssetCondition.FailedAssetFetch) || (this.PrimAssetState == PrimAssetCondition.FailedMeshing) ); } // The objects base shape information. Null if not a prim type shape. public PrimitiveBaseShape BaseShape { get; protected set; } // When the physical properties are updated, an EntityProperty holds the update values. // Keep the current and last EntityProperties to enable computation of differences // between the current update and the previous values. public EntityProperties CurrentEntityProperties { get; set; } public EntityProperties LastEntityProperties { get; set; } public virtual OMV.Vector3 Scale { get; set; } // It can be confusing for an actor to know if it should move or update an object // depeneding on the setting of 'selected', 'physical, ... // This flag is the true test -- if true, the object is being acted on in the physical world public abstract bool IsPhysicallyActive { get; } // Detailed state of the object. public abstract bool IsSolid { get; } public abstract bool IsStatic { get; } public abstract bool IsSelected { get; } public abstract bool IsVolumeDetect { get; } // Materialness public MaterialAttributes.Material Material { get; private set; } public override void SetMaterial(int material) { Material = (MaterialAttributes.Material)material; // Setting the material sets the material attributes also. // TODO: decide if this is necessary -- the simulator does this. MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false); Friction = matAttrib.friction; Restitution = matAttrib.restitution; Density = matAttrib.density; // DetailLog("{0},{1}.SetMaterial,Mat={2},frict={3},rest={4},den={5}", LocalID, TypeName, Material, Friction, Restitution, Density); } public override float Density { get { return base.Density; } set { DetailLog("{0},BSPhysObject.Density,set,den={1}", LocalID, value); base.Density = value; } } // Stop all physical motion. public abstract void ZeroMotion(bool inTaintTime); public abstract void ZeroAngularMotion(bool inTaintTime); // Update the physical location and motion of the object. Called with data from Bullet. public abstract void UpdateProperties(EntityProperties entprop); public virtual OMV.Vector3 RawPosition { get; set; } public abstract OMV.Vector3 ForcePosition { get; set; } public virtual OMV.Quaternion RawOrientation { get; set; } public abstract OMV.Quaternion ForceOrientation { get; set; } public OMV.Vector3 RawVelocity { get; set; } public abstract OMV.Vector3 ForceVelocity { get; set; } public OMV.Vector3 RawForce { get; set; } public OMV.Vector3 RawTorque { get; set; } public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { AddAngularForce(force, pushforce, false); } public abstract void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime); public abstract void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime); public abstract OMV.Vector3 ForceRotationalVelocity { get; set; } public abstract float ForceBuoyancy { get; set; } public virtual bool ForceBodyShapeRebuild(bool inTaintTime) { return false; } public override bool PIDActive { get { return MoveToTargetActive; } set { MoveToTargetActive = value; } } public override OMV.Vector3 PIDTarget { set { MoveToTargetTarget = value; } } public override float PIDTau { set { MoveToTargetTau = value; } } public bool MoveToTargetActive { get; set; } public OMV.Vector3 MoveToTargetTarget { get; set; } public float MoveToTargetTau { get; set; } // Used for llSetHoverHeight and maybe vehicle height. Hover Height will override MoveTo target's Z public override bool PIDHoverActive { set { HoverActive = value; } } public override float PIDHoverHeight { set { HoverHeight = value; } } public override PIDHoverType PIDHoverType { set { HoverType = value; } } public override float PIDHoverTau { set { HoverTau = value; } } public bool HoverActive { get; set; } public float HoverHeight { get; set; } public PIDHoverType HoverType { get; set; } public float HoverTau { get; set; } // For RotLookAt public override OMV.Quaternion APIDTarget { set { return; } } public override bool APIDActive { set { return; } } public override float APIDStrength { set { return; } } public override float APIDDamping { set { return; } } // The current velocity forward public virtual float ForwardSpeed { get { OMV.Vector3 characterOrientedVelocity = RawVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation)); return characterOrientedVelocity.X; } } // The forward speed we are trying to achieve (TargetVelocity) public virtual float TargetVelocitySpeed { get { OMV.Vector3 characterOrientedVelocity = TargetVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation)); return characterOrientedVelocity.X; } } // The user can optionally set the center of mass. The user's setting will override any // computed center-of-mass (like in linksets). // Note this is a displacement from the root's coordinates. Zero means use the root prim as center-of-mass. public OMV.Vector3? UserSetCenterOfMassDisplacement { get; set; } public OMV.Vector3 LockedLinearAxis { get; set; } // zero means locked. one means free. public OMV.Vector3 LockedAngularAxis { get; set; } // zero means locked. one means free. public const float FreeAxis = 1f; public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(FreeAxis, FreeAxis, FreeAxis); // All axis are free // Enable physical actions. Bullet will keep sleeping non-moving physical objects so // they need waking up when parameters are changed. // Called in taint-time!! public void ActivateIfPhysical(bool forceIt) { if (PhysBody.HasPhysicalBody) { if (IsPhysical) { // Physical objects might need activating PhysScene.PE.Activate(PhysBody, forceIt); } else { // Clear the collision cache since we've changed some properties. PhysScene.PE.ClearCollisionProxyCache(PhysScene.World, PhysBody); } } } // 'actors' act on the physical object to change or constrain its motion. These can range from // hovering to complex vehicle motion. // May be called at non-taint time as this just adds the actor to the action list and the real // work is done during the simulation step. // Note that, if the actor is already in the list and we are disabling same, the actor is just left // in the list disabled. public delegate BSActor CreateActor(); public void EnableActor(bool enableActor, string actorName, CreateActor creator) { lock (PhysicalActors) { BSActor theActor; if (PhysicalActors.TryGetActor(actorName, out theActor)) { // The actor already exists so just turn it on or off DetailLog("{0},BSPhysObject.EnableActor,enablingExistingActor,name={1},enable={2}", LocalID, actorName, enableActor); theActor.Enabled = enableActor; } else { // The actor does not exist. If it should, create it. if (enableActor) { DetailLog("{0},BSPhysObject.EnableActor,creatingActor,name={1}", LocalID, actorName); theActor = creator(); PhysicalActors.Add(actorName, theActor); theActor.Enabled = true; } else { DetailLog("{0},BSPhysObject.EnableActor,notCreatingActorSinceNotEnabled,name={1}", LocalID, actorName); } } } } #region Collisions // Requested number of milliseconds between collision events. Zero means disabled. protected int SubscribedEventsMs { get; set; } // Given subscription, the time that a collision may be passed up protected int NextCollisionOkTime { get; set; } // The simulation step that last had a collision protected long CollidingStep { get; set; } // The simulation step that last had a collision with the ground protected long CollidingGroundStep { get; set; } // The simulation step that last collided with an object protected long CollidingObjectStep { get; set; } // The collision flags we think are set in Bullet protected CollisionFlags CurrentCollisionFlags { get; set; } // On a collision, check the collider and remember if the last collider was moving // Used to modify the standing of avatars (avatars on stationary things stand still) public bool ColliderIsMoving; // 'true' if the last collider was a volume detect object public bool ColliderIsVolumeDetect; // Used by BSCharacter to manage standing (and not slipping) public bool IsStationary; // Count of collisions for this object protected long CollisionAccumulation { get; set; } public override bool IsColliding { get { return (CollidingStep == PhysScene.SimulationStep); } set { if (value) CollidingStep = PhysScene.SimulationStep; else CollidingStep = BSScene.NotASimulationStep; } } // Complex objects (like linksets) need to know if there is a collision on any part of // their shape. 'IsColliding' has an existing definition of reporting a collision on // only this specific prim or component of linksets. // 'HasSomeCollision' is defined as reporting if there is a collision on any part of // the complex body that this prim is the root of. public virtual bool HasSomeCollision { get { return IsColliding; } set { IsColliding = value; } } public override bool CollidingGround { get { return (CollidingGroundStep == PhysScene.SimulationStep); } set { if (value) CollidingGroundStep = PhysScene.SimulationStep; else CollidingGroundStep = BSScene.NotASimulationStep; } } public override bool CollidingObj { get { return (CollidingObjectStep == PhysScene.SimulationStep); } set { if (value) CollidingObjectStep = PhysScene.SimulationStep; else CollidingObjectStep = BSScene.NotASimulationStep; } } // The collisions that have been collected for the next collision reporting (throttled by subscription) protected CollisionEventUpdate CollisionCollection; // This is the collision collection last reported to the Simulator. public CollisionEventUpdate CollisionsLastReported; // Remember the collisions recorded in the last tick for fancy collision checking // (like a BSCharacter walking up stairs). public CollisionEventUpdate CollisionsLastTick; private long CollisionsLastTickStep = -1; // The simulation step is telling this object about a collision. // Return 'true' if a collision was processed and should be sent up. // Return 'false' if this object is not enabled/subscribed/appropriate for or has already seen this collision. // Called at taint time from within the Step() function public delegate bool CollideCall(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); public virtual bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { bool ret = false; // The following lines make IsColliding(), CollidingGround() and CollidingObj work CollidingStep = PhysScene.SimulationStep; if (collidingWith <= PhysScene.TerrainManager.HighestTerrainID) { CollidingGroundStep = PhysScene.SimulationStep; } else { CollidingObjectStep = PhysScene.SimulationStep; } CollisionAccumulation++; // For movement tests, remember if we are colliding with an object that is moving. ColliderIsMoving = collidee != null ? (collidee.RawVelocity != OMV.Vector3.Zero) : false; ColliderIsVolumeDetect = collidee != null ? (collidee.IsVolumeDetect) : false; // Make a collection of the collisions that happened the last simulation tick. // This is different than the collection created for sending up to the simulator as it is cleared every tick. if (CollisionsLastTickStep != PhysScene.SimulationStep) { CollisionsLastTick = new CollisionEventUpdate(); CollisionsLastTickStep = PhysScene.SimulationStep; } CollisionsLastTick.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); // If someone has subscribed for collision events log the collision so it will be reported up if (SubscribedEvents()) { lock (PhysScene.CollisionLock) { CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); } DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5},colliderMoving={6}", LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth, ColliderIsMoving); ret = true; } return ret; } // Send the collected collisions into the simulator. // Called at taint time from within the Step() function thus no locking problems // with CollisionCollection and ObjectsWithNoMoreCollisions. // Called with BSScene.CollisionLock locked to protect the collision lists. // Return 'true' if there were some actual collisions passed up public virtual bool SendCollisions() { bool ret = true; // If no collisions this call but there were collisions last call, force the collision // event to be happen right now so quick collision_end. bool force = (CollisionCollection.Count == 0 && CollisionsLastReported.Count != 0); // throttle the collisions to the number of milliseconds specified in the subscription if (force || (PhysScene.SimulationNowTime >= NextCollisionOkTime)) { NextCollisionOkTime = PhysScene.SimulationNowTime + SubscribedEventsMs; // We are called if we previously had collisions. If there are no collisions // this time, send up one last empty event so OpenSim can sense collision end. if (CollisionCollection.Count == 0) { // If I have no collisions this time, remove me from the list of objects with collisions. ret = false; } DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count); base.SendCollisionUpdate(CollisionCollection); // Remember the collisions from this tick for some collision specific processing. CollisionsLastReported = CollisionCollection; // The CollisionCollection instance is passed around in the simulator. // Make sure we don't have a handle to that one and that a new one is used for next time. // This fixes an interesting 'gotcha'. If we call CollisionCollection.Clear() here, // a race condition is created for the other users of this instance. CollisionCollection = new CollisionEventUpdate(); } return ret; } // Subscribe for collision events. // Parameter is the millisecond rate the caller wishes collision events to occur. public override void SubscribeEvents(int ms) { // DetailLog("{0},{1}.SubscribeEvents,subscribing,ms={2}", LocalID, TypeName, ms); SubscribedEventsMs = ms; if (ms > 0) { // make sure first collision happens NextCollisionOkTime = Environment.TickCount - SubscribedEventsMs; PhysScene.TaintedObject(LocalID, TypeName+".SubscribeEvents", delegate() { if (PhysBody.HasPhysicalBody) CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } else { // Subscribing for zero or less is the same as unsubscribing UnSubscribeEvents(); } } public override void UnSubscribeEvents() { // DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName); SubscribedEventsMs = 0; PhysScene.TaintedObject(LocalID, TypeName+".UnSubscribeEvents", delegate() { // Make sure there is a body there because sometimes destruction happens in an un-ideal order. if (PhysBody.HasPhysicalBody) CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } // Return 'true' if the simulator wants collision events public override bool SubscribedEvents() { return (SubscribedEventsMs > 0); } // Because 'CollisionScore' is called many times while sorting, it should not be recomputed // each time called. So this is built to be light weight for each collision and to do // all the processing when the user asks for the info. public void ComputeCollisionScore() { // Scale the collision count by the time since the last collision. // The "+1" prevents dividing by zero. long timeAgo = PhysScene.SimulationStep - CollidingStep + 1; CollisionScore = CollisionAccumulation / timeAgo; } public override float CollisionScore { get; set; } #endregion // Collisions #region Per Simulation Step actions public BSActorCollection PhysicalActors; // When an update to the physical properties happens, this event is fired to let // different actors to modify the update before it is passed around public delegate void PreUpdatePropertyAction(ref EntityProperties entprop); public event PreUpdatePropertyAction OnPreUpdateProperty; protected void TriggerPreUpdatePropertyAction(ref EntityProperties entprop) { PreUpdatePropertyAction actions = OnPreUpdateProperty; if (actions != null) actions(ref entprop); } #endregion // Per Simulation Step actions // High performance detailed logging routine used by the physical objects. protected void DetailLog(string msg, params Object[] args) { if (PhysScene.PhysicsLogging.Enabled) PhysScene.DetailLog(msg, args); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Gravity2D { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Camera2d _camera = new Camera2d(); int _bulletTimer = 0; // Data double stationHealth = 100; double stationRepair = 100; int maxScrollH = 8192; int maxScrollV = 8192; int[] resources = { 0, 0, 0 }; float score; int livesLeft = 3; // State GameState _gameState; MouseState _mouseStatePrevious; KeyboardState _keyboardStatePrevious; Vector2 _screenPosition; double respawnTimer = 0; // Resources Texture2D _circle; Texture2D _fourpx; Texture2D _square; Texture2D _rocket; Texture2D _starfield; Texture2D _needle; Texture2D _stationTexture; Texture2D _theFuckingMoon; Texture2D _menuBackground; Texture2D _playUp; Texture2D _playDown; Texture2D _exitUp; Texture2D _exitDown; SoundEffect _kerchingSE; SoundEffect _explosionSE; SoundEffect _whipSE; SoundEffect _laserSE; SpriteFont _spriteFont; // Instances Player _player; SpaceStation _station; List<MassiveObject> _objects; List<Planet> _planets; List<Bullet> _projectiles; Random _generator; public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; Content.RootDirectory = "Content"; TargetElapsedTime = TimeSpan.FromMilliseconds(17); IsMouseVisible = true; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here _gameState = GameState.MENU; _objects = new List<MassiveObject>(); _planets = new List<Planet>(); _projectiles = new List<Bullet>(); _mouseStatePrevious = Mouse.GetState(); _keyboardStatePrevious = Keyboard.GetState(); _generator = new Random(); //objects.Add(new MassiveObject(new Vector2(899.807621f, 500.0f), new Vector2(0.5f, -0.866025f))); //objects.Add(new MassiveObject(new Vector2(50, 50), Vector2.Zero, 1)); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); _circle = Content.Load<Texture2D>("circle"); _fourpx = Content.Load<Texture2D>("fourpx"); _square = Content.Load<Texture2D>("square"); _rocket = Content.Load<Texture2D>("rocket"); _starfield = Content.Load<Texture2D>("starfield"); _needle = Content.Load<Texture2D>("needle"); _stationTexture = Content.Load<Texture2D>("deathstar"); _theFuckingMoon = Content.Load<Texture2D>("moon"); _menuBackground = Content.Load<Texture2D>("menuBackground"); _playUp = Content.Load<Texture2D>("playUp"); _playDown = Content.Load<Texture2D>("playDown"); _exitUp = Content.Load<Texture2D>("exitUp"); _exitDown = Content.Load<Texture2D>("exitDown"); _kerchingSE = Content.Load<SoundEffect>("kerching"); _explosionSE = Content.Load<SoundEffect>("explosion"); _whipSE = Content.Load<SoundEffect>("whip"); _laserSE = Content.Load<SoundEffect>("laser"); _spriteFont = Content.Load<SpriteFont>("SpriteFont1"); _screenPosition = Vector2.Zero; // Post load init /*objects.Add(new PointMass(_circle, new Vector2(640, 50), Vector2.Zero, 50, 100)); objects.Add(new PointMass(_circle, new Vector2(1100, 300), Vector2.Zero, 50, 100)); objects.Add(new PointMass(_circle, new Vector2(380.192379f, 500.0f), Vector2.Zero, 25, 50));*/ _player = new Player(_rocket); _station = new SpaceStation(_stationTexture); _objects.Add(_player); _objects.Add(_station); _objects.Add((MassiveObject)new DynamicMass(_circle, new Vector2(400, 350), new Vector2(0f, 10.0f), 10, 50)); //objects.Add((PointMass)new DynamicMass(_circle, new Vector2(890, 350), new Vector2(0f, -10.0f), 100, 25)); // TODO: use this.Content to load your game content here } Planet createPlanet() { const int max = 8192; Resources resource = Resources.None; int randomInt = _generator.Next(16); if (randomInt < 8) resource = Resources.Hydrogen; else if (randomInt < 14) resource = Resources.Iron; else resource = Resources.Unobtanium; Vector2 position = new Vector2(_generator.Next(max) - max / 2, _generator.Next(max) - max / 2); while ((_player.Position - position).LengthSquared() < 1000000) { position = new Vector2(_generator.Next(max) - max / 2, _generator.Next(max) - max / 2); } int mass = _generator.Next(5, 20); int radius = mass * 5; Planet planet = new Planet(resource, _theFuckingMoon, position, new Vector2(_generator.Next(0, 15), _generator.Next(0, 15)), mass, radius); return planet; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (!Keyboard.GetState().IsKeyDown(Keys.Escape) && _keyboardStatePrevious.IsKeyDown(Keys.Escape)) { if (_gameState == GameState.MENU) this.Exit(); else _gameState = GameState.MENU; } switch (_gameState) { case GameState.MENU: if (Mouse.GetState().LeftButton == ButtonState.Released && _mouseStatePrevious.LeftButton == ButtonState.Pressed) { if (_mouseStatePrevious.X > 521 && _mouseStatePrevious.Y > 321 && _mouseStatePrevious.X < 618 && _mouseStatePrevious.Y < 370) { _planets.Clear(); _objects.Clear(); _projectiles.Clear(); _player = new Player(_rocket); stationHealth = 100; stationRepair = 100; resources[0] = 0; resources[1] = 0; resources[2] = 0; respawnTimer = 0; _station = new SpaceStation(_stationTexture); _objects.Add(_player); _objects.Add(_station); livesLeft = 3; score = 0; _gameState = GameState.PLAY; } else if (_mouseStatePrevious.X > 523 && _mouseStatePrevious.Y > 371 && _mouseStatePrevious.X < 614 && _mouseStatePrevious.Y < 418) { this.Exit(); } } break; case GameState.PLAY: UpdateGame(gameTime); break; case GameState.GAMEOVER: if (Keyboard.GetState().IsKeyDown(Keys.Enter)) _gameState = GameState.MENU; break; default: this.Exit(); break; } // TODO: Add your update logic here _mouseStatePrevious = Mouse.GetState(); _keyboardStatePrevious = Keyboard.GetState(); base.Update(gameTime); } protected void UpdateGame(GameTime gameTime) { if (stationHealth <= 0) { _gameState = GameState.GAMEOVER; } if (_player.Dead) { if (livesLeft <= 0) { _gameState = GameState.GAMEOVER; } if (respawnTimer < 0) { respawnTimer = 0; _player.Position = Vector2.Zero; _player.Velocity = Vector2.Zero; resources[0] = 0; resources[1] = 0; resources[2] = 0; _player.Dead = false; } else { respawnTimer -= gameTime.ElapsedGameTime.TotalMilliseconds; } } _bulletTimer += (int)gameTime.ElapsedGameTime.TotalMilliseconds; while (_planets.Count < 100) { Planet planet = createPlanet(); _objects.Add(planet); _planets.Add(planet); } Vector2 playerDirection = new Vector2((float)(Math.Cos(_player.Rotation)), (float)(Math.Sin(_player.Rotation))); for (int i = 0; i < _objects.Count; i++) { for (int j = 0; j < _objects.Count; j++) { if (i != j) { if (_objects[i] is SpaceStation) { if (_objects[j] == _player && !_player.Dead) { if (_objects[i].BoundingSphere.Intersects(_objects[j].BoundingSphere)) { if (resources[0] > 0 || resources[1] > 0 || resources[2] > 0) { _kerchingSE.Play(); score += resources[0] * 500 + resources[1] * 200 + resources[2] * 100; stationHealth += resources[0] + (0.5 * resources[1]); stationRepair += resources[2]; _station.Resources[0] += resources[0]; _station.Resources[1] += resources[1]; _station.Resources[2] += resources[2]; resources[0] = 0; resources[1] = 0; resources[2] = 0; } } } else if (_objects[j] is Planet && _objects[i].BoundingSphere.Intersects(_objects[j].BoundingSphere)) { _objects[j].Dead = true; double damage = ((Planet)_objects[j]).Velocity.Length(); if (stationRepair > 0) { damage /= 2; stationRepair -= damage; } if (stationRepair < 0) { stationHealth -= stationRepair; stationRepair = 0; } stationHealth -= damage; } } if (_objects[i] is DynamicMass) { if (_objects[i] == _player && _objects[j] is Planet && !_player.Dead) { if ((_objects[i] == _player || _objects[j] == _player) && _player.Dead) continue; if (((Planet)_objects[j]).Resource != Resources.None) { if ((_player.Position - _objects[j].Position).LengthSquared() < 10000 + (_objects[j].Radius * _objects[j].Radius)) { switch (((Planet)_objects[j]).Resource) { case Resources.Unobtanium: resources[0] += (int)((Planet)_objects[j]).Radius; break; case Resources.Iron: resources[1] += (int)((Planet)_objects[j]).Radius; break; case Resources.Hydrogen: resources[2] += (int)((Planet)_objects[j]).Radius; break; } ((Planet)_objects[j]).SetResource(Resources.None); _whipSE.Play(); } } } MassiveObject planet = _objects[i]; MassiveObject other = _objects[j]; if (planet.BoundingSphere.Intersects(other.BoundingSphere)) { if (other is DynamicMass && !(planet is Bullet)) { if (planet != _player && other != _player) { //for (int k = 0; k < _projectiles.Count; k++) //{ // Bullet bullet = _projectiles[k]; // if (_objects[i].BoundingSphere.Intersects(bullet.BoundingSphere)) // { // _objects[i].Radius *= 0.5f; // } //} if (!(other is Bullet)) { if (_generator.NextDouble() < 0.5) { other.Dead = true; planet.Mass += other.Mass; planet.Radius += (float)Math.Sqrt(other.Radius); ((DynamicMass)planet).Velocity += ((DynamicMass)other).Velocity; if (planet.Mass > 500) planet.Mass = 500; if (planet.Radius > 100) planet.Radius = 100; } else { planet.Dead = true; other.Dead = true; } } else if (other is Bullet) { ((Planet)planet).Velocity = ((Bullet)other).Velocity; other.Dead = true; } } else if (!_player.Dead) { _explosionSE.Play(); _player.Dead = true; livesLeft--; respawnTimer = 3000; continue; } } } else { double distanceSquared = (_objects[i].Position - _objects[j].Position).LengthSquared(); double accelerationMagnitude = (250 * _objects[j].Mass) / (distanceSquared != 0 ? distanceSquared : 1); double direction = Math.Atan2(_objects[j].Position.X - _objects[i].Position.X, _objects[j].Position.Y - _objects[i].Position.Y); ((DynamicMass)_objects[i]).Velocity += new Vector2((float)(Math.Sin(direction) * accelerationMagnitude), (float)(Math.Cos(direction) * accelerationMagnitude)); } } } } if (!_player.Dead) { if (Keyboard.GetState().IsKeyDown(Keys.Space)) { if (_bulletTimer > 800) { _laserSE.Play(); Bullet bullet = new Bullet(_player, _circle, _player.Position + (playerDirection * 30.0f), Vector2.Normalize(playerDirection) * 15.0f, 0.1, 3); _objects.Add(bullet); _projectiles.Add(bullet); _bulletTimer = 0; } } if (Keyboard.GetState().IsKeyDown(Keys.Up)) { _player.Velocity += playerDirection * 0.005f * (float)(gameTime.ElapsedGameTime.TotalMilliseconds / 17); } if (Keyboard.GetState().IsKeyDown(Keys.Down)) { _player.Velocity -= playerDirection * 0.005f * (float)(gameTime.ElapsedGameTime.TotalMilliseconds / 17); } if (Keyboard.GetState().IsKeyDown(Keys.Left)) { _player.Rotation -= 0.0005f * (float)(gameTime.ElapsedGameTime.TotalMilliseconds / 17); } if (Keyboard.GetState().IsKeyDown(Keys.Right)) { _player.Rotation += 0.0005f * (float)(gameTime.ElapsedGameTime.TotalMilliseconds / 17); } } if (i >= 0 && i < _objects.Count) { if (_objects[i] is DynamicMass) { if (((DynamicMass)_objects[i]).Velocity.LengthSquared() > 100) { ((DynamicMass)_objects[i]).Velocity = Vector2.Normalize(((DynamicMass)_objects[i]).Velocity) * 10.0f; } ((DynamicMass)_objects[i]).Update(gameTime); } } } foreach (Bullet bullet in _projectiles) { bullet.Update(gameTime); } // Remove dead objects and make living objects wrap around for (int i = 0; i < _objects.Count; i++) { MassiveObject currentObject = _objects[i]; if (currentObject.Dead) { if (currentObject != _player) { _objects.Remove(currentObject); if (currentObject is DynamicMass) { if (currentObject is Planet) _planets.Remove((Planet)currentObject); if (currentObject is Bullet) _projectiles.Remove((Bullet)currentObject); } } } else if (currentObject.X > (maxScrollH / 2)) { currentObject.X -= maxScrollH; } else if (currentObject.X < -(maxScrollH / 2)) { currentObject.X += maxScrollH; } else if (currentObject.Y > (maxScrollV / 2)) { currentObject.Y -= maxScrollH; } else if (currentObject.Y < -(maxScrollV / 2)) { currentObject.Y += maxScrollH; } } //if (Keyboard.GetState().IsKeyDown(Keys.Left)) // _camera.Rotation -= 0.01f; //else if (Keyboard.GetState().IsKeyDown(Keys.Right)) // _camera.Rotation += 0.01f; if (_objects.Count > 0) _camera.Position = _player.Position; } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); // TODO: Add your drawing code here spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, _camera.get_transformation(GraphicsDevice)); { switch (_gameState) { case GameState.MENU: _camera.Position = new Vector2(640, 360); DrawMenu(gameTime); break; case GameState.PLAY: DrawGame(gameTime); break; case GameState.GAMEOVER: _camera.Position = new Vector2(640, 360); spriteBatch.DrawString(_spriteFont, "YOU LOSE. Only got a score of " + score + "? Pitiful.", new Vector2(350, 360), Color.White); spriteBatch.DrawString(_spriteFont, "Press return to continue.", new Vector2(350, 400), Color.White); break; default: this.Exit(); break; } } spriteBatch.End(); base.Draw(gameTime); } public void DrawMenu(GameTime gameTime) { spriteBatch.Draw(_menuBackground, Vector2.Zero, null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1); spriteBatch.Draw((_mouseStatePrevious.X > 521 && _mouseStatePrevious.Y > 321 && _mouseStatePrevious.X < 618 && _mouseStatePrevious.Y < 370 && _mouseStatePrevious.LeftButton != ButtonState.Pressed ? _playDown : _playUp), Vector2.Zero, null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0); spriteBatch.Draw((_mouseStatePrevious.X > 523 && _mouseStatePrevious.Y > 371 && _mouseStatePrevious.X < 614 && _mouseStatePrevious.Y < 418 && _mouseStatePrevious.LeftButton != ButtonState.Pressed ? _exitDown : _exitUp), Vector2.Zero, null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0); } public void DrawGame(GameTime gameTime) { // Draw starfields for (float y = (_camera.Position.Y * 1.0f) - graphics.PreferredBackBufferHeight - 512; y < (_camera.Position.Y * 1.0f) + graphics.PreferredBackBufferHeight + 512; y += 256) { for (float x = _camera.Position.X - graphics.PreferredBackBufferWidth - 512; x < _camera.Position.X + graphics.PreferredBackBufferWidth + 512; x += 256) { spriteBatch.Draw(_starfield, new Vector2(((int)x / 256) * 256.0f, ((int)y / 256) * 256.0f), null, Color.White, 0, Vector2.Zero, Vector2.One, SpriteEffects.None, 100000); } } //foreach (Star star in _starFieldLayer1) //{ // star.Draw(gameTime, spriteBatch, 1.5f); //} // spriteBatch.DrawString(_spriteFont, Mouse.GetState().X.ToString() + ", " + Mouse.GetState().Y.ToString(), Vector2.Transform(new Vector2(-Mouse.GetState().X, -Mouse.GetState().Y), -_camera.get_transformation(GraphicsDevice)), Color.White); foreach (MassiveObject planet in _objects) { if (planet is Player) { if (_player.Dead) continue; //spriteBatch.DrawString(_spriteFont, planet.Velocity.Length().ToString(), planet.Position, Color.Red); } if (planet is Planet) ((Planet)planet).Draw(gameTime, spriteBatch, _camera.Position, maxScrollH, maxScrollV, 50); } foreach (Bullet bullet in _projectiles) { bullet.Draw(gameTime, spriteBatch, _camera.Position, maxScrollH, maxScrollV); } if (!_player.Dead) _player.Draw(gameTime, spriteBatch, _camera.Position, maxScrollH, maxScrollV); _station.Draw(gameTime, spriteBatch, _camera.Position, maxScrollH, maxScrollV); //if (_startPosition != Vector2.Zero) // DrawLine(spriteBatch, _fourpx, _startPosition, new Vector2(Mouse.GetState().X, Mouse.GetState().Y), Color.White); //spriteBatch.DrawString(_spriteFont, "(" + _player.X.ToString() + ", " + _player.Y.ToString() + ")", _player.Position, Color.Red); spriteBatch.DrawString(_spriteFont, "Station Health: " + (int)stationHealth, _camera.Position - new Vector2(620, 160), Color.Red); spriteBatch.DrawString(_spriteFont, "Station Energy: " + (int)stationRepair, _camera.Position - new Vector2(620, 140), Color.Red); // Draw HUD spriteBatch.Draw(_needle, _camera.Position - new Vector2((graphics.PreferredBackBufferWidth / 2) - 100, (graphics.PreferredBackBufferHeight / 2) - 100), null, Color.White, -(float)Math.Atan2(_camera.Position.X, _camera.Position.Y), new Vector2(50, 50), 1.0f, SpriteEffects.None, -500); spriteBatch.DrawString(_spriteFont, "Unobtanium: " + resources[0], _camera.Position + new Vector2(380, -320), Color.Red); spriteBatch.DrawString(_spriteFont, "Iron: " + resources[1], _camera.Position + new Vector2(400, -300), Color.Red); spriteBatch.DrawString(_spriteFont, "Hydrogen: " + resources[2], _camera.Position + new Vector2(420, -280), Color.Red); spriteBatch.DrawString(_spriteFont, "Score: " + score, _camera.Position + new Vector2(380, -240), Color.Red); for (int i = 0; i < livesLeft; i++) { spriteBatch.Draw(_rocket, _camera.Position - new Vector2(580 - i * 40, 0), null, Color.White, -MathHelper.PiOver2, Vector2.Zero, 1.4f, SpriteEffects.None, -300); } if (_station.BoundingSphere.Intersects(_player.BoundingSphere)) { //spriteBatch.DrawString(_spriteFont, "Press return to begin docking procedure", _camera.Position + new Vector2(-220, 50), Color.Red); } if (respawnTimer > 0) { spriteBatch.DrawString(_spriteFont, "Deploying new ship in " + (int)(respawnTimer / 1000 + 0.5), _camera.Position - new Vector2(300, 0), Color.White); } } public void DrawLine(SpriteBatch spriteBatch, Texture2D spr, Vector2 a, Vector2 b, Color col) { Vector2 Origin = new Vector2(0.5f, 0.0f); Vector2 diff = b - a; float angle; Vector2 Scale = new Vector2(1.0f, diff.Length() / spr.Height); angle = (float)(Math.Atan2(diff.Y, diff.X)) - MathHelper.PiOver2; spriteBatch.Draw(spr, a, null, col, angle, Origin, Scale, SpriteEffects.None, 1.0f); } } enum GameState { MENU, PLAY, GAMEOVER, PAUSE } }
// Copyright (c) 2012 DotNetAnywhere // // 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.Runtime.CompilerServices; #if LOCALTEST using System; namespace System_ { #else namespace System { #endif public static class Math { public const double E = 2.7182818284590452354; public const double PI = 3.14159265358979323846; #region Abs() public static sbyte Abs(sbyte v) { if (v == sbyte.MinValue) { throw new OverflowException("Value is too small"); } return (v >= 0) ? v : (sbyte)-v; } public static short Abs(short v) { if (v == short.MinValue) { throw new OverflowException("Value is too small"); } return (v >= 0) ? v : (short)-v; } public static int Abs(int v) { if (v == int.MinValue) { throw new OverflowException("Value is too small"); } return (v >= 0) ? v : -v; } public static long Abs(long v) { if (v == long.MinValue) { throw new OverflowException("Value is too small"); } return (v >= 0) ? v : -v; } public static float Abs(float v) { return (v >= 0) ? v : -v; } public static double Abs(double v) { return (v >= 0) ? v : -v; } #endregion #region Min() public static sbyte Min(sbyte v1, sbyte v2) { return (v1 < v2) ? v1 : v2; } public static short Min(short v1, short v2) { return (v1 < v2) ? v1 : v2; } public static int Min(int v1, int v2) { return (v1 < v2) ? v1 : v2; } public static long Min(long v1, long v2) { return (v1 < v2) ? v1 : v2; } public static byte Min(byte v1, byte v2) { return (v1 < v2) ? v1 : v2; } public static ushort Min(ushort v1, ushort v2) { return (v1 < v2) ? v1 : v2; } public static uint Min(uint v1, uint v2) { return (v1 < v2) ? v1 : v2; } public static ulong Min(ulong v1, ulong v2) { return (v1 < v2) ? v1 : v2; } public static float Min(float v1, float v2) { if (float.IsNaN(v1) || float.IsNaN(v2)) { return float.NaN; } return (v1 < v2) ? v1 : v2; } public static double Min(double v1, double v2) { if (double.IsNaN(v1) || double.IsNaN(v2)) { return double.NaN; } return (v1 < v2) ? v1 : v2; } #endregion #region Max() public static sbyte Max(sbyte v1, sbyte v2) { return (v1 > v2) ? v1 : v2; } public static short Max(short v1, short v2) { return (v1 > v2) ? v1 : v2; } public static int Max(int v1, int v2) { return (v1 > v2) ? v1 : v2; } public static long Max(long v1, long v2) { return (v1 > v2) ? v1 : v2; } public static byte Max(byte v1, byte v2) { return (v1 > v2) ? v1 : v2; } public static ushort Max(ushort v1, ushort v2) { return (v1 > v2) ? v1 : v2; } public static uint Max(uint v1, uint v2) { return (v1 > v2) ? v1 : v2; } public static ulong Max(ulong v1, ulong v2) { return (v1 > v2) ? v1 : v2; } public static float Max(float v1, float v2) { if (float.IsNaN(v1) || float.IsNaN(v2)) { return float.NaN; } return (v1 > v2) ? v1 : v2; } public static double Max(double v1, double v2) { if (double.IsNaN(v1) || double.IsNaN(v2)) { return double.NaN; } return (v1 > v2) ? v1 : v2; } #endregion #region Sign() public static int Sign(sbyte v) { return (v > 0) ? 1 : ((v < 0) ? -1 : 0); } public static int Sign(short v) { return (v > 0) ? 1 : ((v < 0) ? -1 : 0); } public static int Sign(int v) { return (v > 0) ? 1 : ((v < 0) ? -1 : 0); } public static int Sign(long v) { return (v > 0) ? 1 : ((v < 0) ? -1 : 0); } public static int Sign(float v) { if (float.IsNaN(v)) { throw new ArithmeticException("NaN"); } return (v > 0) ? 1 : ((v < 0) ? -1 : 0); } public static int Sign(double v) { if (double.IsNaN(v)) { throw new ArithmeticException("NaN"); } return (v > 0) ? 1 : ((v < 0) ? -1 : 0); } #endregion [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static double Sin(double x); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static double Cos(double x); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static double Tan(double x); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static double Pow(double x, double y); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static double Sqrt(double x); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Ceiling(double a); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Floor(double d); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Round(double d); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // The older-style CustomAttribute-related members on the various Reflection types. The implementation dependency // stack on .Net Native differs from that of CoreClr due to the difference in development history. // // - IEnumerable<CustomAttributeData> xInfo.get_CustomAttributes is at the very bottom of the dependency stack. // // - CustomAttributeExtensions layers on top of that (primarily because it's the one with the nice generic methods.) // // - Everything else is a thin layer over one of these two. // // using System; using System.IO; using System.Reflection; using System.Collections.Generic; using System.Reflection.Runtime.General; using Internal.LowLevelLinq; using Internal.Reflection.Extensions.NonPortable; namespace System.Reflection.Runtime.Assemblies { internal partial class RuntimeAssembly { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this).ToArray(); // inherit is meaningless for Assemblies public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, skipTypeValidation: true); // inherit is meaningless for Assemblies return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, skipTypeValidation: true); // inherit is meaningless for Assemblies return cads.Any(); } } } namespace System.Reflection.Runtime.MethodInfos { internal abstract partial class RuntimeConstructorInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit).ToArray(); public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.Any(); } } } namespace System.Reflection.Runtime.EventInfos { internal abstract partial class RuntimeEventInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit: false).ToArray(); // Desktop compat: for events, this form of the api ignores "inherit" public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for events, this form of the api ignores "inherit" return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for events, this form of the api ignores "inherit" return cads.Any(); } } } namespace System.Reflection.Runtime.FieldInfos { internal abstract partial class RuntimeFieldInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit).ToArray(); public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.Any(); } } } namespace System.Reflection.Runtime.MethodInfos { internal abstract partial class RuntimeMethodInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit).ToArray(); public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.Any(); } } } namespace System.Reflection.Runtime.Modules { internal sealed partial class RuntimeModule { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this).ToArray(); // inherit is meaningless for Modules public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, skipTypeValidation: true); // inherit is meaningless for Modules return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, skipTypeValidation: true); // inherit is meaningless for Modules return cads.Any(); } } } namespace System.Reflection.Runtime.ParameterInfos { internal abstract partial class RuntimeParameterInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit: false).ToArray(); // Desktop compat: for parameters, this form of the api ignores "inherit" public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for parameters, this form of the api ignores "inherit" return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for parameters, this form of the api ignores "inherit" return cads.Any(); } } } namespace System.Reflection.Runtime.PropertyInfos { internal abstract partial class RuntimePropertyInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit: false).ToArray(); // Desktop compat: for properties, this form of the api ignores "inherit" public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for properties, this form of the api ignores "inherit" return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: false, skipTypeValidation: true); // Desktop compat: for properties, this form of the api ignores "inherit" return cads.Any(); } } } namespace System.Reflection.Runtime.TypeInfos { internal abstract partial class RuntimeTypeInfo { public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection(); public sealed override object[] GetCustomAttributes(bool inherit) => CustomAttributeExtensions.GetCustomAttributes(this, inherit).ToArray(); public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.InstantiateAsArray(attributeType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); IEnumerable<CustomAttributeData> cads = this.GetMatchingCustomAttributes(attributeType, inherit: inherit, skipTypeValidation: true); return cads.Any(); } } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 2.3.1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IDeedApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param> /// <returns>OperativeDeed</returns> OperativeDeed DeedDeedReferenceGet (string deedReference, string accept); /// <summary> /// Deed /// </summary> /// <remarks> /// The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param> /// <returns>ApiResponse of OperativeDeed</returns> ApiResponse<OperativeDeed> DeedDeedReferenceGetWithHttpInfo (string deedReference, string accept); /// <summary> /// Modify Deed /// </summary> /// <remarks> /// The Modify Deed endpoint modifies a deed based on the unique deed reference provided in the path. The response will give the relative path to access the deed via the \&quot;Get\&quot; endpoint if an update is successful. Any modifications which arent aren&#39;t successful will show the relevant error messages. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="body"></param> /// <returns>string</returns> string DeedDeedReferencePut (string deedReference, DeedApplication body); /// <summary> /// Modify Deed /// </summary> /// <remarks> /// The Modify Deed endpoint modifies a deed based on the unique deed reference provided in the path. The response will give the relative path to access the deed via the \&quot;Get\&quot; endpoint if an update is successful. Any modifications which arent aren&#39;t successful will show the relevant error messages. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> ApiResponse<string> DeedDeedReferencePutWithHttpInfo (string deedReference, DeedApplication body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param> /// <returns>Task of OperativeDeed</returns> System.Threading.Tasks.Task<OperativeDeed> DeedDeedReferenceGetAsync (string deedReference, string accept); /// <summary> /// Deed /// </summary> /// <remarks> /// The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param> /// <returns>Task of ApiResponse (OperativeDeed)</returns> System.Threading.Tasks.Task<ApiResponse<OperativeDeed>> DeedDeedReferenceGetAsyncWithHttpInfo (string deedReference, string accept); /// <summary> /// Modify Deed /// </summary> /// <remarks> /// The Modify Deed endpoint modifies a deed based on the unique deed reference provided in the path. The response will give the relative path to access the deed via the \&quot;Get\&quot; endpoint if an update is successful. Any modifications which arent aren&#39;t successful will show the relevant error messages. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="body"></param> /// <returns>Task of string</returns> System.Threading.Tasks.Task<string> DeedDeedReferencePutAsync (string deedReference, DeedApplication body); /// <summary> /// Modify Deed /// </summary> /// <remarks> /// The Modify Deed endpoint modifies a deed based on the unique deed reference provided in the path. The response will give the relative path to access the deed via the \&quot;Get\&quot; endpoint if an update is successful. Any modifications which arent aren&#39;t successful will show the relevant error messages. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> System.Threading.Tasks.Task<ApiResponse<string>> DeedDeedReferencePutAsyncWithHttpInfo (string deedReference, DeedApplication body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class DeedApi : IDeedApi { private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="DeedApi"/> class. /// </summary> /// <returns></returns> public DeedApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="DeedApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public DeedApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Swagger.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Deed The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param> /// <returns>OperativeDeed</returns> public OperativeDeed DeedDeedReferenceGet (string deedReference, string accept) { ApiResponse<OperativeDeed> localVarResponse = DeedDeedReferenceGetWithHttpInfo(deedReference, accept); return localVarResponse.Data; } /// <summary> /// Deed The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param> /// <returns>ApiResponse of OperativeDeed</returns> public ApiResponse< OperativeDeed > DeedDeedReferenceGetWithHttpInfo (string deedReference, string accept) { // verify the required parameter 'deedReference' is set if (deedReference == null) throw new ApiException(400, "Missing required parameter 'deedReference' when calling DeedApi->DeedDeedReferenceGet"); // verify the required parameter 'accept' is set if (accept == null) throw new ApiException(400, "Missing required parameter 'accept' when calling DeedApi->DeedDeedReferenceGet"); var localVarPath = "/deed/{deed_reference}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/pdf" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (deedReference != null) localVarPathParams.Add("deed_reference", Configuration.ApiClient.ParameterToString(deedReference)); // path parameter // This header has already been added on line 294 and causes an API exception to occur if left in. //if (accept != null) localVarHeaderParams.Add("Accept", Configuration.ApiClient.ParameterToString(accept)); // header parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeedDeedReferenceGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OperativeDeed>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OperativeDeed) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperativeDeed))); } /// <summary> /// Deed The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param> /// <returns>Task of OperativeDeed</returns> public async System.Threading.Tasks.Task<OperativeDeed> DeedDeedReferenceGetAsync (string deedReference, string accept) { ApiResponse<OperativeDeed> localVarResponse = await DeedDeedReferenceGetAsyncWithHttpInfo(deedReference, accept); return localVarResponse.Data; } /// <summary> /// Deed The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param> /// <returns>Task of ApiResponse (OperativeDeed)</returns> public async System.Threading.Tasks.Task<ApiResponse<OperativeDeed>> DeedDeedReferenceGetAsyncWithHttpInfo (string deedReference, string accept) { // verify the required parameter 'deedReference' is set if (deedReference == null) throw new ApiException(400, "Missing required parameter 'deedReference' when calling DeedApi->DeedDeedReferenceGet"); // verify the required parameter 'accept' is set if (accept == null) throw new ApiException(400, "Missing required parameter 'accept' when calling DeedApi->DeedDeedReferenceGet"); var localVarPath = "/deed/{deed_reference}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/pdf" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (deedReference != null) localVarPathParams.Add("deed_reference", Configuration.ApiClient.ParameterToString(deedReference)); // path parameter if (accept != null) localVarHeaderParams.Add("Accept", Configuration.ApiClient.ParameterToString(accept)); // header parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeedDeedReferenceGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<OperativeDeed>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (OperativeDeed) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperativeDeed))); } /// <summary> /// Modify Deed The Modify Deed endpoint modifies a deed based on the unique deed reference provided in the path. The response will give the relative path to access the deed via the \&quot;Get\&quot; endpoint if an update is successful. Any modifications which arent aren&#39;t successful will show the relevant error messages. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="body"></param> /// <returns>string</returns> public string DeedDeedReferencePut (string deedReference, DeedApplication body) { ApiResponse<string> localVarResponse = DeedDeedReferencePutWithHttpInfo(deedReference, body); return localVarResponse.Data; } /// <summary> /// Modify Deed The Modify Deed endpoint modifies a deed based on the unique deed reference provided in the path. The response will give the relative path to access the deed via the \&quot;Get\&quot; endpoint if an update is successful. Any modifications which arent aren&#39;t successful will show the relevant error messages. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> public ApiResponse< string > DeedDeedReferencePutWithHttpInfo (string deedReference, DeedApplication body) { // verify the required parameter 'deedReference' is set if (deedReference == null) throw new ApiException(400, "Missing required parameter 'deedReference' when calling DeedApi->DeedDeedReferencePut"); // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling DeedApi->DeedDeedReferencePut"); var localVarPath = "/deed/{deed_reference}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (deedReference != null) localVarPathParams.Add("deed_reference", Configuration.ApiClient.ParameterToString(deedReference)); // path parameter if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeedDeedReferencePut", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } /// <summary> /// Modify Deed The Modify Deed endpoint modifies a deed based on the unique deed reference provided in the path. The response will give the relative path to access the deed via the \&quot;Get\&quot; endpoint if an update is successful. Any modifications which arent aren&#39;t successful will show the relevant error messages. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="body"></param> /// <returns>Task of string</returns> public async System.Threading.Tasks.Task<string> DeedDeedReferencePutAsync (string deedReference, DeedApplication body) { ApiResponse<string> localVarResponse = await DeedDeedReferencePutAsyncWithHttpInfo(deedReference, body); return localVarResponse.Data; } /// <summary> /// Modify Deed The Modify Deed endpoint modifies a deed based on the unique deed reference provided in the path. The response will give the relative path to access the deed via the \&quot;Get\&quot; endpoint if an update is successful. Any modifications which arent aren&#39;t successful will show the relevant error messages. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="deedReference">Unique reference of the deed.</param> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> public async System.Threading.Tasks.Task<ApiResponse<string>> DeedDeedReferencePutAsyncWithHttpInfo (string deedReference, DeedApplication body) { // verify the required parameter 'deedReference' is set if (deedReference == null) throw new ApiException(400, "Missing required parameter 'deedReference' when calling DeedApi->DeedDeedReferencePut"); // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling DeedApi->DeedDeedReferencePut"); var localVarPath = "/deed/{deed_reference}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (deedReference != null) localVarPathParams.Add("deed_reference", Configuration.ApiClient.ParameterToString(deedReference)); // path parameter if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeedDeedReferencePut", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } } }
/* * 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.Reflection; using System.Text; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.Framework.Scenes { #region Delegates public delegate uint GenerateClientFlagsHandler(UUID userID, UUID objectID); public delegate void SetBypassPermissionsHandler(bool value); public delegate bool BypassPermissionsHandler(); public delegate bool PropagatePermissionsHandler(); public delegate bool RezObjectHandler(int objectCount, UUID owner, Vector3 objectPosition, Scene scene); public delegate bool DeleteObjectHandler(UUID objectID, UUID deleter, Scene scene); public delegate bool TransferObjectHandler(UUID objectID, UUID recipient, Scene scene); public delegate bool TakeObjectHandler(UUID objectID, UUID stealer, Scene scene); public delegate bool TakeCopyObjectHandler(UUID objectID, UUID userID, Scene inScene); public delegate bool DuplicateObjectHandler(int objectCount, UUID objectID, UUID owner, Scene scene, Vector3 objectPosition); public delegate bool EditObjectHandler(UUID objectID, UUID editorID, Scene scene); public delegate bool EditObjectInventoryHandler(UUID objectID, UUID editorID, Scene scene); public delegate bool MoveObjectHandler(UUID objectID, UUID moverID, Scene scene); public delegate bool ObjectEntryHandler(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene); public delegate bool ReturnObjectsHandler(ILandObject land, UUID user, List<SceneObjectGroup> objects, Scene scene); public delegate bool InstantMessageHandler(UUID user, UUID target, Scene startScene); public delegate bool InventoryTransferHandler(UUID user, UUID target, Scene startScene); public delegate bool ViewScriptHandler(UUID script, UUID objectID, UUID user, Scene scene); public delegate bool ViewNotecardHandler(UUID script, UUID objectID, UUID user, Scene scene); public delegate bool EditScriptHandler(UUID script, UUID objectID, UUID user, Scene scene); public delegate bool EditNotecardHandler(UUID notecard, UUID objectID, UUID user, Scene scene); public delegate bool RunScriptHandler(UUID script, UUID objectID, UUID user, Scene scene); public delegate bool CompileScriptHandler(UUID ownerUUID, int scriptType, Scene scene); public delegate bool StartScriptHandler(UUID script, UUID user, Scene scene); public delegate bool StopScriptHandler(UUID script, UUID user, Scene scene); public delegate bool ResetScriptHandler(UUID prim, UUID script, UUID user, Scene scene); public delegate bool TerraformLandHandler(UUID user, Vector3 position, Scene requestFromScene); public delegate bool RunConsoleCommandHandler(UUID user, Scene requestFromScene); public delegate bool IssueEstateCommandHandler(UUID user, Scene requestFromScene, bool ownerCommand); public delegate bool IsGodHandler(UUID user, Scene requestFromScene); public delegate bool IsAdministratorHandler(UUID user); public delegate bool EditParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool EditParcelPropertiesHandler(UUID user, ILandObject parcel, GroupPowers p, Scene scene); public delegate bool SellParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool AbandonParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool ReclaimParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool DeedParcelHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool DeedObjectHandler(UUID user, UUID group, Scene scene); public delegate bool BuyLandHandler(UUID user, ILandObject parcel, Scene scene); public delegate bool LinkObjectHandler(UUID user, UUID objectID); public delegate bool DelinkObjectHandler(UUID user, UUID objectID); public delegate bool CreateObjectInventoryHandler(int invType, UUID objectID, UUID userID); public delegate bool CopyObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID); public delegate bool DeleteObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID); public delegate bool TransferObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID); public delegate bool CreateUserInventoryHandler(int invType, UUID userID); public delegate bool EditUserInventoryHandler(UUID itemID, UUID userID); public delegate bool CopyUserInventoryHandler(UUID itemID, UUID userID); public delegate bool DeleteUserInventoryHandler(UUID itemID, UUID userID); public delegate bool TransferUserInventoryHandler(UUID itemID, UUID userID, UUID recipientID); public delegate bool TeleportHandler(UUID userID, Scene scene); public delegate bool ControlPrimMediaHandler(UUID userID, UUID primID, int face); public delegate bool InteractWithPrimMediaHandler(UUID userID, UUID primID, int face); #endregion public class ScenePermissions { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; public ScenePermissions(Scene scene) { m_scene = scene; } #region Events public event GenerateClientFlagsHandler OnGenerateClientFlags; public event SetBypassPermissionsHandler OnSetBypassPermissions; public event BypassPermissionsHandler OnBypassPermissions; public event PropagatePermissionsHandler OnPropagatePermissions; public event RezObjectHandler OnRezObject; public event DeleteObjectHandler OnDeleteObject; public event TransferObjectHandler OnTransferObject; public event TakeObjectHandler OnTakeObject; public event TakeCopyObjectHandler OnTakeCopyObject; public event DuplicateObjectHandler OnDuplicateObject; public event EditObjectHandler OnEditObject; public event EditObjectInventoryHandler OnEditObjectInventory; public event MoveObjectHandler OnMoveObject; public event ObjectEntryHandler OnObjectEntry; public event ReturnObjectsHandler OnReturnObjects; public event InstantMessageHandler OnInstantMessage; public event InventoryTransferHandler OnInventoryTransfer; public event ViewScriptHandler OnViewScript; public event ViewNotecardHandler OnViewNotecard; public event EditScriptHandler OnEditScript; public event EditNotecardHandler OnEditNotecard; public event RunScriptHandler OnRunScript; public event CompileScriptHandler OnCompileScript; public event StartScriptHandler OnStartScript; public event StopScriptHandler OnStopScript; public event ResetScriptHandler OnResetScript; public event TerraformLandHandler OnTerraformLand; public event RunConsoleCommandHandler OnRunConsoleCommand; public event IssueEstateCommandHandler OnIssueEstateCommand; public event IsGodHandler OnIsGod; public event IsAdministratorHandler OnIsAdministrator; // public event EditParcelHandler OnEditParcel; public event EditParcelPropertiesHandler OnEditParcelProperties; public event SellParcelHandler OnSellParcel; public event AbandonParcelHandler OnAbandonParcel; public event ReclaimParcelHandler OnReclaimParcel; public event DeedParcelHandler OnDeedParcel; public event DeedObjectHandler OnDeedObject; public event BuyLandHandler OnBuyLand; public event LinkObjectHandler OnLinkObject; public event DelinkObjectHandler OnDelinkObject; public event CreateObjectInventoryHandler OnCreateObjectInventory; public event CopyObjectInventoryHandler OnCopyObjectInventory; public event DeleteObjectInventoryHandler OnDeleteObjectInventory; public event TransferObjectInventoryHandler OnTransferObjectInventory; public event CreateUserInventoryHandler OnCreateUserInventory; public event EditUserInventoryHandler OnEditUserInventory; public event CopyUserInventoryHandler OnCopyUserInventory; public event DeleteUserInventoryHandler OnDeleteUserInventory; public event TransferUserInventoryHandler OnTransferUserInventory; public event TeleportHandler OnTeleport; public event ControlPrimMediaHandler OnControlPrimMedia; public event InteractWithPrimMediaHandler OnInteractWithPrimMedia; #endregion #region Object Permission Checks public uint GenerateClientFlags(UUID userID, UUID objectID) { // libomv will moan about PrimFlags.ObjectYouOfficer being // obsolete... #pragma warning disable 0612 const PrimFlags DEFAULT_FLAGS = PrimFlags.ObjectModify | PrimFlags.ObjectCopy | PrimFlags.ObjectMove | PrimFlags.ObjectTransfer | PrimFlags.ObjectYouOwner | PrimFlags.ObjectAnyOwner | PrimFlags.ObjectOwnerModify | PrimFlags.ObjectYouOfficer; #pragma warning restore 0612 SceneObjectPart part = m_scene.GetSceneObjectPart(objectID); if (part == null) return 0; uint perms = part.GetEffectiveObjectFlags() | (uint)DEFAULT_FLAGS; GenerateClientFlagsHandler handlerGenerateClientFlags = OnGenerateClientFlags; if (handlerGenerateClientFlags != null) { Delegate[] list = handlerGenerateClientFlags.GetInvocationList(); foreach (GenerateClientFlagsHandler check in list) { perms &= check(userID, objectID); } } return perms; } public void SetBypassPermissions(bool value) { SetBypassPermissionsHandler handler = OnSetBypassPermissions; if (handler != null) handler(value); } public bool BypassPermissions() { BypassPermissionsHandler handler = OnBypassPermissions; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (BypassPermissionsHandler h in list) { if (h() == false) return false; } } return true; } public bool PropagatePermissions() { PropagatePermissionsHandler handler = OnPropagatePermissions; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (PropagatePermissionsHandler h in list) { if (h() == false) return false; } } return true; } #region REZ OBJECT public bool CanRezObject(int objectCount, UUID owner, Vector3 objectPosition) { RezObjectHandler handler = OnRezObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (RezObjectHandler h in list) { if (h(objectCount, owner,objectPosition, m_scene) == false) return false; } } return true; } #endregion #region DELETE OBJECT public bool CanDeleteObject(UUID objectID, UUID deleter) { bool result = true; DeleteObjectHandler handler = OnDeleteObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeleteObjectHandler h in list) { if (h(objectID, deleter, m_scene) == false) { result = false; break; } } } return result; } public bool CanTransferObject(UUID objectID, UUID recipient) { bool result = true; TransferObjectHandler handler = OnTransferObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TransferObjectHandler h in list) { if (h(objectID, recipient, m_scene) == false) { result = false; break; } } } return result; } #endregion #region TAKE OBJECT public bool CanTakeObject(UUID objectID, UUID AvatarTakingUUID) { bool result = true; TakeObjectHandler handler = OnTakeObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TakeObjectHandler h in list) { if (h(objectID, AvatarTakingUUID, m_scene) == false) { result = false; break; } } } // m_log.DebugFormat( // "[SCENE PERMISSIONS]: CanTakeObject() fired for object {0}, taker {1}, result {2}", // objectID, AvatarTakingUUID, result); return result; } #endregion #region TAKE COPY OBJECT public bool CanTakeCopyObject(UUID objectID, UUID userID) { bool result = true; TakeCopyObjectHandler handler = OnTakeCopyObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TakeCopyObjectHandler h in list) { if (h(objectID, userID, m_scene) == false) { result = false; break; } } } // m_log.DebugFormat( // "[SCENE PERMISSIONS]: CanTakeCopyObject() fired for object {0}, user {1}, result {2}", // objectID, userID, result); return result; } #endregion #region DUPLICATE OBJECT public bool CanDuplicateObject(int objectCount, UUID objectID, UUID owner, Vector3 objectPosition) { DuplicateObjectHandler handler = OnDuplicateObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DuplicateObjectHandler h in list) { if (h(objectCount, objectID, owner, m_scene, objectPosition) == false) return false; } } return true; } #endregion #region EDIT OBJECT public bool CanEditObject(UUID objectID, UUID editorID) { EditObjectHandler handler = OnEditObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditObjectHandler h in list) { if (h(objectID, editorID, m_scene) == false) return false; } } return true; } public bool CanEditObjectInventory(UUID objectID, UUID editorID) { EditObjectInventoryHandler handler = OnEditObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditObjectInventoryHandler h in list) { if (h(objectID, editorID, m_scene) == false) return false; } } return true; } #endregion #region MOVE OBJECT public bool CanMoveObject(UUID objectID, UUID moverID) { MoveObjectHandler handler = OnMoveObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (MoveObjectHandler h in list) { if (h(objectID, moverID, m_scene) == false) return false; } } return true; } #endregion #region OBJECT ENTRY public bool CanObjectEntry(UUID objectID, bool enteringRegion, Vector3 newPoint) { ObjectEntryHandler handler = OnObjectEntry; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ObjectEntryHandler h in list) { if (h(objectID, enteringRegion, newPoint, m_scene) == false) return false; } } return true; } #endregion #region RETURN OBJECT public bool CanReturnObjects(ILandObject land, UUID user, List<SceneObjectGroup> objects) { bool result = true; ReturnObjectsHandler handler = OnReturnObjects; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ReturnObjectsHandler h in list) { if (h(land, user, objects, m_scene) == false) { result = false; break; } } } // m_log.DebugFormat( // "[SCENE PERMISSIONS]: CanReturnObjects() fired for user {0} for {1} objects on {2}, result {3}", // user, objects.Count, land.LandData.Name, result); return result; } #endregion #region INSTANT MESSAGE public bool CanInstantMessage(UUID user, UUID target) { InstantMessageHandler handler = OnInstantMessage; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (InstantMessageHandler h in list) { if (h(user, target, m_scene) == false) return false; } } return true; } #endregion #region INVENTORY TRANSFER public bool CanInventoryTransfer(UUID user, UUID target) { InventoryTransferHandler handler = OnInventoryTransfer; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (InventoryTransferHandler h in list) { if (h(user, target, m_scene) == false) return false; } } return true; } #endregion #region VIEW SCRIPT public bool CanViewScript(UUID script, UUID objectID, UUID user) { ViewScriptHandler handler = OnViewScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ViewScriptHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } public bool CanViewNotecard(UUID script, UUID objectID, UUID user) { ViewNotecardHandler handler = OnViewNotecard; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ViewNotecardHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } #endregion #region EDIT SCRIPT public bool CanEditScript(UUID script, UUID objectID, UUID user) { EditScriptHandler handler = OnEditScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditScriptHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } public bool CanEditNotecard(UUID script, UUID objectID, UUID user) { EditNotecardHandler handler = OnEditNotecard; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditNotecardHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } #endregion #region RUN SCRIPT (When Script Placed in Object) public bool CanRunScript(UUID script, UUID objectID, UUID user) { RunScriptHandler handler = OnRunScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (RunScriptHandler h in list) { if (h(script, objectID, user, m_scene) == false) return false; } } return true; } #endregion #region COMPILE SCRIPT (When Script needs to get (re)compiled) public bool CanCompileScript(UUID ownerUUID, int scriptType) { CompileScriptHandler handler = OnCompileScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CompileScriptHandler h in list) { if (h(ownerUUID, scriptType, m_scene) == false) return false; } } return true; } #endregion #region START SCRIPT (When Script run box is Checked after placed in object) public bool CanStartScript(UUID script, UUID user) { StartScriptHandler handler = OnStartScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (StartScriptHandler h in list) { if (h(script, user, m_scene) == false) return false; } } return true; } #endregion #region STOP SCRIPT (When Script run box is unchecked after placed in object) public bool CanStopScript(UUID script, UUID user) { StopScriptHandler handler = OnStopScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (StopScriptHandler h in list) { if (h(script, user, m_scene) == false) return false; } } return true; } #endregion #region RESET SCRIPT public bool CanResetScript(UUID prim, UUID script, UUID user) { ResetScriptHandler handler = OnResetScript; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ResetScriptHandler h in list) { if (h(prim, script, user, m_scene) == false) return false; } } return true; } #endregion #region TERRAFORM LAND public bool CanTerraformLand(UUID user, Vector3 pos) { TerraformLandHandler handler = OnTerraformLand; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TerraformLandHandler h in list) { if (h(user, pos, m_scene) == false) return false; } } return true; } #endregion #region RUN CONSOLE COMMAND public bool CanRunConsoleCommand(UUID user) { RunConsoleCommandHandler handler = OnRunConsoleCommand; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (RunConsoleCommandHandler h in list) { if (h(user, m_scene) == false) return false; } } return true; } #endregion #region CAN ISSUE ESTATE COMMAND public bool CanIssueEstateCommand(UUID user, bool ownerCommand) { IssueEstateCommandHandler handler = OnIssueEstateCommand; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (IssueEstateCommandHandler h in list) { if (h(user, m_scene, ownerCommand) == false) return false; } } return true; } #endregion #region CAN BE GODLIKE public bool IsGod(UUID user) { IsGodHandler handler = OnIsGod; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (IsGodHandler h in list) { if (h(user, m_scene) == false) return false; } } return true; } public bool IsAdministrator(UUID user) { IsAdministratorHandler handler = OnIsAdministrator; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (IsAdministratorHandler h in list) { if (h(user) == false) return false; } } return true; } #endregion #region EDIT PARCEL public bool CanEditParcelProperties(UUID user, ILandObject parcel, GroupPowers p) { EditParcelPropertiesHandler handler = OnEditParcelProperties; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditParcelPropertiesHandler h in list) { if (h(user, parcel, p, m_scene) == false) return false; } } return true; } #endregion #region SELL PARCEL public bool CanSellParcel(UUID user, ILandObject parcel) { SellParcelHandler handler = OnSellParcel; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (SellParcelHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } #endregion #region ABANDON PARCEL public bool CanAbandonParcel(UUID user, ILandObject parcel) { AbandonParcelHandler handler = OnAbandonParcel; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (AbandonParcelHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } #endregion public bool CanReclaimParcel(UUID user, ILandObject parcel) { ReclaimParcelHandler handler = OnReclaimParcel; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ReclaimParcelHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } public bool CanDeedParcel(UUID user, ILandObject parcel) { DeedParcelHandler handler = OnDeedParcel; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeedParcelHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } public bool CanDeedObject(UUID user, UUID group) { DeedObjectHandler handler = OnDeedObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeedObjectHandler h in list) { if (h(user, group, m_scene) == false) return false; } } return true; } public bool CanBuyLand(UUID user, ILandObject parcel) { BuyLandHandler handler = OnBuyLand; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (BuyLandHandler h in list) { if (h(user, parcel, m_scene) == false) return false; } } return true; } public bool CanLinkObject(UUID user, UUID objectID) { LinkObjectHandler handler = OnLinkObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (LinkObjectHandler h in list) { if (h(user, objectID) == false) return false; } } return true; } public bool CanDelinkObject(UUID user, UUID objectID) { DelinkObjectHandler handler = OnDelinkObject; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DelinkObjectHandler h in list) { if (h(user, objectID) == false) return false; } } return true; } #endregion /// Check whether the specified user is allowed to directly create the given inventory type in a prim's /// inventory (e.g. the New Script button in the 1.21 Linden Lab client). /// </summary> /// <param name="invType"></param> /// <param name="objectID"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanCreateObjectInventory(int invType, UUID objectID, UUID userID) { CreateObjectInventoryHandler handler = OnCreateObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CreateObjectInventoryHandler h in list) { if (h(invType, objectID, userID) == false) return false; } } return true; } public bool CanCopyObjectInventory(UUID itemID, UUID objectID, UUID userID) { CopyObjectInventoryHandler handler = OnCopyObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CopyObjectInventoryHandler h in list) { if (h(itemID, objectID, userID) == false) return false; } } return true; } public bool CanDeleteObjectInventory(UUID itemID, UUID objectID, UUID userID) { DeleteObjectInventoryHandler handler = OnDeleteObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeleteObjectInventoryHandler h in list) { if (h(itemID, objectID, userID) == false) return false; } } return true; } public bool CanTransferObjectInventory(UUID itemID, UUID objectID, UUID userID) { TransferObjectInventoryHandler handler = OnTransferObjectInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TransferObjectInventoryHandler h in list) { if (h(itemID, objectID, userID) == false) return false; } } return true; } /// <summary> /// Check whether the specified user is allowed to create the given inventory type in their inventory. /// </summary> /// <param name="invType"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanCreateUserInventory(int invType, UUID userID) { CreateUserInventoryHandler handler = OnCreateUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CreateUserInventoryHandler h in list) { if (h(invType, userID) == false) return false; } } return true; } /// <summary> /// Check whether the specified user is allowed to edit the given inventory item within their own inventory. /// </summary> /// <param name="itemID"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanEditUserInventory(UUID itemID, UUID userID) { EditUserInventoryHandler handler = OnEditUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (EditUserInventoryHandler h in list) { if (h(itemID, userID) == false) return false; } } return true; } /// <summary> /// Check whether the specified user is allowed to copy the given inventory item from their own inventory. /// </summary> /// <param name="itemID"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanCopyUserInventory(UUID itemID, UUID userID) { CopyUserInventoryHandler handler = OnCopyUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (CopyUserInventoryHandler h in list) { if (h(itemID, userID) == false) return false; } } return true; } /// <summary> /// Check whether the specified user is allowed to edit the given inventory item within their own inventory. /// </summary> /// <param name="itemID"></param> /// <param name="userID"></param> /// <returns></returns> public bool CanDeleteUserInventory(UUID itemID, UUID userID) { DeleteUserInventoryHandler handler = OnDeleteUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (DeleteUserInventoryHandler h in list) { if (h(itemID, userID) == false) return false; } } return true; } public bool CanTransferUserInventory(UUID itemID, UUID userID, UUID recipientID) { TransferUserInventoryHandler handler = OnTransferUserInventory; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TransferUserInventoryHandler h in list) { if (h(itemID, userID, recipientID) == false) return false; } } return true; } public bool CanTeleport(UUID userID) { TeleportHandler handler = OnTeleport; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (TeleportHandler h in list) { if (h(userID, m_scene) == false) return false; } } return true; } public bool CanControlPrimMedia(UUID userID, UUID primID, int face) { ControlPrimMediaHandler handler = OnControlPrimMedia; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (ControlPrimMediaHandler h in list) { if (h(userID, primID, face) == false) return false; } } return true; } public bool CanInteractWithPrimMedia(UUID userID, UUID primID, int face) { InteractWithPrimMediaHandler handler = OnInteractWithPrimMedia; if (handler != null) { Delegate[] list = handler.GetInvocationList(); foreach (InteractWithPrimMediaHandler h in list) { if (h(userID, primID, face) == false) return false; } } return true; } } }
// Copyright (c) .NET Foundation and contributors. 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.Diagnostics; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Compilation.Preprocessor; using Microsoft.DotNet.ProjectModel.Files; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.ProjectModel.Resolution; using Microsoft.DotNet.ProjectModel.Utilities; using Microsoft.DotNet.Tools.Compiler; using NuGet.Frameworks; namespace Microsoft.DotNet.ProjectModel.Compilation { public class LibraryExporter { private readonly string _configuration; private readonly string _runtime; private readonly string[] _runtimeFallbacks; private readonly ProjectDescription _rootProject; private readonly string _buildBasePath; private readonly string _solutionRootPath; public LibraryExporter(ProjectDescription rootProject, LibraryManager manager, string configuration, string runtime, string[] runtimeFallbacks, string buildBasePath, string solutionRootPath) { if (string.IsNullOrEmpty(configuration)) { throw new ArgumentNullException(nameof(configuration)); } LibraryManager = manager; _configuration = configuration; _runtime = runtime; _runtimeFallbacks = runtimeFallbacks; _buildBasePath = buildBasePath; _solutionRootPath = solutionRootPath; _rootProject = rootProject; } public LibraryManager LibraryManager { get; } /// <summary> /// Gets all the exports specified by this project, including the root project itself /// </summary> public IEnumerable<LibraryExport> GetAllExports() { return ExportLibraries(_ => true); } /// <summary> /// Gets all exports required by the project, NOT including the project itself /// </summary> /// <returns></returns> public IEnumerable<LibraryExport> GetDependencies() { return GetDependencies(LibraryType.Unspecified); } /// <summary> /// Gets all exports required by the project, of the specified <see cref="LibraryType"/>, NOT including the project itself /// </summary> /// <returns></returns> public IEnumerable<LibraryExport> GetDependencies(LibraryType type) { // Export all but the main project return ExportLibraries(library => library != _rootProject && LibraryIsOfType(type, library)); } /// <summary> /// Retrieves a list of <see cref="LibraryExport"/> objects representing the assets /// required from other libraries to compile this project. /// </summary> private IEnumerable<LibraryExport> ExportLibraries(Func<LibraryDescription, bool> condition) { var seenMetadataReferences = new HashSet<string>(); // Iterate over libraries in the library manager foreach (var library in LibraryManager.GetLibraries()) { if (!condition(library)) { continue; } var compilationAssemblies = new List<LibraryAsset>(); var sourceReferences = new List<LibraryAsset>(); var analyzerReferences = new List<AnalyzerReference>(); var libraryExport = GetExport(library); // We need to filter out source references from non-root libraries, // so we rebuild the library export foreach (var reference in libraryExport.CompilationAssemblies) { if (seenMetadataReferences.Add(reference.Name)) { compilationAssemblies.Add(reference); } } // Source and analyzer references are not transitive if (library.Parents.Contains(_rootProject)) { sourceReferences.AddRange(libraryExport.SourceReferences); analyzerReferences.AddRange(libraryExport.AnalyzerReferences); } var builder = LibraryExportBuilder.Create(library); if (_runtime != null && _runtimeFallbacks != null) { // For portable apps that are built with runtime trimming we replace RuntimeAssemblyGroups and NativeLibraryGroups // with single default group that contains asset specific to runtime we are trimming for // based on runtime fallback list builder.WithRuntimeAssemblyGroups(TrimAssetGroups(libraryExport.RuntimeAssemblyGroups, _runtimeFallbacks)); builder.WithNativeLibraryGroups(TrimAssetGroups(libraryExport.NativeLibraryGroups, _runtimeFallbacks)); } else { builder.WithRuntimeAssemblyGroups(libraryExport.RuntimeAssemblyGroups); builder.WithNativeLibraryGroups(libraryExport.NativeLibraryGroups); } yield return builder .WithCompilationAssemblies(compilationAssemblies) .WithSourceReferences(sourceReferences) .WithRuntimeAssets(libraryExport.RuntimeAssets) .WithEmbedddedResources(libraryExport.EmbeddedResources) .WithAnalyzerReference(analyzerReferences) .WithResourceAssemblies(libraryExport.ResourceAssemblies) .Build(); } } private IEnumerable<LibraryAssetGroup> TrimAssetGroups(IEnumerable<LibraryAssetGroup> runtimeAssemblyGroups, string[] runtimeFallbacks) { LibraryAssetGroup runtimeAssets; foreach (var rid in runtimeFallbacks) { runtimeAssets = runtimeAssemblyGroups.GetRuntimeGroup(rid); if (runtimeAssets != null) { yield return new LibraryAssetGroup(runtimeAssets.Assets); yield break; } } runtimeAssets = runtimeAssemblyGroups.GetDefaultGroup(); if (runtimeAssets != null) { yield return runtimeAssets; } } /// <summary> /// Create a LibraryExport from LibraryDescription. /// /// When the library is not resolved the LibraryExport is created nevertheless. /// </summary> private LibraryExport GetExport(LibraryDescription library) { if (!library.Resolved) { // For a unresolved project reference returns a export with empty asset. return LibraryExportBuilder.Create(library).Build(); } var libraryType = library.Identity.Type; if (Equals(LibraryType.Package, libraryType) || Equals(LibraryType.MSBuildProject, libraryType)) { return ExportPackage((TargetLibraryWithAssets)library); } else if (Equals(LibraryType.Project, libraryType)) { return ExportProject((ProjectDescription)library); } else { return ExportFrameworkLibrary(library); } } private LibraryExport ExportPackage(TargetLibraryWithAssets library) { var builder = LibraryExportBuilder.Create(library); builder.AddNativeLibraryGroup(new LibraryAssetGroup(PopulateAssets(library, library.NativeLibraries))); builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(PopulateAssets(library, library.RuntimeAssemblies))); builder.WithResourceAssemblies(PopulateResources(library, library.ResourceAssemblies)); builder.WithCompilationAssemblies(PopulateAssets(library, library.CompileTimeAssemblies)); if (library.Identity.Type.Equals(LibraryType.Package)) { builder.WithSourceReferences(GetSharedSources((PackageDescription) library)); builder.WithAnalyzerReference(GetAnalyzerReferences((PackageDescription) library)); } if (library.ContentFiles.Any()) { var parameters = PPFileParameters.CreateForProject(_rootProject.Project); Action<Stream, Stream> transform = (input, output) => PPFilePreprocessor.Preprocess(input, output, parameters); var sourceCodeLanguage = _rootProject.Project.GetSourceCodeLanguage(); var languageGroups = library.ContentFiles.GroupBy(file => file.CodeLanguage); var selectedGroup = languageGroups.FirstOrDefault(g => g.Key == sourceCodeLanguage) ?? languageGroups.FirstOrDefault(g => g.Key == null); if (selectedGroup != null) { foreach (var contentFile in selectedGroup) { if (contentFile.CodeLanguage != null && string.Compare(contentFile.CodeLanguage, sourceCodeLanguage, StringComparison.OrdinalIgnoreCase) != 0) { continue; } var fileTransform = contentFile.PPOutputPath != null ? transform : null; var fullPath = Path.Combine(library.Path, contentFile.Path); if (contentFile.BuildAction == BuildAction.Compile) { builder.AddSourceReference(LibraryAsset.CreateFromRelativePath(library.Path, contentFile.Path, fileTransform)); } else if (contentFile.BuildAction == BuildAction.EmbeddedResource) { builder.AddEmbedddedResource(LibraryAsset.CreateFromRelativePath(library.Path, contentFile.Path, fileTransform)); } if (contentFile.CopyToOutput) { builder.AddRuntimeAsset(new LibraryAsset(contentFile.Path, contentFile.OutputPath, fullPath, fileTransform)); } } } } if (library.RuntimeTargets.Any()) { foreach (var targetGroup in library.RuntimeTargets.GroupBy(t => t.Runtime)) { var runtime = new List<LibraryAsset>(); var native = new List<LibraryAsset>(); foreach (var lockFileRuntimeTarget in targetGroup) { if (string.Equals(lockFileRuntimeTarget.AssetType, "native", StringComparison.OrdinalIgnoreCase)) { native.Add(LibraryAsset.CreateFromRelativePath(library.Path, lockFileRuntimeTarget.Path)); } else if (string.Equals(lockFileRuntimeTarget.AssetType, "runtime", StringComparison.OrdinalIgnoreCase)) { runtime.Add(LibraryAsset.CreateFromRelativePath(library.Path, lockFileRuntimeTarget.Path)); } } if (runtime.Any()) { builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(targetGroup.Key, runtime.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.RelativePath)))); } if (native.Any()) { builder.AddNativeLibraryGroup(new LibraryAssetGroup(targetGroup.Key, native.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.RelativePath)))); } } } return builder.Build(); } private LibraryExport ExportProject(ProjectDescription project) { var builder = LibraryExportBuilder.Create(project); var compilerOptions = project.Project.GetCompilerOptions(project.TargetFrameworkInfo.FrameworkName, _configuration); if (!string.IsNullOrEmpty(project.TargetFrameworkInfo?.AssemblyPath)) { // Project specifies a pre-compiled binary. We're done! var assemblyPath = ResolvePath(project.Project, _configuration, project.TargetFrameworkInfo.AssemblyPath); var pdbPath = Path.ChangeExtension(assemblyPath, "pdb"); var compileAsset = new LibraryAsset( project.Project.Name, Path.GetFileName(assemblyPath), assemblyPath); builder.AddCompilationAssembly(compileAsset); builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(new[] { compileAsset })); if (File.Exists(pdbPath)) { builder.AddRuntimeAsset(new LibraryAsset(Path.GetFileName(pdbPath), Path.GetFileName(pdbPath), pdbPath)); } } else if (HasSourceFiles(project, compilerOptions)) { var outputPaths = project.GetOutputPaths(_buildBasePath, _solutionRootPath, _configuration, _runtime); var compilationAssembly = outputPaths.CompilationFiles.Assembly; var compilationAssemblyAsset = LibraryAsset.CreateFromAbsolutePath( outputPaths.CompilationFiles.BasePath, compilationAssembly); builder.AddCompilationAssembly(compilationAssemblyAsset); if (ExportsRuntime(project)) { var runtimeAssemblyAsset = LibraryAsset.CreateFromAbsolutePath( outputPaths.RuntimeFiles.BasePath, outputPaths.RuntimeFiles.Assembly); builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(new[] { runtimeAssemblyAsset })); builder.WithRuntimeAssets(CollectAssets(outputPaths.RuntimeFiles)); } else { builder.AddRuntimeAssemblyGroup(new LibraryAssetGroup(new[] { compilationAssemblyAsset })); builder.WithRuntimeAssets(CollectAssets(outputPaths.CompilationFiles)); } builder.WithResourceAssemblies(outputPaths.CompilationFiles.Resources().Select(r => new LibraryResourceAssembly( LibraryAsset.CreateFromAbsolutePath(outputPaths.CompilationFiles.BasePath, r.Path), r.Locale))); } builder.WithSourceReferences(project.Project.Files.SharedFiles.Select(f => LibraryAsset.CreateFromAbsolutePath(project.Path, f) )); return builder.Build(); } private bool HasSourceFiles(ProjectDescription project, CommonCompilerOptions compilerOptions) { if (compilerOptions.CompileInclude == null) { return project.Project.Files.SourceFiles.Any(); } var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null); return includeFiles.Any(); } private IEnumerable<LibraryAsset> CollectAssets(CompilationOutputFiles files) { var assemblyPath = files.Assembly; foreach (var path in files.All().Except(files.Resources().Select(r => r.Path))) { if (string.Equals(assemblyPath, path)) { continue; } yield return LibraryAsset.CreateFromAbsolutePath(files.BasePath, path); } } private bool ExportsRuntime(ProjectDescription project) { return project == _rootProject && !string.IsNullOrWhiteSpace(_runtime) && project.Project.HasRuntimeOutput(_configuration); } private static string ResolvePath(Project project, string configuration, string path) { if (string.IsNullOrEmpty(path)) { return null; } path = PathUtility.GetPathWithDirectorySeparator(path); path = path.Replace("{configuration}", configuration); return Path.Combine(project.ProjectDirectory, path); } private LibraryExport ExportFrameworkLibrary(LibraryDescription library) { // We assume the path is to an assembly. Framework libraries only export compile-time stuff // since they assume the runtime library is present already var builder = LibraryExportBuilder.Create(library); if (!string.IsNullOrEmpty(library.Path)) { builder.WithCompilationAssemblies(new[] { new LibraryAsset(library.Identity.Name, null, library.Path) }); } return builder.Build(); } private IEnumerable<LibraryAsset> GetSharedSources(PackageDescription package) { return package .PackageLibrary .Files .Where(path => path.StartsWith("shared" + Path.DirectorySeparatorChar)) .Select(path => LibraryAsset.CreateFromRelativePath(package.Path, path)); } private IEnumerable<AnalyzerReference> GetAnalyzerReferences(PackageDescription package) { var analyzers = package .PackageLibrary .Files .Where(path => path.StartsWith("analyzers" + Path.DirectorySeparatorChar) && path.EndsWith(".dll")); var analyzerRefs = new List<AnalyzerReference>(); // See https://docs.nuget.org/create/analyzers-conventions for the analyzer // NuGet specification foreach (var analyzer in analyzers) { var specifiers = analyzer.Split(Path.DirectorySeparatorChar); var assemblyPath = Path.Combine(package.Path, analyzer); // $/analyzers/{Framework Name}{Version}/{Supported Architecture}/{Supported Programming Language}/{Analyzer}.dll switch (specifiers.Length) { // $/analyzers/{analyzer}.dll case 2: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: null, language: null, runtimeIdentifier: null )); break; // $/analyzers/{framework}/{analyzer}.dll case 3: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: NuGetFramework.Parse(specifiers[1]), language: null, runtimeIdentifier: null )); break; // $/analyzers/{framework}/{language}/{analyzer}.dll case 4: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: NuGetFramework.Parse(specifiers[1]), language: specifiers[2], runtimeIdentifier: null )); break; // $/analyzers/{framework}/{runtime}/{language}/{analyzer}.dll case 5: analyzerRefs.Add(new AnalyzerReference( assembly: assemblyPath, framework: NuGetFramework.Parse(specifiers[1]), language: specifiers[3], runtimeIdentifier: specifiers[2] )); break; // Anything less than 2 specifiers or more than 4 is // illegal according to the specification and will be // ignored } } return analyzerRefs; } private IEnumerable<LibraryResourceAssembly> PopulateResources(TargetLibraryWithAssets library, IEnumerable<LockFileItem> section) { foreach (var assemblyPath in section.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.Path))) { string locale; if(!assemblyPath.Properties.TryGetValue(Constants.LocaleLockFilePropertyName, out locale)) { locale = null; } yield return new LibraryResourceAssembly( LibraryAsset.CreateFromRelativePath(library.Path, assemblyPath.Path), locale); } } private IEnumerable<LibraryAsset> PopulateAssets(TargetLibraryWithAssets library, IEnumerable<LockFileItem> section) { foreach (var assemblyPath in section.Where(a => !PackageDependencyProvider.IsPlaceholderFile(a.Path))) { yield return LibraryAsset.CreateFromRelativePath(library.Path, assemblyPath.Path); } } private static bool LibraryIsOfType(LibraryType type, LibraryDescription library) { return type.Equals(LibraryType.Unspecified) || // No type filter was requested library.Identity.Type.Equals(type); // OR, library type matches requested type } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace BugLogger.RestService.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Util; using Lucene.Net.Util.Packed; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Lucene.Net.Codecs.BlockTerms { /* * 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. */ /// <summary> /// <see cref="TermsIndexReaderBase"/> for simple every Nth terms indexes. /// <para/> /// @lucene.experimental /// </summary> /// <seealso cref="FixedGapTermsIndexWriter"/> public class FixedGapTermsIndexReader : TermsIndexReaderBase { // NOTE: long is overkill here, since this number is 128 // by default and only indexDivisor * 128 if you change // the indexDivisor at search time. But, we use this in a // number of places to multiply out the actual ord, and we // will overflow int during those multiplies. So to avoid // having to upgrade each multiple to long in multiple // places (error prone), we use long here: private long totalIndexInterval; private int indexDivisor; private readonly int indexInterval; // Closed if indexLoaded is true: private IndexInput input; private volatile bool indexLoaded; private readonly IComparer<BytesRef> termComp; private readonly static int PAGED_BYTES_BITS = 15; // all fields share this single logical byte[] private readonly PagedBytes termBytes = new PagedBytes(PAGED_BYTES_BITS); private PagedBytes.Reader termBytesReader; readonly IDictionary<FieldInfo, FieldIndexData> fields = new Dictionary<FieldInfo, FieldIndexData>(); // start of the field info data private long dirOffset; private readonly int version; public FixedGapTermsIndexReader(Directory dir, FieldInfos fieldInfos, string segment, int indexDivisor, IComparer<BytesRef> termComp, string segmentSuffix, IOContext context) { this.termComp = termComp; Debug.Assert(indexDivisor == -1 || indexDivisor > 0); input = dir.OpenInput(IndexFileNames.SegmentFileName(segment, segmentSuffix, FixedGapTermsIndexWriter.TERMS_INDEX_EXTENSION), context); bool success = false; try { version = ReadHeader(input); if (version >= FixedGapTermsIndexWriter.VERSION_CHECKSUM) { CodecUtil.ChecksumEntireFile(input); } indexInterval = input.ReadInt32(); if (indexInterval < 1) { throw new CorruptIndexException("invalid indexInterval: " + indexInterval + " (resource=" + input + ")"); } this.indexDivisor = indexDivisor; if (indexDivisor < 0) { totalIndexInterval = indexInterval; } else { // In case terms index gets loaded, later, on demand totalIndexInterval = indexInterval * indexDivisor; } Debug.Assert(totalIndexInterval > 0); SeekDir(input, dirOffset); // Read directory int numFields = input.ReadVInt32(); if (numFields < 0) { throw new CorruptIndexException("invalid numFields: " + numFields + " (resource=" + input + ")"); } //System.out.println("FGR: init seg=" + segment + " div=" + indexDivisor + " nF=" + numFields); for (int i = 0; i < numFields; i++) { int field = input.ReadVInt32(); int numIndexTerms = input.ReadVInt32(); if (numIndexTerms < 0) { throw new CorruptIndexException("invalid numIndexTerms: " + numIndexTerms + " (resource=" + input + ")"); } long termsStart = input.ReadVInt64(); long indexStart = input.ReadVInt64(); long packedIndexStart = input.ReadVInt64(); long packedOffsetsStart = input.ReadVInt64(); if (packedIndexStart < indexStart) { throw new CorruptIndexException("invalid packedIndexStart: " + packedIndexStart + " indexStart: " + indexStart + "numIndexTerms: " + numIndexTerms + " (resource=" + input + ")"); } FieldInfo fieldInfo = fieldInfos.FieldInfo(field); FieldIndexData previous = fields.Put(fieldInfo, new FieldIndexData(this, fieldInfo, numIndexTerms, indexStart, termsStart, packedIndexStart, packedOffsetsStart)); if (previous != null) { throw new CorruptIndexException("duplicate field: " + fieldInfo.Name + " (resource=" + input + ")"); } } success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(input); } if (indexDivisor > 0) { input.Dispose(); input = null; if (success) { indexLoaded = true; } termBytesReader = termBytes.Freeze(true); } } } public override int Divisor { get { return indexDivisor; } } private int ReadHeader(DataInput input) { int version = CodecUtil.CheckHeader(input, FixedGapTermsIndexWriter.CODEC_NAME, FixedGapTermsIndexWriter.VERSION_START, FixedGapTermsIndexWriter.VERSION_CURRENT); if (version < FixedGapTermsIndexWriter.VERSION_APPEND_ONLY) { dirOffset = input.ReadInt64(); } return version; } private class IndexEnum : FieldIndexEnum { // Outer intstance private readonly FixedGapTermsIndexReader outerInstance; private readonly FieldIndexData.CoreFieldIndex fieldIndex; private readonly BytesRef term = new BytesRef(); private long ord; public IndexEnum(FixedGapTermsIndexReader outerInstance, FieldIndexData.CoreFieldIndex fieldIndex) { this.outerInstance = outerInstance; this.fieldIndex = fieldIndex; } public override sealed BytesRef Term { get { return term; } } public override long Seek(BytesRef target) { int lo = 0; // binary search int hi = fieldIndex.numIndexTerms - 1; Debug.Assert(outerInstance.totalIndexInterval > 0, "totalIndexInterval=" + outerInstance.totalIndexInterval); while (hi >= lo) { int mid = (int)(((uint)(lo + hi)) >> 1); long offset2 = fieldIndex.termOffsets.Get(mid); int length2 = (int)(fieldIndex.termOffsets.Get(1 + mid) - offset2); outerInstance.termBytesReader.FillSlice(term, fieldIndex.termBytesStart + offset2, length2); int delta = outerInstance.termComp.Compare(target, term); if (delta < 0) { hi = mid - 1; } else if (delta > 0) { lo = mid + 1; } else { Debug.Assert(mid >= 0); ord = mid * outerInstance.totalIndexInterval; return fieldIndex.termsStart + fieldIndex.termsDictOffsets.Get(mid); } } if (hi < 0) { Debug.Assert(hi == -1); hi = 0; } long offset = fieldIndex.termOffsets.Get(hi); int length = (int)(fieldIndex.termOffsets.Get(1 + hi) - offset); outerInstance.termBytesReader.FillSlice(term, fieldIndex.termBytesStart + offset, length); ord = hi * outerInstance.totalIndexInterval; return fieldIndex.termsStart + fieldIndex.termsDictOffsets.Get(hi); } public override long Next() { int idx = 1 + (int)(ord / outerInstance.totalIndexInterval); if (idx >= fieldIndex.numIndexTerms) { return -1; } ord += outerInstance.totalIndexInterval; long offset = fieldIndex.termOffsets.Get(idx); int length = (int)(fieldIndex.termOffsets.Get(1 + idx) - offset); outerInstance.termBytesReader.FillSlice(term, fieldIndex.termBytesStart + offset, length); return fieldIndex.termsStart + fieldIndex.termsDictOffsets.Get(idx); } public override long Ord { get { return ord; } } public override long Seek(long ord) { int idx = (int)(ord / outerInstance.totalIndexInterval); // caller must ensure ord is in bounds Debug.Assert(idx < fieldIndex.numIndexTerms); long offset = fieldIndex.termOffsets.Get(idx); int length = (int)(fieldIndex.termOffsets.Get(1 + idx) - offset); outerInstance.termBytesReader.FillSlice(term, fieldIndex.termBytesStart + offset, length); this.ord = idx * outerInstance.totalIndexInterval; return fieldIndex.termsStart + fieldIndex.termsDictOffsets.Get(idx); } } public override bool SupportsOrd { get { return true; } } private class FieldIndexData { private readonly FixedGapTermsIndexReader outerInstance; internal volatile CoreFieldIndex coreIndex; private readonly long indexStart; private readonly long termsStart; private readonly long packedIndexStart; private readonly long packedOffsetsStart; private readonly int numIndexTerms; public FieldIndexData(FixedGapTermsIndexReader outerInstance, FieldInfo fieldInfo, int numIndexTerms, long indexStart, long termsStart, long packedIndexStart, long packedOffsetsStart) { this.outerInstance = outerInstance; this.termsStart = termsStart; this.indexStart = indexStart; this.packedIndexStart = packedIndexStart; this.packedOffsetsStart = packedOffsetsStart; this.numIndexTerms = numIndexTerms; if (outerInstance.indexDivisor > 0) { LoadTermsIndex(); } } private void LoadTermsIndex() { if (coreIndex == null) { coreIndex = new CoreFieldIndex(this, indexStart, termsStart, packedIndexStart, packedOffsetsStart, numIndexTerms); } } internal sealed class CoreFieldIndex { // where this field's terms begin in the packed byte[] // data internal readonly long termBytesStart; // offset into index termBytes internal readonly PackedInt32s.Reader termOffsets; // index pointers into main terms dict internal readonly PackedInt32s.Reader termsDictOffsets; internal readonly int numIndexTerms; internal readonly long termsStart; public CoreFieldIndex(FieldIndexData outerInstance, long indexStart, long termsStart, long packedIndexStart, long packedOffsetsStart, int numIndexTerms) { this.termsStart = termsStart; termBytesStart = outerInstance.outerInstance.termBytes.GetPointer(); IndexInput clone = (IndexInput)outerInstance.outerInstance.input.Clone(); clone.Seek(indexStart); // -1 is passed to mean "don't load term index", but // if we are then later loaded it's overwritten with // a real value Debug.Assert(outerInstance.outerInstance.indexDivisor > 0); this.numIndexTerms = 1 + (numIndexTerms - 1) / outerInstance.outerInstance.indexDivisor; Debug.Assert(this.numIndexTerms > 0, "numIndexTerms=" + numIndexTerms + " indexDivisor=" + outerInstance.outerInstance.indexDivisor); if (outerInstance.outerInstance.indexDivisor == 1) { // Default (load all index terms) is fast -- slurp in the images from disk: try { long numTermBytes = packedIndexStart - indexStart; outerInstance.outerInstance.termBytes.Copy(clone, numTermBytes); // records offsets into main terms dict file termsDictOffsets = PackedInt32s.GetReader(clone); Debug.Assert(termsDictOffsets.Count == numIndexTerms); // records offsets into byte[] term data termOffsets = PackedInt32s.GetReader(clone); Debug.Assert(termOffsets.Count == 1 + numIndexTerms); } finally { clone.Dispose(); } } else { // Get packed iterators IndexInput clone1 = (IndexInput)outerInstance.outerInstance.input.Clone(); IndexInput clone2 = (IndexInput)outerInstance.outerInstance.input.Clone(); try { // Subsample the index terms clone1.Seek(packedIndexStart); PackedInt32s.IReaderIterator termsDictOffsetsIter = PackedInt32s.GetReaderIterator(clone1, PackedInt32s.DEFAULT_BUFFER_SIZE); clone2.Seek(packedOffsetsStart); PackedInt32s.IReaderIterator termOffsetsIter = PackedInt32s.GetReaderIterator(clone2, PackedInt32s.DEFAULT_BUFFER_SIZE); // TODO: often we can get by w/ fewer bits per // value, below.. .but this'd be more complex: // we'd have to try @ fewer bits and then grow // if we overflowed it. PackedInt32s.Mutable termsDictOffsetsM = PackedInt32s.GetMutable(this.numIndexTerms, termsDictOffsetsIter.BitsPerValue, PackedInt32s.DEFAULT); PackedInt32s.Mutable termOffsetsM = PackedInt32s.GetMutable(this.numIndexTerms + 1, termOffsetsIter.BitsPerValue, PackedInt32s.DEFAULT); termsDictOffsets = termsDictOffsetsM; termOffsets = termOffsetsM; int upto = 0; long termOffsetUpto = 0; while (upto < this.numIndexTerms) { // main file offset copies straight over termsDictOffsetsM.Set(upto, termsDictOffsetsIter.Next()); termOffsetsM.Set(upto, termOffsetUpto); long termOffset = termOffsetsIter.Next(); long nextTermOffset = termOffsetsIter.Next(); int numTermBytes = (int)(nextTermOffset - termOffset); clone.Seek(indexStart + termOffset); Debug.Assert(indexStart + termOffset < clone.Length, "indexStart=" + indexStart + " termOffset=" + termOffset + " len=" + clone.Length); Debug.Assert(indexStart + termOffset + numTermBytes < clone.Length); outerInstance.outerInstance.termBytes.Copy(clone, numTermBytes); termOffsetUpto += numTermBytes; upto++; if (upto == this.numIndexTerms) { break; } // skip terms: termsDictOffsetsIter.Next(); for (int i = 0; i < outerInstance.outerInstance.indexDivisor - 2; i++) { termOffsetsIter.Next(); termsDictOffsetsIter.Next(); } } termOffsetsM.Set(upto, termOffsetUpto); } finally { clone1.Dispose(); clone2.Dispose(); clone.Dispose(); } } } /// <summary>Returns approximate RAM bytes used.</summary> public long RamBytesUsed() { return ((termOffsets != null) ? termOffsets.RamBytesUsed() : 0) + ((termsDictOffsets != null) ? termsDictOffsets.RamBytesUsed() : 0); } } } public override FieldIndexEnum GetFieldEnum(FieldInfo fieldInfo) { FieldIndexData fieldData; if (!fields.TryGetValue(fieldInfo, out fieldData) || fieldData == null || fieldData.coreIndex == null) { return null; } else { return new IndexEnum(this, fieldData.coreIndex); } } protected override void Dispose(bool disposing) { if (disposing) { if (input != null && !indexLoaded) { input.Dispose(); } } } private void SeekDir(IndexInput input, long dirOffset) { if (version >= FixedGapTermsIndexWriter.VERSION_CHECKSUM) { input.Seek(input.Length - CodecUtil.FooterLength() - 8); dirOffset = input.ReadInt64(); } else if (version >= FixedGapTermsIndexWriter.VERSION_APPEND_ONLY) { input.Seek(input.Length - 8); dirOffset = input.ReadInt64(); } input.Seek(dirOffset); } public override long RamBytesUsed() { long sizeInBytes = ((termBytes != null) ? termBytes.RamBytesUsed() : 0) + ((termBytesReader != null) ? termBytesReader.RamBytesUsed() : 0); foreach (FieldIndexData entry in fields.Values) { sizeInBytes += entry.coreIndex.RamBytesUsed(); } return sizeInBytes; } } }
// 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.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService { private partial class WorkCoordinator { private const int MinimumDelayInMS = 50; private readonly Registration _registration; private readonly LogAggregator _logAggregator; private readonly IAsynchronousOperationListener _listener; private readonly IOptionService _optionService; private readonly CancellationTokenSource _shutdownNotificationSource; private readonly CancellationToken _shutdownToken; private readonly SimpleTaskQueue _eventProcessingQueue; // points to processor task private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor; private readonly SemanticChangeProcessor _semanticChangeProcessor; public WorkCoordinator( IAsynchronousOperationListener listener, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, Registration registration) { _logAggregator = new LogAggregator(); _registration = registration; _listener = listener; _optionService = _registration.GetService<IOptionService>(); _optionService.OptionChanged += OnOptionChanged; // event and worker queues _shutdownNotificationSource = new CancellationTokenSource(); _shutdownToken = _shutdownNotificationSource.Token; _eventProcessingQueue = new SimpleTaskQueue(TaskScheduler.Default); var activeFileBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS); var allFilesWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS); var entireProjectWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS); _documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor( listener, analyzerProviders, _registration, activeFileBackOffTimeSpanInMS, allFilesWorkerBackOffTimeSpanInMS, entireProjectWorkerBackOffTimeSpanInMS, _shutdownToken); var semanticBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS); var projectBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS); _semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpanInMS, projectBackOffTimeSpanInMS, _shutdownToken); // if option is on if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler)) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } } public int CorrelationId { get { return _registration.CorrelationId; } } public void Shutdown(bool blockingShutdown) { _optionService.OptionChanged -= OnOptionChanged; // detach from the workspace _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; // cancel any pending blocks _shutdownNotificationSource.Cancel(); _documentAndProjectWorkerProcessor.Shutdown(); SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator); if (blockingShutdown) { var shutdownTask = Task.WhenAll( _eventProcessingQueue.LastScheduledTask, _documentAndProjectWorkerProcessor.AsyncProcessorTask, _semanticChangeProcessor.AsyncProcessorTask); shutdownTask.Wait(TimeSpan.FromSeconds(5)); if (!shutdownTask.IsCompleted) { SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId); } } } private void OnOptionChanged(object sender, OptionChangedEventArgs e) { // if solution crawler got turned off or on. if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler) { var value = (bool)e.Value; if (value) { _registration.Workspace.WorkspaceChanged += OnWorkspaceChanged; _registration.Workspace.DocumentOpened += OnDocumentOpened; _registration.Workspace.DocumentClosed += OnDocumentClosed; } else { _registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged; _registration.Workspace.DocumentOpened -= OnDocumentOpened; _registration.Workspace.DocumentClosed -= OnDocumentClosed; } SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value); return; } // TODO: remove this once prototype is done // it is here just because it was convenient to add per workspace option change monitoring // for incremental analyzer if (e.Option == Diagnostics.InternalDiagnosticsOptions.UseDiagnosticEngineV2) { _documentAndProjectWorkerProcessor.ChangeDiagnosticsEngine((bool)e.Value); } ReanalyzeOnOptionChange(sender, e); } private void ReanalyzeOnOptionChange(object sender, OptionChangedEventArgs e) { // otherwise, let each analyzer decide what they want on option change ISet<DocumentId> set = null; foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers) { if (analyzer.NeedsReanalysisOnOptionChanged(sender, e)) { set = set ?? _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(); this.Reanalyze(analyzer, set); } } } public void Reanalyze(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds) { var asyncToken = _listener.BeginAsyncOperation("Reanalyze"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(analyzer, documentIds), _shutdownToken).CompletesAsyncOperation(asyncToken); SolutionCrawlerLogger.LogReanalyze(CorrelationId, analyzer, documentIds); } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { // guard us from cancellation try { ProcessEvents(args, _listener.BeginAsyncOperation("OnWorkspaceChanged")); } catch (OperationCanceledException oce) { if (NotOurShutdownToken(oce)) { throw; } // it is our cancellation, ignore } catch (AggregateException ae) { ae = ae.Flatten(); // If we had a mix of exceptions, don't eat it if (ae.InnerExceptions.Any(e => !(e is OperationCanceledException)) || ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken)) { // We had a cancellation with a different token, so don't eat it throw; } // it is our cancellation, ignore } } private bool NotOurShutdownToken(OperationCanceledException oce) { return oce.CancellationToken == _shutdownToken; } private void ProcessEvents(WorkspaceChangeEventArgs args, IAsyncToken asyncToken) { SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind); // TODO: add telemetry that record how much it takes to process an event (max, min, average and etc) switch (args.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: ProcessSolutionEvent(args, asyncToken); break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: ProcessProjectEvent(args, asyncToken); break; case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: ProcessDocumentEvent(args, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnDocumentOpened(object sender, DocumentEventArgs e) { var asyncToken = _listener.BeginAsyncOperation("OnDocumentOpened"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentOpened), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void OnDocumentClosed(object sender, DocumentEventArgs e) { var asyncToken = _listener.BeginAsyncOperation("OnDocumentClosed"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentClosed), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.DocumentAdded: EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.DocumentRemoved: EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, asyncToken); break; case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: // If an additional file has changed we need to reanalyze the entire project. EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessProjectEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.ProjectAdded: OnProjectAdded(e.NewSolution.GetProject(e.ProjectId)); EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.ProjectRemoved: EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: OnSolutionAdded(e.NewSolution); EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.SolutionRemoved: EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionCleared: EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnSolutionAdded(Solution solution) { var asyncToken = _listener.BeginAsyncOperation("OnSolutionAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(solution); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void OnProjectAdded(Project project) { var asyncToken = _listener.BeginAsyncOperation("OnProjectAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(project); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, IAsyncToken asyncToken) { // document changed event is the special one. _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private async Task EnqueueWorkItemAsync(Document document, InvocationReasons invocationReasons, SyntaxNode changedMember = null) { // we are shutting down _shutdownToken.ThrowIfCancellationRequested(); var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false); var currentMember = GetSyntaxPath(changedMember); // call to this method is serialized. and only this method does the writing. _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(document.Id, document.Project.Language, invocationReasons, isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem"))); // enqueue semantic work planner if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { // must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later. // due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual. _semanticChangeProcessor.Enqueue(document, currentMember); } } private SyntaxPath GetSyntaxPath(SyntaxNode changedMember) { // using syntax path might be too expansive since it will be created on every keystroke. // but currently, we have no other way to track a node between two different tree (even for incrementally parsed one) if (changedMember == null) { return null; } return new SyntaxPath(changedMember); } private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons) { foreach (var documentId in project.DocumentIds) { var document = project.GetDocument(documentId); await EnqueueWorkItemAsync(document, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds) { var solution = _registration.CurrentSolution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); if (document == null) { continue; } var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false); _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(documentId, document.Project.Language, InvocationReasons.Reanalyze, isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem"))); } } private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution) { var solutionChanges = newSolution.GetChanges(oldSolution); // TODO: Async version for GetXXX methods? foreach (var addedProject in solutionChanges.GetAddedProjects()) { await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var projectChanges in solutionChanges.GetProjectChanges()) { await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedProject in solutionChanges.GetRemovedProjects()) { await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges) { await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false); foreach (var addedDocumentId in projectChanges.GetAddedDocuments()) { await EnqueueWorkItemAsync(projectChanges.NewProject.GetDocument(addedDocumentId), InvocationReasons.DocumentAdded).ConfigureAwait(false); } foreach (var changedDocumentId in projectChanges.GetChangedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(changedDocumentId), projectChanges.NewProject.GetDocument(changedDocumentId)) .ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedDocumentId in projectChanges.GetRemovedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(removedDocumentId), InvocationReasons.DocumentRemoved).ConfigureAwait(false); } } private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges) { var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; // TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document? var projectConfigurationChange = InvocationReasons.Empty; if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged); } if (projectChanges.GetAddedMetadataReferences().Any() || projectChanges.GetAddedProjectReferences().Any() || projectChanges.GetAddedAnalyzerReferences().Any() || projectChanges.GetRemovedMetadataReferences().Any() || projectChanges.GetRemovedProjectReferences().Any() || projectChanges.GetRemovedAnalyzerReferences().Any() || !object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) || !object.Equals(oldProject.AssemblyName, newProject.AssemblyName) || !object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged); } if (!projectConfigurationChange.IsEmpty) { await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false); } } private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument) { var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>(); if (differenceService != null) { var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false); if (differenceResult != null) { await EnqueueWorkItemAsync(newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false); } } } private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons) { var document = solution.GetDocument(documentId); return EnqueueWorkItemAsync(document, invocationReasons); } private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons) { var project = solution.GetProject(projectId); return EnqueueWorkItemAsync(project, invocationReasons); } private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons) { foreach (var projectId in solution.ProjectIds) { await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false); } } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId) { var oldProject = oldSolution.GetProject(projectId); var newProject = newSolution.GetProject(projectId); await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false); } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId) { var oldProject = oldSolution.GetProject(documentId.ProjectId); var newProject = newSolution.GetProject(documentId.ProjectId); await EnqueueWorkItemAsync(oldProject.GetDocument(documentId), newProject.GetDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false); } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> workers) { var solution = _registration.CurrentSolution; var list = new List<WorkItem>(); foreach (var project in solution.Projects) { foreach (var document in project.Documents) { list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, false, EmptyAsyncToken.Instance)); } } _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(workers, list); } internal void WaitUntilCompletion_ForTestingPurposesOnly() { _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(); } } } }
#region Header // // Copyright 2003-2019 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // #endregion // Header using System; using System.Diagnostics; using System.Windows.Forms; using System.Drawing; using System.Drawing.Printing; using System.Reflection; using Autodesk.Revit.DB; namespace RevitLookup.Snoop { public class Utils { public Utils() { } public static void Display(ListView lvCur, Snoop.Collectors.Collector snoopCollector) { lvCur.BeginUpdate(); lvCur.Items.Clear(); Font oldFont = lvCur.Font; FontStyle newStyle = lvCur.Font.Style ^ FontStyle.Bold; Font boldFont = new Font(oldFont, newStyle); for (int i = 0; i < snoopCollector.Data().Count; i++) { Snoop.Data.Data tmpSnoopData = (Snoop.Data.Data)snoopCollector.Data()[i]; // if it is a class separator, then color the background differently // and don't add a SubItem for the "Field" value if (tmpSnoopData.IsSeparator) { ListViewItem lvItem = new ListViewItem(tmpSnoopData.StrValue()); if (tmpSnoopData is Snoop.Data.ClassSeparator) lvItem.BackColor = System.Drawing.Color.LightBlue; else lvItem.BackColor = System.Drawing.Color.WhiteSmoke; lvItem.Tag = tmpSnoopData; lvCur.Items.Add(lvItem); } else { ListViewItem lvItem = new ListViewItem(tmpSnoopData.Label); lvItem.SubItems.Add(tmpSnoopData.StrValue()); if (tmpSnoopData.IsError) { ListViewItem.ListViewSubItem sItem = (ListViewItem.ListViewSubItem)lvItem.SubItems[0]; sItem.ForeColor = System.Drawing.Color.Red; } if (tmpSnoopData.HasDrillDown) { ListViewItem.ListViewSubItem sItem = (ListViewItem.ListViewSubItem)lvItem.SubItems[0]; sItem.Font = boldFont; } lvItem.Tag = tmpSnoopData; lvCur.Items.Add(lvItem); } } lvCur.EndUpdate(); } public static void DataItemSelected(ListView lvCur) { Debug.Assert((lvCur.SelectedItems.Count > 1) == false); if (lvCur.SelectedItems.Count != 0) { Snoop.Data.Data tmpSnoopData = (Snoop.Data.Data)lvCur.SelectedItems[0].Tag; tmpSnoopData.DrillDown(); } } public static void BrowseReflection(Object obj) { if (obj == null) { MessageBox.Show("Object == null"); return; } RevitLookup.Snoop.Forms.GenericPropGrid pgForm = new RevitLookup.Snoop.Forms.GenericPropGrid(obj); pgForm.Text = string.Format("Object Data (System.Type = {0})", obj.GetType().FullName); pgForm.ShowDialog(); } public static string ObjToTypeStr(System.Object obj) { if (obj == null) return "< null >"; Autodesk.Revit.DB.Element elem = obj as Autodesk.Revit.DB.Element; if (elem != null) { var nameStr = (elem.Name == string.Empty) ? "???" : elem.Name; // use "???" if no name is set return string.Format("< {0} {1} {2,4} >", obj.GetType().Name, nameStr, elem.Id.IntegerValue.ToString()); } return GetNamedObjectLabel(obj) ?? GetParameterObjectLabel(obj) ?? string.Format("< {0} >", obj.GetType().Name); } private static string GetNamedObjectLabel(object obj) { var nameProperty = obj .GetType() .GetProperty("Name", BindingFlags.Instance); if (nameProperty != null) { var propertyValue = nameProperty.GetValue(obj) as string; return string.Format("< {0} {1} >", obj.GetType().Name, string.IsNullOrEmpty(propertyValue) ? "???" : propertyValue); } return null; } public static string GetParameterObjectLabel(object obj) { var parameter = obj as Parameter; if (parameter == null) return null; return parameter.Definition.Name; } public static string ObjToLabelStr(System.Object obj) { if (obj == null) return "< null >"; Autodesk.Revit.DB.Element elem = obj as Autodesk.Revit.DB.Element; if (elem != null) { // TBD: Exceptions are thrown in certain cases when accessing the Name property. // Eg. for the RoomTag object. So we will catch the exception and display the exception message // arj - 1/23/07 try { string nameStr = (elem.Name == string.Empty) ? "???" : elem.Name; // use "???" if no name is set return string.Format("< {0} {1} >", nameStr, elem.Id.IntegerValue.ToString()); } catch (System.InvalidOperationException ex) { return string.Format("< {0} {1} >", null, ex.Message); } } return GetNamedObjectLabel(obj) ?? GetParameterObjectLabel(obj) ?? string.Format("< {0} >", obj.GetType().Name); } public static void CopyToClipboard(ListView lv) { if (lv.Items.Count == 0) { Clipboard.Clear(); return; } //First find the longest piece of text in the Field column // Int32 maxField = 0; Int32 maxValue = 0; foreach (ListViewItem item in lv.Items) { if (item.Text.Length > maxField) { maxField = item.Text.Length; } if ((item.SubItems.Count > 1) && (item.SubItems[1].Text.Length > maxValue)) { maxValue = item.SubItems[1].Text.Length; } } String headerFormat = String.Format("{{0,{0}}}----{1}\r\n", maxField, new String('-', maxValue)); String tabbedFormat = String.Format("{{0,{0}}} {{1}}\r\n", maxField); System.Text.StringBuilder bldr = new System.Text.StringBuilder(); foreach (ListViewItem item in lv.Items) { if (item.SubItems.Count == 1) { String tmp = item.Text; if (item.Text.Length < maxField) { tmp = item.Text.PadLeft(item.Text.Length + (maxField - item.Text.Length), '-'); } bldr.AppendFormat(headerFormat, tmp); } else if (item.SubItems.Count > 1) { bldr.AppendFormat(tabbedFormat, item.Text, item.SubItems[1].Text); } } String txt = bldr.ToString(); if (String.IsNullOrEmpty(txt) == false) { Clipboard.SetDataObject(txt); } } public static void CopyToClipboard(ListViewItem lvItem, Boolean multipleItems) { if (lvItem.SubItems.Count > 1) { if (!multipleItems) { Clipboard.SetDataObject(lvItem.SubItems[1].Text); } else { Clipboard.SetDataObject(lvItem.SubItems[0].Text + " => " + lvItem.SubItems[1].Text); } } else { Clipboard.Clear(); } } public static Int32 Print(String title, ListView lv, System.Drawing.Printing.PrintPageEventArgs e, Int32 maxFieldWidth, Int32 maxValueWidth, Int32 currentItem) { Single linesPerPage = 0; Single yPos = 0; Single leftMargin = e.MarginBounds.Left + ((e.MarginBounds.Width - (maxFieldWidth + maxValueWidth)) / 2); Single topMargin = e.MarginBounds.Top; Single fontHeight = lv.Font.GetHeight(e.Graphics); Int32 count = 0; String line = null; ListViewItem item; SolidBrush backgroundBrush; SolidBrush subbackgroundBrush; SolidBrush textBrush; RectangleF rect; StringFormat centerFormat = new StringFormat(); StringFormat fieldFormat = new StringFormat(); StringFormat valueFormat = new StringFormat(); centerFormat.Alignment = StringAlignment.Center; fieldFormat.Alignment = HorizontalAlignmentToStringAligment(lv.Columns[0].TextAlign); valueFormat.Alignment = HorizontalAlignmentToStringAligment(lv.Columns[1].TextAlign); //Draw the title of the list. // rect = new RectangleF(leftMargin, topMargin, maxFieldWidth + maxValueWidth, fontHeight); e.Graphics.DrawString(title, lv.Font, Brushes.Black, rect, centerFormat); //Update the count so that we are giving ourselves a line between the title and the list. // count = 2; //Calculate the number of lines per page // linesPerPage = e.MarginBounds.Height / fontHeight; while ((count < linesPerPage) && (currentItem < lv.Items.Count)) { item = lv.Items[currentItem]; line = item.Text; yPos = topMargin + (count * fontHeight); backgroundBrush = new SolidBrush(item.BackColor); textBrush = new SolidBrush(item.ForeColor); rect = new RectangleF(leftMargin, yPos, maxFieldWidth, fontHeight); e.Graphics.FillRectangle(backgroundBrush, rect); e.Graphics.DrawRectangle(Pens.Black, rect.X, rect.Y, rect.Width, rect.Height); //Draw the field portion of the list view item // e.Graphics.DrawString(" " + item.Text, item.Font, textBrush, rect, fieldFormat); //Draw the value portion of the list view item // rect = new RectangleF(leftMargin + maxFieldWidth, yPos, maxValueWidth, fontHeight); if (item.SubItems.Count > 1) { subbackgroundBrush = new SolidBrush(item.SubItems[1].BackColor); e.Graphics.FillRectangle(subbackgroundBrush, rect); e.Graphics.DrawString(" " + item.SubItems[1].Text, item.Font, textBrush, rect, valueFormat); } else { e.Graphics.FillRectangle(backgroundBrush, rect); } e.Graphics.DrawRectangle(Pens.Black, rect.X, rect.Y, rect.Width, rect.Height); count++; currentItem++; } if (currentItem < lv.Items.Count) { e.HasMorePages = true; } else { e.HasMorePages = false; currentItem = 0; } return currentItem; } public static StringAlignment HorizontalAlignmentToStringAligment(HorizontalAlignment ha) { switch (ha) { case HorizontalAlignment.Center: return StringAlignment.Center; case HorizontalAlignment.Left: return StringAlignment.Near; case HorizontalAlignment.Right: return StringAlignment.Far; default: return StringAlignment.Near; } } public static Int32[] GetMaximumColumnWidths(ListView lv) { Int32 index = 0; Int32[] widthArray = new Int32[lv.Columns.Count]; foreach (ColumnHeader col in lv.Columns) { widthArray[index] = col.Width; index++; } System.Drawing.Graphics g = lv.CreateGraphics(); Int32 offset = Convert.ToInt32(Math.Ceiling(g.MeasureString(" ", lv.Font).Width)); Int32 width = 0; foreach (ListViewItem item in lv.Items) { index = 0; foreach (ListViewItem.ListViewSubItem subItem in item.SubItems) { width = Convert.ToInt32(Math.Ceiling(g.MeasureString(subItem.Text, item.Font).Width)) + offset; if (width > widthArray[index]) { widthArray[index] = width; } index++; } } g.Dispose(); return widthArray; } public static TreeNode GetRootNode(TreeNode node) { if (node.Parent == null) { return node; } return GetRootNode(node.Parent); } public static String GetPrintDocumentName(TreeNode node) { TreeNode root = GetRootNode(node); String str = root.Tag as String; if (str != null) { return System.IO.Path.GetFileNameWithoutExtension((String)root.Tag); } return String.Empty; } public static void UpdatePrintSettings(PrintDocument doc, TreeView tv, ListView lv, ref Int32[] widthArray) { if (tv.SelectedNode == null) { return; } doc.DocumentName = Utils.GetPrintDocumentName(tv.SelectedNode); widthArray = Utils.GetMaximumColumnWidths(lv); } public static void UpdatePrintSettings(ListView lv, ref Int32[] widthArray) { widthArray = Utils.GetMaximumColumnWidths(lv); } public static void PrintMenuItemClick(PrintDialog dlg, TreeView tv) { if (tv.SelectedNode == null) { MessageBox.Show(tv.Parent, "Please select a node in the tree to print.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (dlg.ShowDialog(tv.Parent) == DialogResult.OK) { dlg.Document.Print(); } } public static void PrintMenuItemClick(PrintDialog dlg) { dlg.Document.Print(); } public static void PrintPreviewMenuItemClick(PrintPreviewDialog dlg, TreeView tv) { if (tv.SelectedNode == null) { MessageBox.Show(tv.Parent, "Please select a node in the tree to print.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } dlg.ShowDialog(tv.Parent); } public static void PrintPreviewMenuItemClick(PrintPreviewDialog dlg, ListView lv) { dlg.ShowDialog(lv.Parent); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.DataFactories; using Microsoft.Azure.Management.DataFactories.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataFactories { /// <summary> /// Operations for managing data factories. /// </summary> internal partial class DataFactoryOperations : IServiceOperations<DataPipelineManagementClient>, IDataFactoryOperations { /// <summary> /// Initializes a new instance of the DataFactoryOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DataFactoryOperations(DataPipelineManagementClient client) { this._client = client; } private DataPipelineManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.DataFactories.DataPipelineManagementClient. /// </summary> public DataPipelineManagementClient Client { get { return this._client; } } /// <summary> /// Create or update a data factory. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public async Task<DataFactoryCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.DataFactory != null) { if (parameters.DataFactory.Location == null) { throw new ArgumentNullException("parameters.DataFactory.Location"); } if (parameters.DataFactory.Name == null) { throw new ArgumentNullException("parameters.DataFactory.Name"); } if (parameters.DataFactory.Name != null && parameters.DataFactory.Name.Length > 63) { throw new ArgumentOutOfRangeException("parameters.DataFactory.Name"); } if (Regex.IsMatch(parameters.DataFactory.Name, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("parameters.DataFactory.Name"); } } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; if (parameters.DataFactory != null && parameters.DataFactory.Name != null) { url = url + Uri.EscapeDataString(parameters.DataFactory.Name); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject dataFactoryCreateOrUpdateParametersValue = new JObject(); requestDoc = dataFactoryCreateOrUpdateParametersValue; if (parameters.DataFactory != null) { if (parameters.DataFactory.Id != null) { dataFactoryCreateOrUpdateParametersValue["id"] = parameters.DataFactory.Id; } dataFactoryCreateOrUpdateParametersValue["name"] = parameters.DataFactory.Name; dataFactoryCreateOrUpdateParametersValue["location"] = parameters.DataFactory.Location; if (parameters.DataFactory.Tags != null) { if (parameters.DataFactory.Tags is ILazyCollection == false || ((ILazyCollection)parameters.DataFactory.Tags).IsInitialized) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.DataFactory.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } dataFactoryCreateOrUpdateParametersValue["tags"] = tagsDictionary; } } if (parameters.DataFactory.Properties != null) { JObject propertiesValue = new JObject(); dataFactoryCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.DataFactory.Properties.ProvisioningState != null) { propertiesValue["provisioningState"] = parameters.DataFactory.Properties.ProvisioningState; } if (parameters.DataFactory.Properties.ErrorMessage != null) { propertiesValue["errorMessage"] = parameters.DataFactory.Properties.ErrorMessage; } } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataFactoryCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactory = dataFactoryInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); dataFactoryInstance.Tags.Add(tagsKey2, tagsValue2); } } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue2["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue2["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } result.Location = url; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create or update a data factory. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public async Task<DataFactoryCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { DataPipelineManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); DataFactoryCreateOrUpdateResponse response = await client.DataFactories.BeginCreateOrUpdateAsync(resourceGroupName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); DataFactoryCreateOrUpdateResponse result = await client.DataFactories.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); int delayInSeconds = 5; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.DataFactories.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); delayInSeconds = 5; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Delete a data factory instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a data factory instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get data factory operation response. /// </returns> public async Task<DataFactoryGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataFactoryGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactory = dataFactoryInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.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); dataFactoryInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get 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 Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public async Task<DataFactoryCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetCreateOrUpdateStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); httpRequest.Headers.Add("x-ms-version", "2015-01-01-preview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataFactoryCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactory = dataFactoryInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.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); dataFactoryInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } result.Location = url; if (result.DataFactory != null && result.DataFactory.Properties != null && result.DataFactory.Properties.ProvisioningState == "Failed") { result.Status = OperationStatus.Failed; } if (result.DataFactory != null && result.DataFactory.Properties != null && result.DataFactory.Properties.ProvisioningState == "Succeeded") { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the first page of data factory instances with the link to the /// next page. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factories. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data factories operation response. /// </returns> public async Task<DataFactoryListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataFactoryListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactories.Add(dataFactoryInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dataFactoryInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the next page of data factory instances with the link to the /// next page. /// </summary> /// <param name='nextLink'> /// Required. The url to the next data factories page. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data factories operation response. /// </returns> public async Task<DataFactoryListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataFactoryListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataFactoryListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataFactory dataFactoryInstance = new DataFactory(); result.DataFactories.Add(dataFactoryInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataFactoryInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataFactoryInstance.Name = nameInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataFactoryInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dataFactoryInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataFactoryProperties propertiesInstance = new DataFactoryProperties(); dataFactoryInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; namespace Microsoft.Research.CodeAnalysis.Inference { public class CallerInvariantDB<Method> { [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.db != null); } private readonly List<CallInvariant> db; public CallerInvariantDB() { this.db = new List<CallInvariant>(); } public void Notify(Method callee, Method caller, int paramPosition, Predicate info) { this.db.Add(new CallInvariant(callee, caller, paramPosition, info)); } public IEnumerable<IGrouping<int, CallInvariant>> GetCalleeInvariantsForAMethod(Method callee) { return this.db.Where(cInv => cInv.Callee.Equals(callee)).GroupBy(cInv => cInv.ParamPosition); } public IEnumerable<CallInvariant> GetCalleeInvariantsForAMethod(Method callee, int pos) { Contract.Requires(pos >= 0); return this.db.Where(cInv => cInv.ParamPosition == pos && cInv.Callee.Equals(callee)); } public IEnumerable<CallInvariant> GetCalleeInvariantsInAMethod(Method caller) { return this.db.Where(cInv => cInv.Caller.Equals(caller)); } public void SuggestCallInvariants(IOutput output) { Contract.Requires(output != null); var groupedByCallees = this.db.GroupBy(cInv => cInv.Callee); output.WriteLine("Inferred Caller invariants"); foreach (var callee in groupedByCallees) { output.WriteLine("Method: {0}", callee.Key); var groupedByPosition = callee.GroupBy(cInv => cInv.ParamPosition); foreach (var inv in groupedByPosition) { var nTops = inv.Count(cInv => cInv.Predicate.Equals(PredicateTop.Value)); var nNotNull = inv.Count(cInv => cInv.Predicate.Equals(PredicateNullness.NotNull)); var nNull = inv.Count(cInv => cInv.Predicate.Equals(PredicateNullness.Null)); var tot = (double)(nTops + nNotNull + nNull); if (tot == 0) continue; output.WriteLine(" Position: {0} (Top:{1}-{4:0.00}%, NN:{2}-{5:0.00}%, N:{3}-{6:0.00}%)", inv.Key, nTops, nNotNull, nNull, nTops/tot, nNotNull/tot, nNull/tot); /* foreach (var value in inv) { output.WriteLine(" Value: {0}", value.ToString()); } */ } } } #region CallInvariant public class CallInvariant { public readonly Method Callee; public readonly Method Caller; public readonly int ParamPosition; public readonly Predicate Predicate; public CallInvariant(Method callee, Method caller, int paramPosition, Predicate info) { Contract.Requires(paramPosition >= 0); Contract.Requires(info != null); this.Callee = callee; this.Caller = caller; this.ParamPosition = paramPosition; this.Predicate = info; } public override string ToString() { return string.Format("<{0}, {1}, {2}, {3}>", this.Callee, this.Caller, this.ParamPosition, this.Predicate); } #endregion } } [ContractClass(typeof(PredicateContracts))] public abstract class Predicate { abstract public Predicate JoinWith(Predicate other); } #region Contracts [ContractClassFor(typeof(Predicate))] abstract class PredicateContracts : Predicate { public override Predicate JoinWith(Predicate other) { Contract.Requires(other != null); Contract.Ensures(Contract.Result<Predicate>() != null); return null; } } #endregion public class PredicateTop : Predicate { public static PredicateTop Value { get { return new PredicateTop(); } } private PredicateTop() { } public override Predicate JoinWith(Predicate other) { return this; } public override bool Equals(object obj) { return obj is PredicateTop; } public override int GetHashCode() { return 1; } public override string ToString() { return "top"; } } public class PredicateNullness : Predicate { public enum Kind {Null, NotNull} private readonly Kind value; public static PredicateNullness Null { get { return new PredicateNullness(Kind.Null); } } public static PredicateNullness NotNull { get { return new PredicateNullness(Kind.NotNull); } } private PredicateNullness(Kind kind) { this.value = kind; } public override Predicate JoinWith(Predicate other) { var right = other as PredicateNullness; if (other != null) { if (this.value == right.value) { return this; } } return PredicateTop.Value; } public override bool Equals(object obj) { var other = obj as PredicateNullness; if (other != null) { return this.value == other.value; } return false; } public override int GetHashCode() { return (int)this.value; } public override string ToString() { return this.value.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.Xml; using System.Xml.Schema; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Security; using System.Runtime.CompilerServices; namespace System.Runtime.Serialization { #if USE_REFEMIT || uapaot public delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces); public delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); public delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); public sealed class XmlFormatReaderGenerator #else internal delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces); internal delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); internal delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); internal sealed class XmlFormatReaderGenerator #endif { private CriticalHelper _helper; public XmlFormatReaderGenerator() { _helper = new CriticalHelper(); } public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { return _helper.GenerateClassReader(classContract); } public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { return _helper.GenerateCollectionReader(collectionContract); } public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { return _helper.GenerateGetOnlyCollectionReader(collectionContract); } /// <SecurityNote> /// Review - handles all aspects of IL generation including initializing the DynamicMethod. /// changes to how IL generated could affect how data is deserialized and what gets access to data, /// therefore we mark it for review so that changes to generation logic are reviewed. /// </SecurityNote> private class CriticalHelper { #if !uapaot private CodeGenerator _ilg; private LocalBuilder _objectLocal; private Type _objectType; private ArgBuilder _xmlReaderArg; private ArgBuilder _contextArg; private ArgBuilder _memberNamesArg; private ArgBuilder _memberNamespacesArg; private ArgBuilder _collectionContractArg; #endif #if uapaot [RemovableFeature(ReflectionBasedSerializationFeature.Name)] #endif private XmlFormatClassReaderDelegate CreateReflectionXmlClassReader(ClassDataContract classContract) { return new ReflectionXmlClassReader(classContract).ReflectionReadClass; } public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { return CreateReflectionXmlClassReader(classContract); } #if uapaot else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { return CreateReflectionXmlClassReader(classContract); } #endif else { #if uapaot throw new InvalidOperationException("Cannot generate class reader"); #else _ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { _ilg.BeginMethod("Read" + classContract.StableName.Name + "FromXml", Globals.TypeOfXmlFormatClassReaderDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); CreateObject(classContract); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); InvokeOnDeserializing(classContract); LocalBuilder objectId = null; if (HasFactoryMethod(classContract)) { objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); } if (classContract.IsISerializable) { ReadISerializable(classContract); } else { ReadClass(classContract); } bool isFactoryType = InvokeFactoryMethod(classContract, objectId); if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom(classContract.UnderlyingType)) { _ilg.Call(_objectLocal, XmlFormatGeneratorStatics.OnDeserializationMethod, null); } InvokeOnDeserialized(classContract); if (objectId == null) { _ilg.Load(_objectLocal); // Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization. // DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter) { _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfDateTimeOffsetAdapter); _ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetMethod); _ilg.ConvertValue(Globals.TypeOfDateTimeOffset, _ilg.CurrentMethod.ReturnType); } //Copy the KeyValuePairAdapter<K,T> to a KeyValuePair<K,T>. else if (classContract.IsKeyValuePairAdapter) { _ilg.Call(classContract.GetKeyValuePairMethodInfo); _ilg.ConvertValue(Globals.TypeOfKeyValuePair.MakeGenericType(classContract.KeyValuePairGenericArguments), _ilg.CurrentMethod.ReturnType); } else { _ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType); } } return (XmlFormatClassReaderDelegate)_ilg.EndMethod(); #endif } } #if uapaot [RemovableFeature(ReflectionBasedSerializationFeature.Name)] #endif private XmlFormatCollectionReaderDelegate CreateReflectionXmlCollectionReader() { return new ReflectionXmlCollectionReader().ReflectionReadCollection; } public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { return CreateReflectionXmlCollectionReader(); } #if uapaot else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { return CreateReflectionXmlCollectionReader(); } #endif else { #if uapaot throw new InvalidOperationException("Cannot generate class reader"); #else _ilg = GenerateCollectionReaderHelper(collectionContract, false /*isGetOnlyCollection*/); ReadCollection(collectionContract); _ilg.Load(_objectLocal); _ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType); return (XmlFormatCollectionReaderDelegate)_ilg.EndMethod(); #endif } } #if uapaot [RemovableFeature(ReflectionBasedSerializationFeature.Name)] #endif private XmlFormatGetOnlyCollectionReaderDelegate CreateReflectionReadGetOnlyCollectionReader() { return new ReflectionXmlCollectionReader().ReflectionReadGetOnlyCollection; } public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { return CreateReflectionReadGetOnlyCollectionReader(); } #if uapaot else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { return CreateReflectionReadGetOnlyCollectionReader(); } #endif else { #if uapaot throw new InvalidOperationException("Cannot generate class reader"); #else _ilg = GenerateCollectionReaderHelper(collectionContract, true /*isGetOnlyCollection*/); ReadGetOnlyCollection(collectionContract); return (XmlFormatGetOnlyCollectionReaderDelegate)_ilg.EndMethod(); #endif } } #if !uapaot private CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract collectionContract, bool isGetOnlyCollection) { _ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForRead(null); try { if (isGetOnlyCollection) { _ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + "IsGetOnly", Globals.TypeOfXmlFormatGetOnlyCollectionReaderDelegate, memberAccessFlag); } else { _ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + string.Empty, Globals.TypeOfXmlFormatCollectionReaderDelegate, memberAccessFlag); } } catch (SecurityException securityException) { if (memberAccessFlag) { collectionContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); _collectionContractArg = _ilg.GetArg(4); return _ilg; } private void InitArgs() { _xmlReaderArg = _ilg.GetArg(0); _contextArg = _ilg.GetArg(1); _memberNamesArg = _ilg.GetArg(2); _memberNamespacesArg = _ilg.GetArg(3); } private void CreateObject(ClassDataContract classContract) { Type type = _objectType = classContract.UnderlyingType; if (type.IsValueType && !classContract.IsNonAttributedType) type = Globals.TypeOfValueType; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); if (classContract.UnderlyingType == Globals.TypeOfDBNull) { _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")); _ilg.Stloc(_objectLocal); } else if (classContract.IsNonAttributedType) { if (type.IsValueType) { _ilg.Ldloca(_objectLocal); _ilg.InitObj(type); } else { _ilg.New(classContract.GetNonAttributedTypeConstructor()); _ilg.Stloc(_objectLocal); } } else { _ilg.Call(null, XmlFormatGeneratorStatics.GetUninitializedObjectMethod, DataContract.GetIdForInitialization(classContract)); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(_objectLocal); } } private void InvokeOnDeserializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserializing(classContract.BaseContract); if (classContract.OnDeserializing != null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserializing); } } private void InvokeOnDeserialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserialized(classContract.BaseContract); if (classContract.OnDeserialized != null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserialized); } } private bool HasFactoryMethod(ClassDataContract classContract) { return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType); } private bool InvokeFactoryMethod(ClassDataContract classContract, LocalBuilder objectId) { if (HasFactoryMethod(classContract)) { _ilg.Load(_contextArg); _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, Globals.TypeOfIObjectReference); _ilg.Load(objectId); _ilg.Call(XmlFormatGeneratorStatics.GetRealObjectMethod); _ilg.ConvertValue(Globals.TypeOfObject, _ilg.CurrentMethod.ReturnType); return true; } return false; } private void ReadClass(ClassDataContract classContract) { if (classContract.HasExtensionData) { LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); _ilg.New(XmlFormatGeneratorStatics.ExtensionDataObjectCtor); _ilg.Store(extensionDataLocal); ReadMembers(classContract, extensionDataLocal); ClassDataContract currentContract = classContract; while (currentContract != null) { MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod; if (extensionDataSetMethod != null) _ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal); currentContract = currentContract.BaseContract; } } else { ReadMembers(classContract, null /*extensionDataLocal*/); } } private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal) { int memberCount = classContract.MemberNames.Length; _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount); LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1); int firstRequiredMember; bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember); bool hasRequiredMembers = (firstRequiredMember < memberCount); LocalBuilder requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null; object forReadElements = _ilg.For(null, null, null); _ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg); _ilg.IfFalseBreak(forReadElements); if (hasRequiredMembers) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexWithRequiredMembersMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, requiredIndexLocal, extensionDataLocal); else _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, extensionDataLocal); Label[] memberLabels = _ilg.Switch(memberCount); ReadMembers(classContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal); _ilg.EndSwitch(); _ilg.EndFor(); if (hasRequiredMembers) { _ilg.If(requiredIndexLocal, Cmp.LessThan, memberCount); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMissingExceptionMethod, _xmlReaderArg, memberIndexLocal, requiredIndexLocal, _memberNamesArg); _ilg.EndIf(); } } private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder requiredIndexLocal) { int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember dataMember = classContract.Members[i]; Type memberType = dataMember.MemberType; _ilg.Case(memberLabels[memberCount], dataMember.Name); if (dataMember.IsRequired) { int nextRequiredIndex = memberCount + 1; for (; nextRequiredIndex < requiredMembers.Length; nextRequiredIndex++) if (requiredMembers[nextRequiredIndex]) break; _ilg.Set(requiredIndexLocal, nextRequiredIndex); } LocalBuilder value = null; if (dataMember.IsGetOnlyCollection) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(dataMember.MemberInfo); value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value"); _ilg.Stloc(value); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value); ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace); } else { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetCollectionMemberInfoMethod); value = ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace); _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Ldloc(value); _ilg.StoreMember(dataMember.MemberInfo); } #if FEATURE_LEGACYNETCF // The DataContractSerializer in the full framework doesn't support unordered elements: // deserialization will fail if the data members in the XML are not sorted alphabetically. // But the NetCF DataContractSerializer does support unordered element. To maintain compatibility // with Mango we always search for the member from the beginning of the member list. // We set memberIndexLocal to -1 because GetMemberIndex always starts from memberIndex+1. if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) ilg.Set(memberIndexLocal, (int)-1); else #endif // FEATURE_LEGACYNETCF _ilg.Set(memberIndexLocal, memberCount); _ilg.EndCase(); } return memberCount; } private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember) { int memberCount = contract.MemberNames.Length; bool[] requiredMembers = new bool[memberCount]; GetRequiredMembers(contract, requiredMembers); for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++) if (requiredMembers[firstRequiredMember]) break; return requiredMembers; } private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers) { int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers); List<DataMember> members = contract.Members; for (int i = 0; i < members.Count; i++, memberCount++) { requiredMembers[memberCount] = members[i].IsRequired; } return memberCount; } private void ReadISerializable(ClassDataContract classContract) { ConstructorInfo ctor = classContract.GetISerializableConstructor(); _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(ctor); } private LocalBuilder ReadValue(Type type, string name, string ns) { LocalBuilder value = _ilg.DeclareLocal(type, "valueRead"); LocalBuilder nullableValue = null; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { nullables++; type = type.GetGenericArguments()[0]; } PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type)); _ilg.Stloc(objectId); // Deserialize null _ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId); if (nullables != 0) { _ilg.LoadAddress(value); _ilg.InitObj(value.LocalType); } else if (type.IsValueType) ThrowValidationException(SR.Format(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type))); else { _ilg.Load(null); _ilg.Stloc(value); } // Deserialize value // Compare against Globals.NewObjectId, which is set to string.Empty _ilg.ElseIfIsEmptyString(objectId); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); if (type.IsValueType) { _ilg.IfNotIsEmptyString(objectId); ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type))); _ilg.EndIf(); } if (nullables != 0) { nullableValue = value; value = _ilg.DeclareLocal(type, "innerValueRead"); } if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { _ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod); _ilg.Stloc(value); if (!type.IsValueType) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value); } else { InternalDeserialize(value, type, name, ns); } // Deserialize ref _ilg.Else(); if (type.IsValueType) ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type))); else { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, ns); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(value); } _ilg.EndIf(); if (nullableValue != null) { _ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId); WrapNullableObject(value, nullableValue, nullables); _ilg.EndIf(); value = nullableValue; } } else { InternalDeserialize(value, type, name, ns); } return value; } private void InternalDeserialize(LocalBuilder value, Type type, string name, string ns) { _ilg.Load(_contextArg); _ilg.Load(_xmlReaderArg); Type declaredType = type; _ilg.Load(DataContract.GetId(declaredType.TypeHandle)); _ilg.Ldtoken(declaredType); _ilg.Load(name); _ilg.Load(ns); _ilg.Call(XmlFormatGeneratorStatics.InternalDeserializeMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(value); } private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue, int nullables) { Type innerType = innerValue.LocalType, outerType = outerValue.LocalType; _ilg.LoadAddress(outerValue); _ilg.Load(innerValue); for (int i = 1; i < nullables; i++) { Type type = Globals.TypeOfNullable.MakeGenericType(innerType); _ilg.New(type.GetConstructor(new Type[] { innerType })); innerType = type; } _ilg.Call(outerType.GetConstructor(new Type[] { innerType })); } private void ReadCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); ConstructorInfo constructor = collectionContract.Constructor; if (type.IsInterface) { switch (collectionContract.Kind) { case CollectionKind.GenericDictionary: type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments()); constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); break; case CollectionKind.Dictionary: type = Globals.TypeOfHashtable; constructor = XmlFormatGeneratorStatics.HashtableCtor; break; case CollectionKind.Collection: case CollectionKind.GenericCollection: case CollectionKind.Enumerable: case CollectionKind.GenericEnumerable: case CollectionKind.List: case CollectionKind.GenericList: type = itemType.MakeArrayType(); isArray = true; break; } } string itemName = collectionContract.ItemName; string itemNs = collectionContract.StableName.Namespace; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); if (!isArray) { if (type.IsValueType) { _ilg.Ldloca(_objectLocal); _ilg.InitObj(type); } else { _ilg.New(constructor); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); } } LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetArraySizeMethod); _ilg.Stloc(size); LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); bool canReadPrimitiveArray = false; if (isArray && TryReadPrimitiveArray(type, itemType, size)) { canReadPrimitiveArray = true; _ilg.IfNot(); } _ilg.If(size, Cmp.EqualTo, -1); LocalBuilder growingCollection = null; if (isArray) { growingCollection = _ilg.DeclareLocal(type, "growingCollection"); _ilg.NewArray(itemType, 32); _ilg.Stloc(growingCollection); } LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = _ilg.For(i, 0, int.MaxValue); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) { MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, ensureArraySizeMethod, growingCollection, i); _ilg.Stloc(growingCollection); _ilg.StoreArrayElement(growingCollection, i, value); } else StoreCollectionValue(_objectLocal, value, collectionContract); _ilg.Else(); IsEndElement(); _ilg.If(); _ilg.Break(forLoop); _ilg.Else(); HandleUnexpectedItemInCollection(i); _ilg.EndIf(); _ilg.EndIf(); _ilg.EndFor(); if (isArray) { MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, trimArraySizeMethod, growingCollection, i); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal); } _ilg.Else(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, size); if (isArray) { _ilg.NewArray(itemType, size); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); } LocalBuilder j = _ilg.DeclareLocal(Globals.TypeOfInt, "j"); _ilg.For(j, 0, size); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); LocalBuilder itemValue = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) _ilg.StoreArrayElement(_objectLocal, j, itemValue); else StoreCollectionValue(_objectLocal, itemValue, collectionContract); _ilg.Else(); HandleUnexpectedItemInCollection(j); _ilg.EndIf(); _ilg.EndFor(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg); _ilg.EndIf(); if (canReadPrimitiveArray) { _ilg.Else(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal); _ilg.EndIf(); } } private void ReadGetOnlyCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); string itemName = collectionContract.ItemName; string itemNs = collectionContract.StableName.Namespace; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(_objectLocal); //check that items are actually going to be deserialized into the collection IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); _ilg.If(_objectLocal, Cmp.EqualTo, null); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type); _ilg.Else(); LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); if (isArray) { _ilg.Load(_objectLocal); _ilg.Call(XmlFormatGeneratorStatics.GetArrayLengthMethod); _ilg.Stloc(size); } _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = _ilg.For(i, 0, int.MaxValue); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) { _ilg.If(size, Cmp.EqualTo, i); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowArrayExceededSizeExceptionMethod, size, type); _ilg.Else(); _ilg.StoreArrayElement(_objectLocal, i, value); _ilg.EndIf(); } else StoreCollectionValue(_objectLocal, value, collectionContract); _ilg.Else(); IsEndElement(); _ilg.If(); _ilg.Break(forLoop); _ilg.Else(); HandleUnexpectedItemInCollection(i); _ilg.EndIf(); _ilg.EndIf(); _ilg.EndFor(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg); _ilg.EndIf(); _ilg.EndIf(); } private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string readArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: readArrayMethod = "TryReadBooleanArray"; break; case TypeCode.DateTime: readArrayMethod = "TryReadDateTimeArray"; break; case TypeCode.Decimal: readArrayMethod = "TryReadDecimalArray"; break; case TypeCode.Int32: readArrayMethod = "TryReadInt32Array"; break; case TypeCode.Int64: readArrayMethod = "TryReadInt64Array"; break; case TypeCode.Single: readArrayMethod = "TryReadSingleArray"; break; case TypeCode.Double: readArrayMethod = "TryReadDoubleArray"; break; default: break; } if (readArrayMethod != null) { _ilg.Load(_xmlReaderArg); _ilg.Load(_contextArg); _ilg.Load(_memberNamesArg); _ilg.Load(_memberNamespacesArg); _ilg.Load(size); _ilg.Ldloca(_objectLocal); _ilg.Call(typeof(XmlReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)); return true; } return false; } private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs) { if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod); LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead"); _ilg.Load(_collectionContractArg); _ilg.Call(XmlFormatGeneratorStatics.GetItemContractMethod); _ilg.Load(_xmlReaderArg); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.ReadXmlValueMethod); _ilg.ConvertValue(Globals.TypeOfObject, itemType); _ilg.Stloc(value); return value; } else { return ReadValue(itemType, itemName, itemNs); } } private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract) { if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; if (keyValuePairContract == null) { DiagnosticUtility.DebugAssert("Failed to create contract for KeyValuePair type"); } DataMember keyMember = keyValuePairContract.Members[0]; DataMember valueMember = keyValuePairContract.Members[1]; LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name); LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name); _ilg.LoadAddress(value); _ilg.LoadMember(keyMember.MemberInfo); _ilg.Stloc(pairKey); _ilg.LoadAddress(value); _ilg.LoadMember(valueMember.MemberInfo); _ilg.Stloc(pairValue); _ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); } else { _ilg.Call(collection, collectionContract.AddMethod, value); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); } } private void HandleUnexpectedItemInCollection(LocalBuilder iterator) { IsStartElement(); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.SkipUnknownElementMethod, _xmlReaderArg); _ilg.Dec(iterator); _ilg.Else(); ThrowUnexpectedStateException(XmlNodeType.Element); _ilg.EndIf(); } private void IsStartElement(ArgBuilder nameArg, ArgBuilder nsArg) { _ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod2, nameArg, nsArg); } private void IsStartElement() { _ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod0); } private void IsEndElement() { _ilg.Load(_xmlReaderArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NodeTypeProperty); _ilg.Load(XmlNodeType.EndElement); _ilg.Ceq(); } private void ThrowUnexpectedStateException(XmlNodeType expectedState) { _ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, _xmlReaderArg); _ilg.Throw(); } private void ThrowValidationException(string msg, params object[] values) { { _ilg.Load(msg); } ThrowValidationException(); } private void ThrowValidationException() { //SerializationException is internal in SL and so cannot be directly invoked from DynamicMethod //So use helper function to create SerializationException _ilg.Call(XmlFormatGeneratorStatics.CreateSerializationExceptionMethod); _ilg.Throw(); } #endif } internal static object UnsafeGetUninitializedObject(Type type) { return FormatterServices.GetUninitializedObject(type); } /// <SecurityNote> /// Critical - Elevates by calling GetUninitializedObject which has a LinkDemand /// Safe - marked as such so that it's callable from transparent generated IL. Takes id as parameter which /// is guaranteed to be in internal serialization cache. /// </SecurityNote> #if USE_REFEMIT public static object UnsafeGetUninitializedObject(int id) #else internal static object UnsafeGetUninitializedObject(int id) #endif { var type = DataContract.GetDataContractForInitialization(id).TypeForInitialization; return UnsafeGetUninitializedObject(type); } } }
/* Copyright 2019 Esri 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 ESRI.ArcGIS.Geometry; using System; namespace MultiPatchExamples { public static class GeometryUtilities { private static object _missing = Type.Missing; public static void MakeZAware(IGeometry geometry) { IZAware zAware = geometry as IZAware; zAware.ZAware = true; } public static IVector3D ConstructVector3D(double xComponent, double yComponent, double zComponent) { IVector3D vector3D = new Vector3DClass(); vector3D.SetComponents(xComponent, yComponent, zComponent); return vector3D; } public static double GetRadians(double decimalDegrees) { return decimalDegrees * (Math.PI / 180); } public static IPoint ConstructPoint3D(double x, double y, double z) { IPoint point = ConstructPoint2D(x, y); point.Z = z; MakeZAware(point as IGeometry); return point; } public static IPoint ConstructPoint2D(double x, double y) { IPoint point = new PointClass(); point.X = x; point.Y = y; return point; } public static IGeometryCollection ConstructMultiPatchOutline(IGeometry multiPatchGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IGeometryCollection multiPatchGeometryCollection = multiPatchGeometry as IGeometryCollection; for (int i = 0; i < multiPatchGeometryCollection.GeometryCount; i++) { IGeometry geometry = multiPatchGeometryCollection.get_Geometry(i); switch(geometry.GeometryType) { case (esriGeometryType.esriGeometryTriangleStrip): outlineGeometryCollection.AddGeometryCollection(ConstructTriangleStripOutline(geometry)); break; case (esriGeometryType.esriGeometryTriangleFan): outlineGeometryCollection.AddGeometryCollection(ConstructTriangleFanOutline(geometry)); break; case (esriGeometryType.esriGeometryTriangles): outlineGeometryCollection.AddGeometryCollection(ConstructTrianglesOutline(geometry)); break; case (esriGeometryType.esriGeometryRing): outlineGeometryCollection.AddGeometry(ConstructRingOutline(geometry), ref _missing, ref _missing); break; default: throw new Exception("Unhandled Geometry Type. " + geometry.GeometryType); } } return outlineGeometryCollection; } public static IGeometryCollection ConstructTriangleStripOutline(IGeometry triangleStripGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IPointCollection triangleStripPointCollection = triangleStripGeometry as IPointCollection; // TriangleStrip: a linked strip of triangles, where every vertex (after the first two) completes a new triangle. // A new triangle is always formed by connecting the new vertex with its two immediate predecessors. for (int i = 2; i < triangleStripPointCollection.PointCount; i++) { IPointCollection outlinePointCollection = new PolylineClass(); outlinePointCollection.AddPoint(triangleStripPointCollection.get_Point(i - 2), ref _missing, ref _missing); outlinePointCollection.AddPoint(triangleStripPointCollection.get_Point(i - 1), ref _missing, ref _missing); outlinePointCollection.AddPoint(triangleStripPointCollection.get_Point(i), ref _missing, ref _missing); outlinePointCollection.AddPoint(triangleStripPointCollection.get_Point(i - 2), ref _missing, ref _missing); //Simulate: Polygon.Close IGeometry outlineGeometry = outlinePointCollection as IGeometry; MakeZAware(outlineGeometry); outlineGeometryCollection.AddGeometry(outlineGeometry, ref _missing, ref _missing); } return outlineGeometryCollection; } public static IGeometryCollection ConstructTriangleFanOutline(IGeometry triangleFanGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IPointCollection triangleFanPointCollection = triangleFanGeometry as IPointCollection; // TriangleFan: a linked fan of triangles, where every vertex (after the first two) completes a new triangle. // A new triangle is always formed by connecting the new vertex with its immediate predecessor // and the first vertex of the part. for (int i = 2; i < triangleFanPointCollection.PointCount; i++) { IPointCollection outlinePointCollection = new PolylineClass(); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(0), ref _missing, ref _missing); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(i - 1), ref _missing, ref _missing); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(i), ref _missing, ref _missing); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(0), ref _missing, ref _missing); //Simulate: Polygon.Close IGeometry outlineGeometry = outlinePointCollection as IGeometry; MakeZAware(outlineGeometry); outlineGeometryCollection.AddGeometry(outlineGeometry, ref _missing, ref _missing); } return outlineGeometryCollection; } public static IGeometryCollection ConstructTrianglesOutline(IGeometry trianglesGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IPointCollection trianglesPointCollection = trianglesGeometry as IPointCollection; // Triangles: an unlinked set of triangles, where every three vertices completes a new triangle. if ((trianglesPointCollection.PointCount % 3) != 0) { throw new Exception("Triangles Geometry Point Count Must Be Divisible By 3. " + trianglesPointCollection.PointCount); } else { for (int i = 0; i < trianglesPointCollection.PointCount; i+=3) { IPointCollection outlinePointCollection = new PolylineClass(); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i), ref _missing, ref _missing); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i + 1), ref _missing, ref _missing); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i + 2), ref _missing, ref _missing); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i), ref _missing, ref _missing); //Simulate: Polygon.Close IGeometry outlineGeometry = outlinePointCollection as IGeometry; MakeZAware(outlineGeometry); outlineGeometryCollection.AddGeometry(outlineGeometry, ref _missing, ref _missing); } } return outlineGeometryCollection; } public static IGeometry ConstructRingOutline(IGeometry ringGeometry) { IGeometry outlineGeometry = new PolylineClass(); IPointCollection outlinePointCollection = outlineGeometry as IPointCollection; IPointCollection ringPointCollection = ringGeometry as IPointCollection; for (int i = 0; i < ringPointCollection.PointCount; i++) { outlinePointCollection.AddPoint(ringPointCollection.get_Point(i), ref _missing, ref _missing); } outlinePointCollection.AddPoint(ringPointCollection.get_Point(0), ref _missing, ref _missing); //Simulate: Polygon.Close MakeZAware(outlineGeometry); return outlineGeometry; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Ionic.Zlib; using GZipStream = Ionic.Zlib.GZipStream; using CompressionMode = Ionic.Zlib.CompressionMode; using CompressionLevel = Ionic.Zlib.CompressionLevel; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveWriteRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Determine whether this archive will save assets. Default is true. /// </summary> public bool SaveAssets { get; set; } /// <summary> /// Determines which items will be included in the archive, according to their permissions. /// Default is null, meaning no permission checks. /// </summary> public string FilterContent { get; set; } /// <summary> /// Counter for inventory items saved to archive for passing to compltion event /// </summary> public int CountItems { get; set; } /// <summary> /// Counter for inventory items skipped due to permission filter option for passing to compltion event /// </summary> public int CountFiltered { get; set; } /// <value> /// Used to select all inventory nodes in a folder but not the folder itself /// </value> private const string STAR_WILDCARD = "*"; private InventoryArchiverModule m_module; private UserAccount m_userInfo; private string m_invPath; protected TarArchiveWriter m_archiveWriter; protected UuidGatherer m_assetGatherer; /// <value> /// We only use this to request modules /// </value> protected Scene m_scene; /// <value> /// ID of this request /// </value> protected UUID m_id; /// <value> /// Used to collect the uuids of the users that we need to save into the archive /// </value> protected Dictionary<UUID, int> m_userUuids = new Dictionary<UUID, int>(); /// <value> /// The stream to which the inventory archive will be saved. /// </value> private Stream m_saveStream; /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( UUID id, InventoryArchiverModule module, Scene scene, UserAccount userInfo, string invPath, string savePath) : this( id, module, scene, userInfo, invPath, new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress, CompressionLevel.BestCompression)) { } /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( UUID id, InventoryArchiverModule module, Scene scene, UserAccount userInfo, string invPath, Stream saveStream) { m_id = id; m_module = module; m_scene = scene; m_userInfo = userInfo; m_invPath = invPath; m_saveStream = saveStream; m_assetGatherer = new UuidGatherer(m_scene.AssetService); SaveAssets = true; FilterContent = null; } protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut) { Exception reportedException = null; bool succeeded = true; try { m_archiveWriter.Close(); } catch (Exception e) { reportedException = e; succeeded = false; } finally { m_saveStream.Close(); } if (timedOut) { succeeded = false; reportedException = new Exception("Loading assets timed out"); } m_module.TriggerInventoryArchiveSaved( m_id, succeeded, m_userInfo, m_invPath, m_saveStream, reportedException, CountItems, CountFiltered); } protected void SaveInvItem(InventoryItemBase inventoryItem, string path, Dictionary<string, object> options, IUserAccountService userAccountService) { if (options.ContainsKey("exclude")) { if (((List<String>)options["exclude"]).Contains(inventoryItem.Name) || ((List<String>)options["exclude"]).Contains(inventoryItem.ID.ToString())) { if (options.ContainsKey("verbose")) { m_log.InfoFormat( "[INVENTORY ARCHIVER]: Skipping inventory item {0} {1} at {2}", inventoryItem.Name, inventoryItem.ID, path); } CountFiltered++; return; } } // Check For Permissions Filter Flags if (!CanUserArchiveObject(m_userInfo.PrincipalID, inventoryItem)) { m_log.InfoFormat( "[INVENTORY ARCHIVER]: Insufficient permissions, skipping inventory item {0} {1} at {2}", inventoryItem.Name, inventoryItem.ID, path); // Count Items Excluded CountFiltered++; return; } if (options.ContainsKey("verbose")) m_log.InfoFormat( "[INVENTORY ARCHIVER]: Saving item {0} {1} (asset UUID {2})", inventoryItem.ID, inventoryItem.Name, inventoryItem.AssetID); string filename = path + CreateArchiveItemName(inventoryItem); // Record the creator of this item for user record purposes (which might go away soon) m_userUuids[inventoryItem.CreatorIdAsUuid] = 1; string serialization = UserInventoryItemSerializer.Serialize(inventoryItem, options, userAccountService); m_archiveWriter.WriteFile(filename, serialization); AssetType itemAssetType = (AssetType)inventoryItem.AssetType; // Count inventory items (different to asset count) CountItems++; // Don't chase down link asset items as they actually point to their target item IDs rather than an asset if (SaveAssets && itemAssetType != AssetType.Link && itemAssetType != AssetType.LinkFolder) { int curErrorCntr = m_assetGatherer.ErrorCount; int possible = m_assetGatherer.possibleNotAssetCount; m_assetGatherer.AddForInspection(inventoryItem.AssetID); m_assetGatherer.GatherAll(); curErrorCntr = m_assetGatherer.ErrorCount - curErrorCntr; possible = m_assetGatherer.possibleNotAssetCount - possible; if(curErrorCntr > 0 || possible > 0) { string spath; int indx = path.IndexOf("__"); if(indx > 0) spath = path.Substring(0,indx); else spath = path; if(curErrorCntr > 0) { m_log.ErrorFormat("[INVENTORY ARCHIVER Warning]: item {0} '{1}', type {2}, in '{3}', contains {4} references to missing or damaged assets", inventoryItem.ID, inventoryItem.Name, itemAssetType.ToString(), spath, curErrorCntr); if(possible > 0) m_log.WarnFormat("[INVENTORY ARCHIVER Warning]: item also contains {0} references that may be to missing or damaged assets or not a problem", possible); } else if(possible > 0) { m_log.WarnFormat("[INVENTORY ARCHIVER Warning]: item {0} '{1}', type {2}, in '{3}', contains {4} references that may be to missing or damaged assets or not a problem", inventoryItem.ID, inventoryItem.Name, itemAssetType.ToString(), spath, possible); } } } } /// <summary> /// Save an inventory folder /// </summary> /// <param name="inventoryFolder">The inventory folder to save</param> /// <param name="path">The path to which the folder should be saved</param> /// <param name="saveThisFolderItself">If true, save this folder itself. If false, only saves contents</param> /// <param name="options"></param> /// <param name="userAccountService"></param> protected void SaveInvFolder( InventoryFolderBase inventoryFolder, string path, bool saveThisFolderItself, Dictionary<string, object> options, IUserAccountService userAccountService) { if (options.ContainsKey("excludefolders")) { if (((List<String>)options["excludefolders"]).Contains(inventoryFolder.Name) || ((List<String>)options["excludefolders"]).Contains(inventoryFolder.ID.ToString())) { if (options.ContainsKey("verbose")) { m_log.InfoFormat( "[INVENTORY ARCHIVER]: Skipping folder {0} at {1}", inventoryFolder.Name, path); } return; } } if (options.ContainsKey("verbose")) m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving folder {0}", inventoryFolder.Name); if (saveThisFolderItself) { path += CreateArchiveFolderName(inventoryFolder); // We need to make sure that we record empty folders m_archiveWriter.WriteDir(path); } InventoryCollection contents = m_scene.InventoryService.GetFolderContent(inventoryFolder.Owner, inventoryFolder.ID); foreach (InventoryFolderBase childFolder in contents.Folders) { SaveInvFolder(childFolder, path, true, options, userAccountService); } foreach (InventoryItemBase item in contents.Items) { SaveInvItem(item, path, options, userAccountService); } } /// <summary> /// Checks whether the user has permission to export an inventory item to an IAR. /// </summary> /// <param name="UserID">The user</param> /// <param name="InvItem">The inventory item</param> /// <returns>Whether the user is allowed to export the object to an IAR</returns> private bool CanUserArchiveObject(UUID UserID, InventoryItemBase InvItem) { if (FilterContent == null) return true;// Default To Allow Export bool permitted = true; bool canCopy = (InvItem.CurrentPermissions & (uint)PermissionMask.Copy) != 0; bool canTransfer = (InvItem.CurrentPermissions & (uint)PermissionMask.Transfer) != 0; bool canMod = (InvItem.CurrentPermissions & (uint)PermissionMask.Modify) != 0; if (FilterContent.Contains("C") && !canCopy) permitted = false; if (FilterContent.Contains("T") && !canTransfer) permitted = false; if (FilterContent.Contains("M") && !canMod) permitted = false; return permitted; } /// <summary> /// Execute the inventory write request /// </summary> public void Execute(Dictionary<string, object> options, IUserAccountService userAccountService) { if (options.ContainsKey("noassets") && (bool)options["noassets"]) SaveAssets = false; // Set Permission filter if flag is set if (options.ContainsKey("checkPermissions")) { Object temp; if (options.TryGetValue("checkPermissions", out temp)) FilterContent = temp.ToString().ToUpper(); } try { InventoryFolderBase inventoryFolder = null; InventoryItemBase inventoryItem = null; InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(m_userInfo.PrincipalID); bool saveFolderContentsOnly = false; // Eliminate double slashes and any leading / on the path. string[] components = m_invPath.Split( new string[] { InventoryFolderImpl.PATH_DELIMITER }, StringSplitOptions.RemoveEmptyEntries); int maxComponentIndex = components.Length - 1; // If the path terminates with a STAR then later on we want to archive all nodes in the folder but not the // folder itself. This may get more sophisicated later on if (maxComponentIndex >= 0 && components[maxComponentIndex] == STAR_WILDCARD) { saveFolderContentsOnly = true; maxComponentIndex--; } else if (maxComponentIndex == -1) { // If the user has just specified "/", then don't save the root "My Inventory" folder. This is // more intuitive then requiring the user to specify "/*" for this. saveFolderContentsOnly = true; } m_invPath = String.Empty; for (int i = 0; i <= maxComponentIndex; i++) { m_invPath += components[i] + InventoryFolderImpl.PATH_DELIMITER; } // Annoyingly Split actually returns the original string if the input string consists only of delimiters // Therefore if we still start with a / after the split, then we need the root folder if (m_invPath.Length == 0) { inventoryFolder = rootFolder; } else { m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER)); List<InventoryFolderBase> candidateFolders = InventoryArchiveUtils.FindFoldersByPath(m_scene.InventoryService, rootFolder, m_invPath); if (candidateFolders.Count > 0) inventoryFolder = candidateFolders[0]; } // The path may point to an item instead if (inventoryFolder == null) inventoryItem = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, rootFolder, m_invPath); if (null == inventoryFolder && null == inventoryItem) { // We couldn't find the path indicated string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath); Exception e = new InventoryArchiverException(errorMessage); m_module.TriggerInventoryArchiveSaved(m_id, false, m_userInfo, m_invPath, m_saveStream, e, 0, 0); if(m_saveStream != null && m_saveStream.CanWrite) m_saveStream.Close(); throw e; } m_archiveWriter = new TarArchiveWriter(m_saveStream); m_log.InfoFormat("[INVENTORY ARCHIVER]: Adding control file to archive."); // Write out control file. This has to be done first so that subsequent loaders will see this file first // XXX: I know this is a weak way of doing it since external non-OAR aware tar executables will not do this // not sure how to fix this though, short of going with a completely different file format. m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(options)); if (inventoryFolder != null) { m_log.DebugFormat( "[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}", inventoryFolder.Name, inventoryFolder.ID, m_invPath == String.Empty ? InventoryFolderImpl.PATH_DELIMITER : m_invPath); //recurse through all dirs getting dirs and files SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !saveFolderContentsOnly, options, userAccountService); } else if (inventoryItem != null) { m_log.DebugFormat( "[INVENTORY ARCHIVER]: Found item {0} {1} at {2}", inventoryItem.Name, inventoryItem.ID, m_invPath); SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH, options, userAccountService); } // Don't put all this profile information into the archive right now. //SaveUsers(); if (SaveAssets) { m_assetGatherer.GatherAll(); int errors = m_assetGatherer.FailedUUIDs.Count; m_log.DebugFormat( "[INVENTORY ARCHIVER]: The items to save reference {0} possible assets", m_assetGatherer.GatheredUuids.Count + errors); if(errors > 0) m_log.DebugFormat("[INVENTORY ARCHIVER]: {0} of these have problems or are not assets and will be ignored", errors); AssetsRequest ar = new AssetsRequest( new AssetsArchiver(m_archiveWriter), m_assetGatherer.GatheredUuids, m_assetGatherer.FailedUUIDs.Count, m_scene.AssetService, m_scene.UserAccountService, m_scene.RegionInfo.ScopeID, options, ReceivedAllAssets); ar.Execute(); } else { m_log.DebugFormat("[INVENTORY ARCHIVER]: Not saving assets since --noassets was specified"); ReceivedAllAssets(new List<UUID>(), new List<UUID>(), false); } } catch (Exception) { m_saveStream.Close(); throw; } } /// <summary> /// Save information for the users that we've collected. /// </summary> protected void SaveUsers() { m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving user information for {0} users", m_userUuids.Count); foreach (UUID creatorId in m_userUuids.Keys) { // Record the creator of this item UserAccount creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, creatorId); if (creator != null) { m_archiveWriter.WriteFile( ArchiveConstants.USERS_PATH + creator.FirstName + " " + creator.LastName + ".xml", UserProfileSerializer.Serialize(creator.PrincipalID, creator.FirstName, creator.LastName)); } else { m_log.WarnFormat("[INVENTORY ARCHIVER]: Failed to get creator profile for {0}", creatorId); } } } /// <summary> /// Create the archive name for a particular folder. /// </summary> /// /// These names are prepended with an inventory folder's UUID so that more than one folder can have the /// same name /// /// <param name="folder"></param> /// <returns></returns> public static string CreateArchiveFolderName(InventoryFolderBase folder) { return CreateArchiveFolderName(folder.Name, folder.ID); } /// <summary> /// Create the archive name for a particular item. /// </summary> /// /// These names are prepended with an inventory item's UUID so that more than one item can have the /// same name /// /// <param name="item"></param> /// <returns></returns> public static string CreateArchiveItemName(InventoryItemBase item) { return CreateArchiveItemName(item.Name, item.ID); } /// <summary> /// Create an archive folder name given its constituent components /// </summary> /// <param name="name"></param> /// <param name="id"></param> /// <returns></returns> public static string CreateArchiveFolderName(string name, UUID id) { return string.Format( "{0}{1}{2}/", InventoryArchiveUtils.EscapeArchivePath(name), ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, id); } /// <summary> /// Create an archive item name given its constituent components /// </summary> /// <param name="name"></param> /// <param name="id"></param> /// <returns></returns> public static string CreateArchiveItemName(string name, UUID id) { return string.Format( "{0}{1}{2}.xml", InventoryArchiveUtils.EscapeArchivePath(name), ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, id); } /// <summary> /// Create the control file for the archive /// </summary> /// <param name="options"></param> /// <returns></returns> public string CreateControlFile(Dictionary<string, object> options) { int majorVersion, minorVersion; if (options.ContainsKey("home")) { majorVersion = 1; minorVersion = 2; } else { majorVersion = 0; minorVersion = 3; } m_log.InfoFormat("[INVENTORY ARCHIVER]: Creating version {0}.{1} IAR", majorVersion, minorVersion); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; xtw.WriteStartDocument(); xtw.WriteStartElement("archive"); xtw.WriteAttributeString("major_version", majorVersion.ToString()); xtw.WriteAttributeString("minor_version", minorVersion.ToString()); xtw.WriteElementString("assets_included", SaveAssets.ToString()); xtw.WriteEndElement(); xtw.Flush(); xtw.Close(); String s = sw.ToString(); sw.Close(); return s; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Mapping { using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Resources; using System.Linq; using Xunit; public class AssociationSetMappingTests { [Fact] public void Can_add_get_remove_column_conditions() { var entitySet1 = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet1); Assert.Empty(associationSetMapping.Conditions); var conditionPropertyMapping = new ValueConditionMapping(new EdmProperty("C", TypeUsage.Create(new PrimitiveType { DataSpace = DataSpace.SSpace })), 42); associationSetMapping.AddCondition(conditionPropertyMapping); Assert.Same(conditionPropertyMapping, associationSetMapping.Conditions.Single()); associationSetMapping.RemoveCondition(conditionPropertyMapping); Assert.Empty(associationSetMapping.Conditions); } [Fact] public void Can_initialize_with_entity_set() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var conditionPropertyMapping = new ValueConditionMapping(new EdmProperty("C", TypeUsage.Create(new PrimitiveType { DataSpace = DataSpace.SSpace })), 42); associationSetMapping.SetReadOnly(); var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var associationTypeMapping = associationSetMapping.TypeMappings.Single(); Assert.NotNull(associationTypeMapping); Assert.Same(associationSet.ElementType, associationTypeMapping.Types.Single()); Assert.Same(associationSetMapping, associationTypeMapping.SetMapping); var mappingFragment = associationTypeMapping.MappingFragments.Single(); Assert.Same(entitySet, mappingFragment.TableSet); } [Fact] public void Can_get_association_set() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); Assert.Same(associationSet, associationSetMapping.AssociationSet); } [Fact] public void Can_get_and_set_store_entity_set() { var entitySet1 = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet1); Assert.Same(entitySet1, associationSetMapping.StoreEntitySet); var entitySet2 = new EntitySet(); associationSetMapping.StoreEntitySet = entitySet2; Assert.Same(entitySet2, associationSetMapping.StoreEntitySet); } [Fact] public void Can_get_table() { var entityType = new EntityType("E", "N", DataSpace.CSpace); var entitySet = new EntitySet("ES", null, null, null, entityType); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); Assert.Same(entityType, associationSetMapping.Table); } [Fact] public void Can_get_and_set_source_and_target_end_mappings() { var entitySet1 = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet1); Assert.Null(associationSetMapping.SourceEndMapping); Assert.Null(associationSetMapping.TargetEndMapping); var sourceEndMapping = new EndPropertyMapping(); associationSetMapping.SourceEndMapping = sourceEndMapping; Assert.Same(sourceEndMapping, associationSetMapping.SourceEndMapping); var targetEndMapping = new EndPropertyMapping(); associationSetMapping.TargetEndMapping = targetEndMapping; Assert.Same(targetEndMapping, associationSetMapping.TargetEndMapping); } [Fact] public void Cannot_set_source_end_mapping_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var sourceEndMapping = new EndPropertyMapping(); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => (associationSetMapping.SourceEndMapping = sourceEndMapping)).Message); } [Fact] public void Cannot_set_target_end_mapping_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var targetEndMapping = new EndPropertyMapping(); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => (associationSetMapping.TargetEndMapping = targetEndMapping)).Message); } [Fact] public void Cannot_set__modification_function_mapping_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var modificationFunctionMapping = new AssociationSetModificationFunctionMapping(associationSet, null, null); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => (associationSetMapping.ModificationFunctionMapping = modificationFunctionMapping)).Message); } [Fact] public void Cannot_add_condition_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var conditionPropertyMapping = new ConditionPropertyMapping(null, new EdmProperty("C", TypeUsage.Create(new PrimitiveType() { DataSpace = DataSpace.SSpace })), 42, null); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => associationSetMapping.AddCondition(conditionPropertyMapping)).Message); } [Fact] public void Cannot_remove_condition_when_read_only() { var entitySet = new EntitySet(); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet); var conditionPropertyMapping = new ConditionPropertyMapping(null, new EdmProperty("C", TypeUsage.Create(new PrimitiveType() { DataSpace = DataSpace.SSpace })), 42, null); associationSetMapping.AddCondition(conditionPropertyMapping); associationSetMapping.SetReadOnly(); Assert.Equal( Strings.OperationOnReadOnlyItem, Assert.Throws<InvalidOperationException>( () => associationSetMapping.RemoveCondition(conditionPropertyMapping)).Message); } [Fact] public void SetReadOnly_is_called_on_child_mapping_items() { var entityType = new EntityType("ET", "N", DataSpace.SSpace); var entitySet = new EntitySet("ES", "S", "T", "Q", entityType); var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)); var associationSetMapping = new AssociationSetMapping(associationSet, entitySet, null); var modificationFunctionMapping = new AssociationSetModificationFunctionMapping(associationSet, null, null); associationSetMapping.ModificationFunctionMapping = modificationFunctionMapping; Assert.False(associationSetMapping.AssociationTypeMapping.IsReadOnly); Assert.False(modificationFunctionMapping.IsReadOnly); associationSetMapping.SetReadOnly(); Assert.True(associationSetMapping.AssociationTypeMapping.IsReadOnly); Assert.True(modificationFunctionMapping.IsReadOnly); } } }
// 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.Numerics; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; namespace System { internal static partial class Number { [StructLayout(LayoutKind.Sequential, Pack = 1)] internal unsafe ref struct BigInteger { // The longest binary mantissa requires: explicit mantissa bits + abs(min exponent) // * Half: 10 + 14 = 24 // * Single: 23 + 126 = 149 // * Double: 52 + 1022 = 1074 // * Quad: 112 + 16382 = 16494 private const int BitsForLongestBinaryMantissa = 1074; // The longest digit sequence requires: ceil(log2(pow(10, max significant digits + 1 rounding digit))) // * Half: ceil(log2(pow(10, 21 + 1))) = 74 // * Single: ceil(log2(pow(10, 112 + 1))) = 376 // * Double: ceil(log2(pow(10, 767 + 1))) = 2552 // * Quad: ceil(log2(pow(10, 11563 + 1))) = 38415 private const int BitsForLongestDigitSequence = 2552; // We require BitsPerBlock additional bits for shift space used during the pre-division preparation private const int MaxBits = BitsForLongestBinaryMantissa + BitsForLongestDigitSequence + BitsPerBlock; private const int BitsPerBlock = sizeof(int) * 8; private const int MaxBlockCount = (MaxBits + (BitsPerBlock - 1)) / BitsPerBlock; private static readonly uint[] s_Pow10UInt32Table = new uint[] { 1, // 10^0 10, // 10^1 100, // 10^2 1000, // 10^3 10000, // 10^4 100000, // 10^5 1000000, // 10^6 10000000, // 10^7 }; private static readonly int[] s_Pow10BigNumTableIndices = new int[] { 0, // 10^8 2, // 10^16 5, // 10^32 10, // 10^64 18, // 10^128 33, // 10^256 61, // 10^512 116, // 10^1024 }; private static readonly uint[] s_Pow10BigNumTable = new uint[] { // 10^8 1, // _length 100000000, // _blocks // 10^16 2, // _length 0x6FC10000, // _blocks 0x002386F2, // 10^32 4, // _length 0x00000000, // _blocks 0x85ACEF81, 0x2D6D415B, 0x000004EE, // 10^64 7, // _length 0x00000000, // _blocks 0x00000000, 0xBF6A1F01, 0x6E38ED64, 0xDAA797ED, 0xE93FF9F4, 0x00184F03, // 10^128 14, // _length 0x00000000, // _blocks 0x00000000, 0x00000000, 0x00000000, 0x2E953E01, 0x03DF9909, 0x0F1538FD, 0x2374E42F, 0xD3CFF5EC, 0xC404DC08, 0xBCCDB0DA, 0xA6337F19, 0xE91F2603, 0x0000024E, // 10^256 27, // _length 0x00000000, // _blocks 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x982E7C01, 0xBED3875B, 0xD8D99F72, 0x12152F87, 0x6BDE50C6, 0xCF4A6E70, 0xD595D80F, 0x26B2716E, 0xADC666B0, 0x1D153624, 0x3C42D35A, 0x63FF540E, 0xCC5573C0, 0x65F9EF17, 0x55BC28F2, 0x80DCC7F7, 0xF46EEDDC, 0x5FDCEFCE, 0x000553F7, // 10^512 54, // _length 0x00000000, // _blocks 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFC6CF801, 0x77F27267, 0x8F9546DC, 0x5D96976F, 0xB83A8A97, 0xC31E1AD9, 0x46C40513, 0x94E65747, 0xC88976C1, 0x4475B579, 0x28F8733B, 0xAA1DA1BF, 0x703ED321, 0x1E25CFEA, 0xB21A2F22, 0xBC51FB2E, 0x96E14F5D, 0xBFA3EDAC, 0x329C57AE, 0xE7FC7153, 0xC3FC0695, 0x85A91924, 0xF95F635E, 0xB2908EE0, 0x93ABADE4, 0x1366732A, 0x9449775C, 0x69BE5B0E, 0x7343AFAC, 0xB099BC81, 0x45A71D46, 0xA2699748, 0x8CB07303, 0x8A0B1F13, 0x8CAB8A97, 0xC1D238D9, 0x633415D4, 0x0000001C, // 10^1024 107, // _length 0x00000000, // _blocks 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x2919F001, 0xF55B2B72, 0x6E7C215B, 0x1EC29F86, 0x991C4E87, 0x15C51A88, 0x140AC535, 0x4C7D1E1A, 0xCC2CD819, 0x0ED1440E, 0x896634EE, 0x7DE16CFB, 0x1E43F61F, 0x9FCE837D, 0x231D2B9C, 0x233E55C7, 0x65DC60D7, 0xF451218B, 0x1C5CD134, 0xC9635986, 0x922BBB9F, 0xA7E89431, 0x9F9F2A07, 0x62BE695A, 0x8E1042C4, 0x045B7A74, 0x1ABE1DE3, 0x8AD822A5, 0xBA34C411, 0xD814B505, 0xBF3FDEB3, 0x8FC51A16, 0xB1B896BC, 0xF56DEEEC, 0x31FB6BFD, 0xB6F4654B, 0x101A3616, 0x6B7595FB, 0xDC1A47FE, 0x80D98089, 0x80BDA5A5, 0x9A202882, 0x31EB0F66, 0xFC8F1F90, 0x976A3310, 0xE26A7B7E, 0xDF68368A, 0x3CE3A0B8, 0x8E4262CE, 0x75A351A2, 0x6CB0B6C9, 0x44597583, 0x31B5653F, 0xC356E38A, 0x35FAABA6, 0x0190FBA0, 0x9FC4ED52, 0x88BC491B, 0x1640114A, 0x005B8041, 0xF4F3235E, 0x1E8D4649, 0x36A8DE06, 0x73C55349, 0xA7E6BD2A, 0xC1A6970C, 0x47187094, 0xD2DB49EF, 0x926C3F5B, 0xAE6209D4, 0x2D433949, 0x34F4A3C6, 0xD4305D94, 0xD9D61A05, 0x00000325, // 9 Trailing blocks to ensure MaxBlockCount 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; private int _length; private fixed uint _blocks[MaxBlockCount]; public BigInteger(uint value) { _blocks[0] = value; _length = (value == 0) ? 0 : 1; } public BigInteger(ulong value) { var lower = (uint)(value); var upper = (uint)(value >> 32); _blocks[0] = lower; _blocks[1] = upper; _length = (upper == 0) ? 1 : 2; } public static void Add(ref BigInteger lhs, uint value, ref BigInteger result) { if (lhs.IsZero()) { result.SetUInt32(value); return; } if (value == 0) { result.SetValue(ref lhs); return; } int lhsLength = lhs._length; int index = 0; uint carry = value; while (index < lhsLength) { ulong sum = (ulong)(lhs._blocks[index]) + carry; lhs._blocks[index] = (uint)(sum); carry = (uint)(sum >> 32); index++; } if (carry != 0) { Debug.Assert(unchecked((uint)(lhsLength)) + 1 <= MaxBlockCount); result._blocks[index] = carry; result._length = (lhsLength + 1); } } public static void Add(ref BigInteger lhs, ref BigInteger rhs, out BigInteger result) { // determine which operand has the smaller length ref BigInteger large = ref (lhs._length < rhs._length) ? ref rhs : ref lhs; ref BigInteger small = ref (lhs._length < rhs._length) ? ref lhs : ref rhs; int largeLength = large._length; int smallLength = small._length; // The output will be at least as long as the largest input result = new BigInteger(0); result._length = largeLength; // Add each block and add carry the overflow to the next block ulong carry = 0; int largeIndex = 0; int smallIndex = 0; int resultIndex = 0; while (smallIndex < smallLength) { ulong sum = carry + large._blocks[largeIndex] + small._blocks[smallIndex]; carry = sum >> 32; result._blocks[resultIndex] = (uint)(sum); largeIndex++; smallIndex++; resultIndex++; } // Add the carry to any blocks that only exist in the large operand while (largeIndex < largeLength) { ulong sum = carry + large._blocks[largeIndex]; carry = sum >> 32; result._blocks[resultIndex] = (uint)(sum); largeIndex++; resultIndex++; } // If there's still a carry, append a new block if (carry != 0) { Debug.Assert(carry == 1); Debug.Assert((resultIndex == largeLength) && (largeLength < MaxBlockCount)); result._blocks[resultIndex] = 1; result._length += 1; } } public static int Compare(ref BigInteger lhs, ref BigInteger rhs) { Debug.Assert(unchecked((uint)(lhs._length)) <= MaxBlockCount); Debug.Assert(unchecked((uint)(rhs._length)) <= MaxBlockCount); int lhsLength = lhs._length; int rhsLength = rhs._length; int lengthDelta = (lhsLength - rhsLength); if (lengthDelta != 0) { return lengthDelta; } if (lhsLength == 0) { Debug.Assert(rhsLength == 0); return 0; } for (int index = (lhsLength - 1); index >= 0; index--) { long delta = (long)(lhs._blocks[index]) - rhs._blocks[index]; if (delta != 0) { return delta > 0 ? 1 : -1; } } return 0; } public static uint CountSignificantBits(uint value) { return 32 - (uint)BitOperations.LeadingZeroCount(value); } public static uint CountSignificantBits(ulong value) { return 64 - (uint)BitOperations.LeadingZeroCount(value); } public static uint CountSignificantBits(ref BigInteger value) { if (value.IsZero()) { return 0; } // We don't track any unused blocks, so we only need to do a BSR on the // last index and add that to the number of bits we skipped. uint lastIndex = (uint)(value._length - 1); return (lastIndex * BitsPerBlock) + CountSignificantBits(value._blocks[lastIndex]); } public static void DivRem(ref BigInteger lhs, ref BigInteger rhs, out BigInteger quo, out BigInteger rem) { // This is modified from the CoreFX BigIntegerCalculator.DivRem.cs implementation: // https://github.com/dotnet/corefx/blob/0bb106232745aedfc0d0c5a84ff2b244bf190317/src/System.Runtime.Numerics/src/System/Numerics/BigIntegerCalculator.DivRem.cs Debug.Assert(!rhs.IsZero()); quo = new BigInteger(0); rem = new BigInteger(0); if (lhs.IsZero()) { return; } int lhsLength = lhs._length; int rhsLength = rhs._length; if ((lhsLength == 1) && (rhsLength == 1)) { uint quotient = Math.DivRem(lhs._blocks[0], rhs._blocks[0], out uint remainder); quo = new BigInteger(quotient); rem = new BigInteger(remainder); return; } if (rhsLength == 1) { // We can make the computation much simpler if the rhs is only one block int quoLength = lhsLength; ulong rhsValue = rhs._blocks[0]; ulong carry = 0; for (int i = quoLength - 1; i >= 0; i--) { ulong value = (carry << 32) | lhs._blocks[i]; ulong digit = Math.DivRem(value, rhsValue, out carry); if ((digit == 0) && (i == (quoLength - 1))) { quoLength--; } else { quo._blocks[i] = (uint)(digit); } } quo._length = quoLength; rem.SetUInt32((uint)(carry)); return; } else if (rhsLength > lhsLength) { // Handle the case where we have no quotient rem.SetValue(ref lhs); return; } else { int quoLength = lhsLength - rhsLength + 1; rem.SetValue(ref lhs); int remLength = lhsLength; // Executes the "grammar-school" algorithm for computing q = a / b. // Before calculating q_i, we get more bits into the highest bit // block of the divisor. Thus, guessing digits of the quotient // will be more precise. Additionally we'll get r = a % b. uint divHi = rhs._blocks[rhsLength - 1]; uint divLo = rhs._blocks[rhsLength - 2]; // We measure the leading zeros of the divisor int shiftLeft = BitOperations.LeadingZeroCount(divHi); int shiftRight = 32 - shiftLeft; // And, we make sure the most significant bit is set if (shiftLeft > 0) { divHi = (divHi << shiftLeft) | (divLo >> shiftRight); divLo = (divLo << shiftLeft); if (rhsLength > 2) { divLo |= (rhs._blocks[rhsLength - 3] >> shiftRight); } } // Then, we divide all of the bits as we would do it using // pen and paper: guessing the next digit, subtracting, ... for (int i = lhsLength; i >= rhsLength; i--) { int n = i - rhsLength; uint t = i < lhsLength ? rem._blocks[i] : 0; ulong valHi = ((ulong)(t) << 32) | rem._blocks[i - 1]; uint valLo = i > 1 ? rem._blocks[i - 2] : 0; // We shifted the divisor, we shift the dividend too if (shiftLeft > 0) { valHi = (valHi << shiftLeft) | (valLo >> shiftRight); valLo = (valLo << shiftLeft); if (i > 2) { valLo |= (rem._blocks[i - 3] >> shiftRight); } } // First guess for the current digit of the quotient, // which naturally must have only 32 bits... ulong digit = valHi / divHi; if (digit > uint.MaxValue) { digit = uint.MaxValue; } // Our first guess may be a little bit to big while (DivideGuessTooBig(digit, valHi, valLo, divHi, divLo)) { digit--; } if (digit > 0) { // Now it's time to subtract our current quotient uint carry = SubtractDivisor(ref rem, n, ref rhs, digit); if (carry != t) { Debug.Assert(carry == t + 1); // Our guess was still exactly one too high carry = AddDivisor(ref rem, n, ref rhs); digit--; Debug.Assert(carry == 1); } } // We have the digit! if (quoLength != 0) { if ((digit == 0) && (n == (quoLength - 1))) { quoLength--; } else { quo._blocks[n] = (uint)(digit); } } if (i < remLength) { remLength--; } } quo._length = quoLength; // We need to check for the case where remainder is zero for (int i = remLength - 1; i >= 0; i--) { if (rem._blocks[i] == 0) { remLength--; } } rem._length = remLength; } } public static uint HeuristicDivide(ref BigInteger dividend, ref BigInteger divisor) { int divisorLength = divisor._length; if (dividend._length < divisorLength) { return 0; } // This is an estimated quotient. Its error should be less than 2. // Reference inequality: // a/b - floor(floor(a)/(floor(b) + 1)) < 2 int lastIndex = (divisorLength - 1); uint quotient = dividend._blocks[lastIndex] / (divisor._blocks[lastIndex] + 1); if (quotient != 0) { // Now we use our estimated quotient to update each block of dividend. // dividend = dividend - divisor * quotient int index = 0; ulong borrow = 0; ulong carry = 0; do { ulong product = ((ulong)(divisor._blocks[index]) * quotient) + carry; carry = product >> 32; ulong difference = (ulong)(dividend._blocks[index]) - (uint)(product) - borrow; borrow = (difference >> 32) & 1; dividend._blocks[index] = (uint)(difference); index++; } while (index < divisorLength); // Remove all leading zero blocks from dividend while ((divisorLength > 0) && (dividend._blocks[divisorLength - 1] == 0)) { divisorLength--; } dividend._length = divisorLength; } // If the dividend is still larger than the divisor, we overshot our estimate quotient. To correct, // we increment the quotient and subtract one more divisor from the dividend (Because we guaranteed the error range). if (Compare(ref dividend, ref divisor) >= 0) { quotient++; // dividend = dividend - divisor int index = 0; ulong borrow = 0; do { ulong difference = (ulong)(dividend._blocks[index]) - divisor._blocks[index] - borrow; borrow = (difference >> 32) & 1; dividend._blocks[index] = (uint)(difference); index++; } while (index < divisorLength); // Remove all leading zero blocks from dividend while ((divisorLength > 0) && (dividend._blocks[divisorLength - 1] == 0)) { divisorLength--; } dividend._length = divisorLength; } return quotient; } public static void Multiply(ref BigInteger lhs, uint value, ref BigInteger result) { if (lhs.IsZero() || (value == 1)) { result.SetValue(ref lhs); return; } if (value == 0) { result.SetZero(); return; } int lhsLength = lhs._length; int index = 0; uint carry = 0; while (index < lhsLength) { ulong product = ((ulong)(lhs._blocks[index]) * value) + carry; result._blocks[index] = (uint)(product); carry = (uint)(product >> 32); index++; } if (carry != 0) { Debug.Assert(unchecked((uint)(lhsLength)) + 1 <= MaxBlockCount); result._blocks[index] = carry; result._length = (lhsLength + 1); } } public static void Multiply(ref BigInteger lhs, ref BigInteger rhs, ref BigInteger result) { if (lhs.IsZero() || rhs.IsOne()) { result.SetValue(ref lhs); return; } if (rhs.IsZero()) { result.SetZero(); return; } ref readonly BigInteger large = ref lhs; int largeLength = lhs._length; ref readonly BigInteger small = ref rhs; int smallLength = rhs._length; if (largeLength < smallLength) { large = ref rhs; largeLength = rhs._length; small = ref lhs; smallLength = lhs._length; } int maxResultLength = smallLength + largeLength; Debug.Assert(unchecked((uint)(maxResultLength)) <= MaxBlockCount); // Zero out result internal blocks. Buffer.ZeroMemory((byte*)(result.GetBlocksPointer()), (maxResultLength * sizeof(uint))); int smallIndex = 0; int resultStartIndex = 0; while (smallIndex < smallLength) { // Multiply each block of large BigNum. if (small._blocks[smallIndex] != 0) { int largeIndex = 0; int resultIndex = resultStartIndex; ulong carry = 0; do { ulong product = result._blocks[resultIndex] + ((ulong)(small._blocks[smallIndex]) * large._blocks[largeIndex]) + carry; carry = product >> 32; result._blocks[resultIndex] = (uint)(product); resultIndex++; largeIndex++; } while (largeIndex < largeLength); result._blocks[resultIndex] = (uint)(carry); } smallIndex++; resultStartIndex++; } if ((maxResultLength > 0) && (result._blocks[maxResultLength - 1] == 0)) { result._length = (maxResultLength - 1); } else { result._length = maxResultLength; } } public static void Pow2(uint exponent, out BigInteger result) { result = new BigInteger(0); ShiftLeft(1, exponent, ref result); } public static void Pow10(uint exponent, out BigInteger result) { // We leverage two arrays - s_Pow10UInt32Table and s_Pow10BigNumTable to speed up the Pow10 calculation. // // s_Pow10UInt32Table stores the results of 10^0 to 10^7. // s_Pow10BigNumTable stores the results of 10^8, 10^16, 10^32, 10^64, 10^128, 10^256, and 10^512 // // For example, let's say exp = 0b111111. We can split the exp to two parts, one is small exp, // which 10^smallExp can be represented as uint, another part is 10^bigExp, which must be represented as BigNum. // So the result should be 10^smallExp * 10^bigExp. // // Calculating 10^smallExp is simple, we just lookup the 10^smallExp from s_Pow10UInt32Table. // But here's a bad news: although uint can represent 10^9, exp 9's binary representation is 1001. // That means 10^(1011), 10^(1101), 10^(1111) all cannot be stored as uint, we cannot easily say something like: // "Any bits <= 3 is small exp, any bits > 3 is big exp". So instead of involving 10^8, 10^9 to s_Pow10UInt32Table, // consider 10^8 and 10^9 as a bigNum, so they fall into s_Pow10BigNumTable. Now we can have a simple rule: // "Any bits <= 3 is small exp, any bits > 3 is big exp". // // For 0b111111, we first calculate 10^(smallExp), which is 10^(7), now we can shift right 3 bits, prepare to calculate the bigExp part, // the exp now becomes 0b000111. // // Apparently the lowest bit of bigExp should represent 10^8 because we have already shifted 3 bits for smallExp, so s_Pow10BigNumTable[0] = 10^8. // Now let's shift exp right 1 bit, the lowest bit should represent 10^(8 * 2) = 10^16, and so on... // // That's why we just need the values of s_Pow10BigNumTable be power of 2. // // More details of this implementation can be found at: https://github.com/dotnet/coreclr/pull/12894#discussion_r128890596 // Validate that `s_Pow10BigNumTable` has exactly enough trailing elements to fill a BigInteger (which contains MaxBlockCount + 1 elements) // We validate here, since this is the only current consumer of the array Debug.Assert((s_Pow10BigNumTableIndices[s_Pow10BigNumTableIndices.Length - 1] + MaxBlockCount + 2) == s_Pow10BigNumTable.Length); BigInteger temp1 = new BigInteger(s_Pow10UInt32Table[exponent & 0x7]); ref BigInteger lhs = ref temp1; BigInteger temp2 = new BigInteger(0); ref BigInteger product = ref temp2; exponent >>= 3; uint index = 0; while (exponent != 0) { // If the current bit is set, multiply it with the corresponding power of 10 if ((exponent & 1) != 0) { // Multiply into the next temporary fixed (uint* pBigNumEntry = &s_Pow10BigNumTable[s_Pow10BigNumTableIndices[index]]) { ref BigInteger rhs = ref *(BigInteger*)(pBigNumEntry); Multiply(ref lhs, ref rhs, ref product); } // Swap to the next temporary ref BigInteger temp = ref product; product = ref lhs; lhs = ref temp; } // Advance to the next bit ++index; exponent >>= 1; } result = new BigInteger(0); result.SetValue(ref lhs); } public static void ShiftLeft(ulong input, uint shift, ref BigInteger output) { if (shift == 0) { return; } uint blocksToShift = Math.DivRem(shift, 32, out uint remainingBitsToShift); if (blocksToShift > 0) { // If blocks shifted, we should fill the corresponding blocks with zero. output.ExtendBlocks(0, blocksToShift); } if (remainingBitsToShift == 0) { // We shift 32 * n (n >= 1) bits. No remaining bits. output.ExtendBlock((uint)(input)); uint highBits = (uint)(input >> 32); if (highBits != 0) { output.ExtendBlock(highBits); } } else { // Extract the high position bits which would be shifted out of range. uint highPositionBits = (uint)(input) >> (int)(64 - remainingBitsToShift); // Shift the input. The result should be stored to current block. ulong shiftedInput = input << (int)(remainingBitsToShift); output.ExtendBlock((uint)(shiftedInput)); uint highBits = (uint)(input >> 32); if (highBits != 0) { output.ExtendBlock(highBits); } if (highPositionBits != 0) { // If the high position bits is not 0, we should store them to next block. output.ExtendBlock(highPositionBits); } } } private static unsafe uint AddDivisor(ref BigInteger lhs, int lhsStartIndex, ref BigInteger rhs) { int lhsLength = lhs._length; int rhsLength = rhs._length; Debug.Assert(lhsLength >= 0); Debug.Assert(rhsLength >= 0); Debug.Assert(lhsLength >= rhsLength); // Repairs the dividend, if the last subtract was too much ulong carry = 0UL; for (int i = 0; i < rhsLength; i++) { ref uint lhsValue = ref lhs._blocks[lhsStartIndex + i]; ulong digit = (lhsValue + carry) + rhs._blocks[i]; lhsValue = unchecked((uint)digit); carry = digit >> 32; } return (uint)(carry); } private static bool DivideGuessTooBig(ulong q, ulong valHi, uint valLo, uint divHi, uint divLo) { Debug.Assert(q <= 0xFFFFFFFF); // We multiply the two most significant limbs of the divisor // with the current guess for the quotient. If those are bigger // than the three most significant limbs of the current dividend // we return true, which means the current guess is still too big. ulong chkHi = divHi * q; ulong chkLo = divLo * q; chkHi = chkHi + (chkLo >> 32); chkLo = chkLo & uint.MaxValue; if (chkHi < valHi) return false; if (chkHi > valHi) return true; if (chkLo < valLo) return false; if (chkLo > valLo) return true; return false; } private static unsafe uint SubtractDivisor(ref BigInteger lhs, int lhsStartIndex, ref BigInteger rhs, ulong q) { int lhsLength = lhs._length - lhsStartIndex; int rhsLength = rhs._length; Debug.Assert((lhsLength) >= 0); Debug.Assert(rhsLength >= 0); Debug.Assert(lhsLength >= rhsLength); Debug.Assert(q <= uint.MaxValue); // Combines a subtract and a multiply operation, which is naturally // more efficient than multiplying and then subtracting... ulong carry = 0; for (int i = 0; i < rhsLength; i++) { carry += rhs._blocks[i] * q; uint digit = unchecked((uint)carry); carry = carry >> 32; ref uint lhsValue = ref lhs._blocks[lhsStartIndex + i]; if (lhsValue < digit) { carry++; } lhsValue = unchecked(lhsValue - digit); } return (uint)(carry); } public void Add(uint value) { Add(ref this, value, ref this); } public void ExtendBlock(uint blockValue) { _blocks[_length] = blockValue; _length++; } public void ExtendBlocks(uint blockValue, uint blockCount) { Debug.Assert(blockCount > 0); if (blockCount == 1) { ExtendBlock(blockValue); return; } Buffer.ZeroMemory((byte*)(GetBlocksPointer() + _length), ((blockCount - 1) * sizeof(uint))); _length += (int)(blockCount); _blocks[_length - 1] = blockValue; } public uint GetBlock(uint index) { Debug.Assert(index < _length); return _blocks[index]; } public int GetLength() { return _length; } public bool IsOne() { return (_length == 1) && (_blocks[0] == 1); } public bool IsZero() { return _length == 0; } public void Multiply(uint value) { Multiply(ref this, value, ref this); } public void Multiply(ref BigInteger value) { var result = new BigInteger(0); Multiply(ref this, ref value, ref result); Buffer.Memcpy((byte*)(GetBlocksPointer()), (byte*)(result.GetBlocksPointer()), (result._length) * sizeof(uint)); _length = result._length; } public void Multiply10() { if (IsZero()) { return; } int index = 0; int length = _length; ulong carry = 0; while (index < length) { var block = (ulong)(_blocks[index]); ulong product = (block << 3) + (block << 1) + carry; carry = product >> 32; _blocks[index] = (uint)(product); index++; } if (carry != 0) { Debug.Assert(unchecked((uint)(_length)) + 1 <= MaxBlockCount); _blocks[index] = (uint)(carry); _length += 1; } } public void MultiplyPow10(uint exponent) { Pow10(exponent, out BigInteger poweredValue); if (poweredValue._length == 1) { Multiply(poweredValue._blocks[0]); } else { Multiply(ref poweredValue); } } public void SetUInt32(uint value) { _blocks[0] = value; _length = 1; } public void SetUInt64(ulong value) { var lower = (uint)(value); var upper = (uint)(value >> 32); _blocks[0] = lower; _blocks[1] = upper; _length = (upper == 0) ? 1 : 2; } public void SetValue(ref BigInteger rhs) { int rhsLength = rhs._length; Buffer.Memcpy((byte*)(GetBlocksPointer()), (byte*)(rhs.GetBlocksPointer()), (rhsLength * sizeof(uint))); _length = rhsLength; } public void SetZero() { _length = 0; } public void ShiftLeft(uint shift) { // Process blocks high to low so that we can safely process in place var length = _length; if ((length == 0) || (shift == 0)) { return; } uint blocksToShift = Math.DivRem(shift, 32, out uint remainingBitsToShift); // Copy blocks from high to low int readIndex = (length - 1); int writeIndex = readIndex + (int)(blocksToShift); // Check if the shift is block aligned if (remainingBitsToShift == 0) { Debug.Assert(writeIndex < MaxBlockCount); while (readIndex >= 0) { _blocks[writeIndex] = _blocks[readIndex]; readIndex--; writeIndex--; } _length += (int)(blocksToShift); // Zero the remaining low blocks Buffer.ZeroMemory((byte*)(GetBlocksPointer()), (blocksToShift * sizeof(uint))); } else { // We need an extra block for the partial shift writeIndex++; Debug.Assert(writeIndex < MaxBlockCount); // Set the length to hold the shifted blocks _length = writeIndex + 1; // Output the initial blocks uint lowBitsShift = (32 - remainingBitsToShift); uint highBits = 0; uint block = _blocks[readIndex]; uint lowBits = block >> (int)(lowBitsShift); while (readIndex > 0) { _blocks[writeIndex] = highBits | lowBits; highBits = block << (int)(remainingBitsToShift); --readIndex; --writeIndex; block = _blocks[readIndex]; lowBits = block >> (int)lowBitsShift; } // Output the final blocks _blocks[writeIndex] = highBits | lowBits; _blocks[writeIndex - 1] = block << (int)(remainingBitsToShift); // Zero the remaining low blocks Buffer.ZeroMemory((byte*)(GetBlocksPointer()), (blocksToShift * sizeof(uint))); // Check if the terminating block has no set bits if (_blocks[_length - 1] == 0) { _length--; } } } public ulong ToUInt64() { if (_length > 1) { return ((ulong)(_blocks[1]) << 32) + _blocks[0]; } if (_length > 0) { return _blocks[0]; } return 0; } private uint* GetBlocksPointer() { // This is safe to do since we are a ref struct return (uint*)(Unsafe.AsPointer(ref _blocks[0])); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; namespace System.Security.Cryptography.Asn1 { internal sealed partial class AsnWriter { /// <summary> /// Write a Bit String value with a tag UNIVERSAL 3. /// </summary> /// <param name="bitString">The value to write.</param> /// <param name="unusedBitCount"> /// The number of trailing bits which are not semantic. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="unusedBitCount"/> is not in the range [0,7] /// </exception> /// <exception cref="CryptographicException"> /// <paramref name="bitString"/> has length 0 and <paramref name="unusedBitCount"/> is not 0 --OR-- /// <paramref name="bitString"/> is not empty and any of the bits identified by /// <paramref name="unusedBitCount"/> is set /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteBitString(ReadOnlySpan<byte> bitString, int unusedBitCount = 0) { WriteBitStringCore(Asn1Tag.PrimitiveBitString, bitString, unusedBitCount); } /// <summary> /// Write a Bit String value with a specified tag. /// </summary> /// <param name="tag">The tag to write.</param> /// <param name="bitString">The value to write.</param> /// <param name="unusedBitCount"> /// The number of trailing bits which are not semantic. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="unusedBitCount"/> is not in the range [0,7] /// </exception> /// <exception cref="CryptographicException"> /// <paramref name="bitString"/> has length 0 and <paramref name="unusedBitCount"/> is not 0 --OR-- /// <paramref name="bitString"/> is not empty and any of the bits identified by /// <paramref name="unusedBitCount"/> is set /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteBitString(Asn1Tag tag, ReadOnlySpan<byte> bitString, int unusedBitCount = 0) { CheckUniversalTag(tag, UniversalTagNumber.BitString); // Primitive or constructed, doesn't matter. WriteBitStringCore(tag, bitString, unusedBitCount); } // T-REC-X.690-201508 sec 8.6 private void WriteBitStringCore(Asn1Tag tag, ReadOnlySpan<byte> bitString, int unusedBitCount) { // T-REC-X.690-201508 sec 8.6.2.2 if (unusedBitCount < 0 || unusedBitCount > 7) { throw new ArgumentOutOfRangeException( nameof(unusedBitCount), unusedBitCount, SR.Cryptography_Asn_UnusedBitCountRange); } CheckDisposed(); // T-REC-X.690-201508 sec 8.6.2.3 if (bitString.Length == 0 && unusedBitCount != 0) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } byte lastByte = bitString.IsEmpty ? (byte)0 : bitString[bitString.Length - 1]; // T-REC-X.690-201508 sec 11.2 // // This could be ignored for BER, but since DER is more common and // it likely suggests a program error on the caller, leave it enabled for // BER for now. if (!CheckValidLastByte(lastByte, unusedBitCount)) { // TODO: Probably warrants a distinct message. throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } if (RuleSet == AsnEncodingRules.CER) { // T-REC-X.690-201508 sec 9.2 // // If it's not within a primitive segment, use the constructed encoding. // (>= instead of > because of the unused bit count byte) if (bitString.Length >= AsnReader.MaxCERSegmentSize) { WriteConstructedCerBitString(tag, bitString, unusedBitCount); return; } } // Clear the constructed flag, if present. WriteTag(tag.AsPrimitive()); // The unused bits byte requires +1. WriteLength(bitString.Length + 1); _buffer[_offset] = (byte)unusedBitCount; _offset++; bitString.CopyTo(_buffer.AsSpan(_offset)); _offset += bitString.Length; } #if NETCOREAPP || NETSTANDARD2_1 /// <summary> /// Write a Bit String value via a callback, with a tag UNIVERSAL 3. /// </summary> /// <param name="byteLength">The total number of bytes to write.</param> /// <param name="state">A state object to pass to <paramref name="action"/>.</param> /// <param name="action">A callback to invoke for populating the Bit String.</param> /// <param name="unusedBitCount"> /// The number of trailing bits which are not semantic. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="byteLength"/> is negative --OR-- /// <paramref name="unusedBitCount"/> is not in the range [0,7] /// </exception> /// <exception cref="CryptographicException"> /// <paramref name="byteLength"/> is 0 and <paramref name="unusedBitCount"/> is not 0 --OR-- /// <paramref name="byteLength"/> is not 0 and any of the bits identified by /// <paramref name="unusedBitCount"/> is set /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteBitString<TState>( int byteLength, TState state, SpanAction<byte, TState> action, int unusedBitCount = 0) { WriteBitStringCore(Asn1Tag.PrimitiveBitString, byteLength, state, action, unusedBitCount); } /// <summary> /// Write a Bit String value via a callback, with a specified tag. /// </summary> /// <param name="tag">The tag to write.</param> /// <param name="byteLength">The total number of bytes to write.</param> /// <param name="state">A state object to pass to <paramref name="action"/>.</param> /// <param name="action">A callback to invoke for populating the Bit String.</param> /// <param name="unusedBitCount"> /// The number of trailing bits which are not semantic. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for /// the method /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="byteLength"/> is negative --OR-- /// <paramref name="unusedBitCount"/> is not in the range [0,7] /// </exception> /// <exception cref="CryptographicException"> /// <paramref name="byteLength"/> is 0 and <paramref name="unusedBitCount"/> is not 0 --OR-- /// <paramref name="byteLength"/> is not 0 and any of the bits identified by /// <paramref name="unusedBitCount"/> is set /// </exception> /// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception> public void WriteBitString<TState>( Asn1Tag tag, int byteLength, TState state, SpanAction<byte, TState> action, int unusedBitCount = 0) { CheckUniversalTag(tag, UniversalTagNumber.BitString); // Primitive or constructed, doesn't matter. WriteBitStringCore(tag, byteLength, state, action, unusedBitCount); } // T-REC-X.690-201508 sec 8.6 private void WriteBitStringCore<TState>( Asn1Tag tag, int byteLength, TState state, SpanAction<byte, TState> action, int unusedBitCount = 0) { if (byteLength == 0) { WriteBitStringCore(tag, ReadOnlySpan<byte>.Empty, unusedBitCount); return; } // T-REC-X.690-201508 sec 8.6.2.2 if (unusedBitCount < 0 || unusedBitCount > 7) { throw new ArgumentOutOfRangeException( nameof(unusedBitCount), unusedBitCount, SR.Cryptography_Asn_UnusedBitCountRange); } CheckDisposed(); int savedOffset = _offset; Span<byte> scratchSpace; byte[] ensureNoExtraCopy = null; int expectedSize = 0; // T-REC-X.690-201508 sec 9.2 // // If it's not within a primitive segment, use the constructed encoding. // (>= instead of > because of the unused bit count byte) bool segmentedWrite = RuleSet == AsnEncodingRules.CER && byteLength >= AsnReader.MaxCERSegmentSize; if (segmentedWrite) { // Rather than call the callback multiple times, grow the buffer to allow // for enough space for the final output, then return a buffer where the last segment // is in the correct place. (Data will shift backwards to the right spot while writing // other segments). expectedSize = DetermineCerBitStringTotalLength(tag, byteLength); EnsureWriteCapacity(expectedSize); int overhead = expectedSize - byteLength; // Start writing where the last content byte is in the correct place, which is // after all of the overhead, but ending before the two byte end-of-contents marker. int scratchStart = overhead - 2; ensureNoExtraCopy = _buffer; scratchSpace = _buffer.AsSpan(scratchStart, byteLength); // Don't let gapped-writes be unpredictable. scratchSpace.Clear(); } else { WriteTag(tag.AsPrimitive()); // The unused bits byte requires +1. WriteLength(byteLength + 1); _buffer[_offset] = (byte)unusedBitCount; _offset++; scratchSpace = _buffer.AsSpan(_offset, byteLength); } action(scratchSpace, state); // T-REC-X.690-201508 sec 11.2 // // This could be ignored for BER, but since DER is more common and // it likely suggests a program error on the caller, leave it enabled for // BER for now. if (!CheckValidLastByte(scratchSpace[byteLength - 1], unusedBitCount)) { // Since we are restoring _offset we won't clear this on a grow or Dispose, // so clear it now. _offset = savedOffset; scratchSpace.Clear(); // TODO: Probably warrants a distinct message. throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } if (segmentedWrite) { WriteConstructedCerBitString(tag, scratchSpace, unusedBitCount); Debug.Assert(_offset - savedOffset == expectedSize, $"expected size was {expectedSize}, actual was {_offset - savedOffset}"); Debug.Assert(_buffer == ensureNoExtraCopy, $"_buffer was replaced during while writing a bit string via callback"); } else { _offset += byteLength; } } #endif private static bool CheckValidLastByte(byte lastByte, int unusedBitCount) { // If 3 bits are "unused" then build a mask for them to check for 0. // 1 << 3 => 0b0000_1000 // subtract 1 => 0b000_0111 int mask = (1 << unusedBitCount) - 1; return ((lastByte & mask) == 0); } private static int DetermineCerBitStringTotalLength(Asn1Tag tag, int contentLength) { const int MaxCERSegmentSize = AsnReader.MaxCERSegmentSize; // Every segment has an "unused bit count" byte. const int MaxCERContentSize = MaxCERSegmentSize - 1; Debug.Assert(contentLength > MaxCERContentSize); int fullSegments = Math.DivRem(contentLength, MaxCERContentSize, out int lastContentSize); // The tag size is 1 byte. // The length will always be encoded as 82 03 E8 (3 bytes) // And 1000 content octets (by T-REC-X.690-201508 sec 9.2) const int FullSegmentEncodedSize = 1004; Debug.Assert( FullSegmentEncodedSize == 1 + 1 + MaxCERSegmentSize + GetEncodedLengthSubsequentByteCount(MaxCERSegmentSize)); int remainingEncodedSize; if (lastContentSize == 0) { remainingEncodedSize = 0; } else { // One byte of tag, minimum one byte of length, and one byte of unused bit count. remainingEncodedSize = 3 + lastContentSize + GetEncodedLengthSubsequentByteCount(lastContentSize); } // Reduce the number of copies by pre-calculating the size. // +2 for End-Of-Contents // +1 for 0x80 indefinite length // +tag length return fullSegments * FullSegmentEncodedSize + remainingEncodedSize + 3 + tag.CalculateEncodedSize(); } // T-REC-X.690-201508 sec 9.2, 8.6 private void WriteConstructedCerBitString(Asn1Tag tag, ReadOnlySpan<byte> payload, int unusedBitCount) { const int MaxCERSegmentSize = AsnReader.MaxCERSegmentSize; // Every segment has an "unused bit count" byte. const int MaxCERContentSize = MaxCERSegmentSize - 1; Debug.Assert(payload.Length > MaxCERContentSize); int expectedSize = DetermineCerBitStringTotalLength(tag, payload.Length); EnsureWriteCapacity(expectedSize); int savedOffset = _offset; WriteTag(tag.AsConstructed()); // T-REC-X.690-201508 sec 9.1 // Constructed CER uses the indefinite form. WriteLength(-1); byte[] ensureNoExtraCopy = _buffer; ReadOnlySpan<byte> remainingData = payload; Span<byte> dest; Asn1Tag primitiveBitString = Asn1Tag.PrimitiveBitString; while (remainingData.Length > MaxCERContentSize) { // T-REC-X.690-201508 sec 8.6.4.1 WriteTag(primitiveBitString); WriteLength(MaxCERSegmentSize); // 0 unused bits in this segment. _buffer[_offset] = 0; _offset++; dest = _buffer.AsSpan(_offset); remainingData.Slice(0, MaxCERContentSize).CopyTo(dest); remainingData = remainingData.Slice(MaxCERContentSize); _offset += MaxCERContentSize; } WriteTag(primitiveBitString); WriteLength(remainingData.Length + 1); _buffer[_offset] = (byte)unusedBitCount; _offset++; dest = _buffer.AsSpan(_offset); remainingData.CopyTo(dest); _offset += remainingData.Length; WriteEndOfContents(); Debug.Assert(_offset - savedOffset == expectedSize, $"expected size was {expectedSize}, actual was {_offset - savedOffset}"); Debug.Assert(_buffer == ensureNoExtraCopy, $"_buffer was replaced during {nameof(WriteConstructedCerBitString)}"); } } }
// 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.IO; using System.Threading; namespace System.Net.Http { internal sealed class CurlResponseMessage : HttpResponseMessage { private readonly CurlResponseStream _responseStream = new CurlResponseStream(); #region Properties internal CurlResponseStream ContentStream { get { return _responseStream; } } #endregion internal CurlResponseMessage(HttpRequestMessage request) { RequestMessage = request; Content = new StreamContent(_responseStream); } } internal sealed class CurlResponseStream : Stream { private volatile bool _disposed = false; private Stream _innerStream; private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private readonly ManualResetEventSlim _readerRequestingDataEvent = new ManualResetEventSlim(false); private readonly ManualResetEventSlim _writerHasDataEvent = new ManualResetEventSlim(false); private readonly ManualResetEventSlim _readerReadAllDataEvent = new ManualResetEventSlim(false); private object LockObject { get { return _cancellationTokenSource; } } internal void SignalComplete() { if (!_disposed) { _cancellationTokenSource.Cancel(); } } internal unsafe void WaitAndSignalReaders(byte* pointer, long length) { CheckDisposed(); _readerRequestingDataEvent.Wait(Timeout.InfiniteTimeSpan, _cancellationTokenSource.Token); lock (LockObject) { _innerStream = new UnmanagedMemoryStream(pointer, length); _readerReadAllDataEvent.Reset(); _readerRequestingDataEvent.Reset(); _writerHasDataEvent.Set(); } _readerReadAllDataEvent.Wait(Timeout.InfiniteTimeSpan, _cancellationTokenSource.Token);; } public override bool CanRead { get { return !_disposed; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { CheckDisposed(); throw new NotSupportedException(); } } public override long Position { get { CheckDisposed(); throw new NotSupportedException(); } set { CheckDisposed(); throw new NotSupportedException(); } } public override void Flush() { // Nothing to do. } //public override Task<int> ReadAsync(byte[] buffer, int offset, int count) //{ // // TODO: Consider proper implementation here using AsyncTaskMethodBuilder // return base.ReadAsync(buffer, offset, count); //} public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if ((long) offset + (long) count > (long) buffer.Length) { throw new ArgumentException("buffer"); } CheckDisposed(); do { lock (LockObject) { // Wait till data is available if (_innerStream == null) { SignalWriter(); continue; } int bytesRead = _innerStream.Read(buffer, offset, (int)Math.Min((long)count, _innerStream.Length)); if (_innerStream.Position == _innerStream.Length) { _innerStream.Dispose(); _innerStream = null; _readerReadAllDataEvent.Set(); } return bytesRead; } } while (WaitForWriter()); return 0; } public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); throw new NotSupportedException(); } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); throw new NotSupportedException(); } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { // Cancel any pending operations SignalComplete(); _disposed = true; lock (LockObject) { if (_innerStream != null) { _innerStream.Dispose(); _innerStream = null; } } _readerRequestingDataEvent.Dispose(); _writerHasDataEvent.Dispose(); _readerReadAllDataEvent.Dispose(); } base.Dispose(disposing); } #region Private private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } } private bool WaitForWriter() { try { _writerHasDataEvent.Wait(Timeout.InfiniteTimeSpan, _cancellationTokenSource.Token); return true; } catch (OperationCanceledException) { if (_writerHasDataEvent.Wait(TimeSpan.Zero)) { // If both are set, unblock the reader based on data availability lock (LockObject) { return (_innerStream != null); } } return false; } } private void SignalWriter() { Debug.Assert(Monitor.IsEntered(LockObject)); _writerHasDataEvent.Reset(); _readerRequestingDataEvent.Set(); } #endregion } }
using System; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using Android.Content; using Android.Support.V4.View; using Android.Support.V7.Widget; using Android.Views; using AColor = Android.Graphics.Color; using AView = Android.Views.View; namespace Xamarin.Forms.Platform.Android.AppCompat { public class FrameRenderer : CardView, IVisualElementRenderer, AView.IOnClickListener, AView.IOnTouchListener { readonly Lazy<GestureDetector> _gestureDetector; readonly PanGestureHandler _panGestureHandler; readonly PinchGestureHandler _pinchGestureHandler; readonly Lazy<ScaleGestureDetector> _scaleDetector; readonly TapGestureHandler _tapGestureHandler; float _defaultElevation = -1f; bool _clickable; bool _disposed; Frame _element; InnerGestureListener _gestureListener; VisualElementPackager _visualElementPackager; VisualElementTracker _visualElementTracker; NotifyCollectionChangedEventHandler _collectionChangeHandler; public FrameRenderer() : base(Forms.Context) { _tapGestureHandler = new TapGestureHandler(() => Element); _panGestureHandler = new PanGestureHandler(() => Element, Context.FromPixels); _pinchGestureHandler = new PinchGestureHandler(() => Element); _gestureDetector = new Lazy<GestureDetector>( () => new GestureDetector( _gestureListener = new InnerGestureListener(_tapGestureHandler.OnTap, _tapGestureHandler.TapGestureRecognizers, _panGestureHandler.OnPan, _panGestureHandler.OnPanStarted, _panGestureHandler.OnPanComplete))); _scaleDetector = new Lazy<ScaleGestureDetector>( () => new ScaleGestureDetector(Context, new InnerScaleListener(_pinchGestureHandler.OnPinch, _pinchGestureHandler.OnPinchStarted, _pinchGestureHandler.OnPinchEnded), Handler)); } protected CardView Control => this; protected Frame Element { get { return _element; } set { if (_element == value) return; Frame oldElement = _element; _element = value; OnElementChanged(new ElementChangedEventArgs<Frame>(oldElement, _element)); if (_element != null) _element.SendViewInitialized(Control); } } void IOnClickListener.OnClick(AView v) { _tapGestureHandler.OnSingleClick(); } bool IOnTouchListener.OnTouch(AView v, MotionEvent e) { var handled = false; if (_pinchGestureHandler.IsPinchSupported) { if (!_scaleDetector.IsValueCreated) ScaleGestureDetectorCompat.SetQuickScaleEnabled(_scaleDetector.Value, true); handled = _scaleDetector.Value.OnTouchEvent(e); } return _gestureDetector.Value.OnTouchEvent(e) || handled; } VisualElement IVisualElementRenderer.Element => Element; public event EventHandler<VisualElementChangedEventArgs> ElementChanged; SizeRequest IVisualElementRenderer.GetDesiredSize(int widthConstraint, int heightConstraint) { Context context = Context; return new SizeRequest(new Size(context.ToPixels(20), context.ToPixels(20))); } void IVisualElementRenderer.SetElement(VisualElement element) { var frame = element as Frame; if (frame == null) throw new ArgumentException("Element must be of type Frame"); Element = frame; if (!string.IsNullOrEmpty(Element.AutomationId)) ContentDescription = Element.AutomationId; } VisualElementTracker IVisualElementRenderer.Tracker => _visualElementTracker; void IVisualElementRenderer.UpdateLayout() { VisualElementTracker tracker = _visualElementTracker; tracker?.UpdateLayout(); } ViewGroup IVisualElementRenderer.ViewGroup => this; protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_gestureListener != null) { _gestureListener.Dispose(); _gestureListener = null; } if (_visualElementTracker != null) { _visualElementTracker.Dispose(); _visualElementTracker = null; } if (_visualElementPackager != null) { _visualElementPackager.Dispose(); _visualElementPackager = null; } if (Element != null) Element.PropertyChanged -= OnElementPropertyChanged; } base.Dispose(disposing); } protected virtual void OnElementChanged(ElementChangedEventArgs<Frame> e) { ElementChanged?.Invoke(this, new VisualElementChangedEventArgs(e.OldElement, e.NewElement)); if (e.OldElement != null) { e.OldElement.PropertyChanged -= OnElementPropertyChanged; UnsubscribeGestureRecognizers(e.OldElement); } if (e.NewElement != null) { if (_visualElementTracker == null) { SetOnClickListener(this); SetOnTouchListener(this); UpdateGestureRecognizers(true); _visualElementTracker = new VisualElementTracker(this); _visualElementPackager = new VisualElementPackager(this); _visualElementPackager.Load(); } e.NewElement.PropertyChanged += OnElementPropertyChanged; UpdateShadow(); UpdateBackgroundColor(); SubscribeGestureRecognizers(e.NewElement); } } protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { if (Element == null) return; var children = Element.LogicalChildren; for (var i = 0; i < children.Count; i++) { var visualElement = children[i] as VisualElement; if (visualElement == null) continue; IVisualElementRenderer renderer = Android.Platform.GetRenderer(visualElement); renderer?.UpdateLayout(); } } void HandleGestureRecognizerCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { UpdateGestureRecognizers(); } void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == Frame.HasShadowProperty.PropertyName) UpdateShadow(); else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName) UpdateBackgroundColor(); } void SubscribeGestureRecognizers(VisualElement element) { var view = element as View; if (view == null) return; if (_collectionChangeHandler == null) _collectionChangeHandler = HandleGestureRecognizerCollectionChanged; var observableCollection = (ObservableCollection<IGestureRecognizer>)view.GestureRecognizers; observableCollection.CollectionChanged += _collectionChangeHandler; } void UnsubscribeGestureRecognizers(VisualElement element) { var view = element as View; if (view == null || _collectionChangeHandler == null) return; var observableCollection = (ObservableCollection<IGestureRecognizer>)view.GestureRecognizers; observableCollection.CollectionChanged -= _collectionChangeHandler; } void UpdateBackgroundColor() { Color bgColor = Element.BackgroundColor; SetCardBackgroundColor(bgColor.IsDefault ? AColor.White : bgColor.ToAndroid()); } void UpdateClickable(bool force = false) { var view = Element as View; if (view == null) return; bool newValue = view.ShouldBeMadeClickable(); if (force || _clickable != newValue) { Clickable = newValue; _clickable = newValue; } } void UpdateGestureRecognizers(bool forceClick = false) { if (Element == null) return; UpdateClickable(forceClick); } void UpdateShadow() { float elevation = _defaultElevation; if (elevation == -1f) _defaultElevation = elevation = CardElevation; if (Element.HasShadow) CardElevation = elevation; else CardElevation = 0f; } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using Encog.Util.HTTP; using Encog.Util.File; namespace Encog.Bot { /// <summary> /// Utility class for bots. /// </summary> public class BotUtil { /// <summary> /// How much data to read at once. /// </summary> public static int BufferSize = 8192; /// <summary> /// This method is very useful for grabbing information from a HTML page. /// </summary> /// <param name="str">The string to search.</param> /// <param name="token1">The text, or tag, that comes before the desired text</param> /// <param name="token2">The text, or tag, that comes after the desired text</param> /// <param name="index">Index in the string to start searching from.</param> /// <param name="occurence">What occurence.</param> /// <returns>The contents of the URL that was downloaded.</returns> public static String ExtractFromIndex(String str, String token1, String token2, int index, int occurence) { // convert everything to lower case String searchStr = str.ToLower(); String token1Lower = token1.ToLower(); String token2Lower = token2.ToLower(); int count = occurence; // now search int location1 = index - 1; do { location1 = searchStr.IndexOf(token1Lower, location1 + 1); if (location1 == -1) { return null; } count--; } while (count > 0); // return the result from the original string that has mixed // case int location2 = searchStr.IndexOf(token2Lower, location1 + 1); if (location2 == -1) { return null; } return str.Substring(location1 + token1Lower.Length, location2 - (location1 + token1.Length)); } /// <summary> /// This method is very useful for grabbing information from a HTML page. /// </summary> /// <param name="str">The string to search.</param> /// <param name="token1">The text, or tag, that comes before the desired text.</param> /// <param name="token2">The text, or tag, that comes after the desired text.</param> /// <param name="index">Which occurrence of token1 to use, 1 for the first.</param> /// <returns>The contents of the URL that was downloaded.</returns> public static String Extract(String str, String token1, String token2, int index) { // convert everything to lower case String searchStr = str.ToLower(); String token1Lower = token1.ToLower(); String token2Lower = token2.ToLower(); int count = index; // now search int location1 = -1; do { location1 = searchStr.IndexOf(token1Lower, location1 + 1); if (location1 == -1) { return null; } count--; } while (count > 0); // return the result from the original string that has mixed // case int location2 = searchStr.IndexOf(token2Lower, location1 + 1); if (location2 == -1) { return null; } return str.Substring(location1 + token1Lower.Length, location2 - (location1 + token1.Length)); } /// <summary> /// Post to a page. /// </summary> /// <param name="uri">The URI to post to.</param> /// <param name="param">The post params.</param> /// <returns>The HTTP response.</returns> public static String POSTPage(Uri uri, IDictionary<String, String> param) { WebRequest req = WebRequest.Create(uri); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; var postString = new StringBuilder(); foreach (String key in param.Keys) { String value = param[key]; if (value != null) { if (postString.Length != 0) postString.Append('&'); postString.Append(key); postString.Append('='); postString.Append(FormUtility.Encode(value)); } } byte[] bytes = Encoding.ASCII.GetBytes(postString.ToString()); req.ContentLength = bytes.Length; Stream os = req.GetRequestStream(); os.Write(bytes, 0, bytes.Length); os.Close(); WebResponse resp = req.GetResponse(); if (resp == null) return null; var sr = new StreamReader(resp.GetResponseStream()); return sr.ReadToEnd().Trim(); } /// <summary> /// Post bytes to a page. /// </summary> /// <param name="uri">The URI to post to.</param> /// <param name="bytes">The bytes to post.</param> /// <param name="length">The length of the posted data.</param> /// <returns>The HTTP response.</returns> public static String POSTPage(Uri uri, byte[] bytes, int length) { WebRequest webRequest = WebRequest.Create(uri); //webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "POST"; webRequest.ContentLength = length; Stream os = null; try { // send the Post webRequest.ContentLength = bytes.Length; //Count bytes to send os = webRequest.GetRequestStream(); os.Write(bytes, 0, length); //Send it } catch (WebException ex) { throw new BotError(ex); } finally { if (os != null) { os.Flush(); } } try { // get the response WebResponse webResponse = webRequest.GetResponse(); if (webResponse == null) { return null; } var sr = new StreamReader(webResponse.GetResponseStream()); return sr.ReadToEnd(); } catch (WebException ex) { throw new BotError(ex); } } /// <summary> /// Load the specified web page into a string. /// </summary> /// <param name="url">The url to load.</param> /// <returns>The web page as a string.</returns> public static String LoadPage(Uri url) { try { var result = new StringBuilder(); var buffer = new byte[BufferSize]; int length; WebRequest http = WebRequest.Create(url); var response = (HttpWebResponse) http.GetResponse(); Stream istream = response.GetResponseStream(); do { length = istream.Read(buffer, 0, buffer.Length); if (length > 0) { String str = Encoding.UTF8.GetString(buffer, 0, length); result.Append(str); } } while (length > 0); return result.ToString(); } catch (IOException e) { #if logging if (LOGGER.IsErrorEnabled) { LOGGER.Error("Exception", e); } #endif throw new BotError(e); } } /// <summary> /// Private constructor. /// </summary> private BotUtil() { } /// <summary> /// Post to a page. /// </summary> /// <param name="uri">The URI to post to.</param> /// <param name="stream">The stream.</param> /// <returns>The page returned.</returns> public static string POSTPage(Uri uri, Stream stream) { WebRequest req = WebRequest.Create(uri); //req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; Stream os = req.GetRequestStream(); FileUtil.CopyStream(stream, os); os.Close(); WebResponse resp = req.GetResponse(); if (resp == null) return null; var sr = new StreamReader(resp.GetResponseStream()); return sr.ReadToEnd().Trim(); } public static void DownloadPage(Uri uri, string file) { var Client = new WebClient(); Client.DownloadFile(uri, file); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.Devices.PointOfService; using System.Threading.Tasks; using Windows.Devices.Enumeration; using SDKTemplate; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace PosPrinterSample { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario3_MultipleReceipt : Page { // Uncomment the following line if you need a pointer back to the MainPage. // This value should be obtained in OnNavigatedTo in the e.Parameter argument private MainPage rootPage; PosPrinter printerInstance1 = null; PosPrinter printerInstance2 = null; ClaimedPosPrinter claimedPrinter1 = null; ClaimedPosPrinter claimedPrinter2 = null; bool IsAnImportantTransactionInstance1; bool IsAnImportantTransactionInstance2; public Scenario3_MultipleReceipt() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; ResetTheScenarioState(); } protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { ResetTheScenarioState(); } async void FindReceiptPrinter_Click(object sender, RoutedEventArgs e) { await FindReceiptPrinterInstances(); } /// <summary> /// Claims printer instance 1 /// </summary> async void Claim1_Click(object sender, RoutedEventArgs e) { await ClaimAndEnablePrinter1(); } /// <summary> /// Releases claim of printer instance 1 /// </summary> void Release1_Click(object sender, RoutedEventArgs e) { if (claimedPrinter1 != null) { claimedPrinter1.ReleaseDeviceRequested -= ClaimedPrinter1_ReleaseDeviceRequested; claimedPrinter1.Dispose(); claimedPrinter1 = null; if (printerInstance1 != null) { printerInstance1.Dispose(); printerInstance1 = null; } rootPage.NotifyUser("Released claimed Instance 1", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Instance 1 not claimed to release", NotifyType.StatusMessage); } } /// <summary> /// Claims printer instance 2 /// </summary> async void Claim2_Click(object sender, RoutedEventArgs e) { await ClaimAndEnablePrinter2(); } /// <summary> /// Releases claim of printer instance 2 /// </summary> void Release2_Click(object sender, RoutedEventArgs e) { if (claimedPrinter2 != null) { claimedPrinter2.ReleaseDeviceRequested -= ClaimedPrinter2_ReleaseDeviceRequested; claimedPrinter2.Dispose(); claimedPrinter2 = null; if (printerInstance2 != null) { printerInstance2.Dispose(); printerInstance2 = null; } rootPage.NotifyUser("Released claimed Instance 2", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Instance 2 not claimed to release", NotifyType.StatusMessage); } } /// <summary> ///Actual claim method task that claims and enables printer instance 1 asynchronously. It then adds the releasedevicerequested event handler as well to the claimed printer. /// </summary> private async Task<bool> ClaimAndEnablePrinter1() { if (printerInstance1 == null) { rootPage.NotifyUser("Cound not claim printer. Make sure you find printer first.", NotifyType.ErrorMessage); return false; } if (claimedPrinter1 == null) { claimedPrinter1 = await printerInstance1.ClaimPrinterAsync(); if (claimedPrinter1 != null) { claimedPrinter1.ReleaseDeviceRequested += ClaimedPrinter1_ReleaseDeviceRequested; rootPage.NotifyUser("Claimed Printer Instance 1", NotifyType.StatusMessage); if (!await claimedPrinter1.EnableAsync()) { rootPage.NotifyUser("Could not enable printer instance 1.", NotifyType.ErrorMessage); } else { return true; } } else { rootPage.NotifyUser("Claim Printer instance 1 failed. Probably because instance 2 is holding on to it.", NotifyType.ErrorMessage); } } return false; } /// <summary> ///Actual claim method task that claims and enables printer instance 2 asynchronously. It then adds the releasedevicerequested event handler as well to the claimed printer. /// </summary> private async Task<bool> ClaimAndEnablePrinter2() { if (printerInstance2 == null) { rootPage.NotifyUser("Cound not claim printer. Make sure you find printer first.", NotifyType.ErrorMessage); return false; } if (printerInstance1 != null && claimedPrinter2 == null) { rootPage.NotifyUser("Trying to claim instance 2.", NotifyType.StatusMessage); claimedPrinter2 = await printerInstance2.ClaimPrinterAsync(); if (claimedPrinter2 != null) { claimedPrinter2.ReleaseDeviceRequested += ClaimedPrinter2_ReleaseDeviceRequested; rootPage.NotifyUser("Claimed Printer Instance 2", NotifyType.StatusMessage); if (!await claimedPrinter2.EnableAsync()) { rootPage.NotifyUser("Could not enable printer instance 2.", NotifyType.ErrorMessage); } else { return true; } } else { rootPage.NotifyUser("Claim Printer instance 2 failed. Probably because instance 1 is holding on to it.", NotifyType.ErrorMessage); } } return false; } /// <summary> /// Find the first receipt printer and create two instances of it. /// </summary> /// <returns></returns> private async Task<bool> FindReceiptPrinterInstances() { if (printerInstance1 == null || printerInstance2 == null) { rootPage.NotifyUser("Finding printer", NotifyType.StatusMessage); printerInstance1 = await DeviceHelpers.GetFirstReceiptPrinterAsync(); if (printerInstance1 != null) { rootPage.NotifyUser("Got Printer Instance 1 with Device Id : " + printerInstance1.DeviceId, NotifyType.StatusMessage); // Create another instance of the same printer. if (printerInstance2 != null) { printerInstance2.Dispose(); printerInstance2 = null; } printerInstance2 = await PosPrinter.FromIdAsync(printerInstance1.DeviceId); if (printerInstance2 != null) { rootPage.NotifyUser("Got Printer Instance 2 with Device Id : " + printerInstance2.DeviceId, NotifyType.StatusMessage); return true; } else { rootPage.NotifyUser("Couldn't create second instance of printer.", NotifyType.StatusMessage); } return false; } else { rootPage.NotifyUser("No Printer found", NotifyType.ErrorMessage); return false; } } return true; } /// <summary> /// Reset all instances of claimed printer and remove event handlers. /// </summary> private void ResetTheScenarioState() { IsAnImportantTransactionInstance1 = true; IsAnImportantTransactionInstance2 = false; chkInstance1.IsChecked = true; chkInstance2.IsChecked = false; //Remove releasedevicerequested handler and dispose claimed printer object. if (claimedPrinter1 != null) { claimedPrinter1.ReleaseDeviceRequested -= ClaimedPrinter1_ReleaseDeviceRequested; claimedPrinter1.Dispose(); claimedPrinter1 = null; } if (claimedPrinter2 != null) { claimedPrinter2.ReleaseDeviceRequested -= ClaimedPrinter2_ReleaseDeviceRequested; claimedPrinter2.Dispose(); claimedPrinter2 = null; } if (printerInstance1 != null) { printerInstance1.Dispose(); printerInstance1 = null; } if (printerInstance2 != null) { printerInstance2.Dispose(); printerInstance2 = null; } } async void ClaimedPrinter1_ReleaseDeviceRequested(ClaimedPosPrinter sender, PosPrinterReleaseDeviceRequestedEventArgs args) { if (IsAnImportantTransactionInstance1) { await sender.RetainDeviceAsync(); } else { claimedPrinter1.ReleaseDeviceRequested -= ClaimedPrinter1_ReleaseDeviceRequested; claimedPrinter1.Dispose(); claimedPrinter1 = null; if (printerInstance1 != null) { printerInstance1.Dispose(); printerInstance1 = null; } } } async void ClaimedPrinter2_ReleaseDeviceRequested(ClaimedPosPrinter sender, PosPrinterReleaseDeviceRequestedEventArgs args) { if (IsAnImportantTransactionInstance2) { await sender.RetainDeviceAsync(); } else { claimedPrinter2.ReleaseDeviceRequested -= ClaimedPrinter2_ReleaseDeviceRequested; claimedPrinter2.Dispose(); claimedPrinter2 = null; if (printerInstance2 != null) { printerInstance2.Dispose(); printerInstance2 = null; } } } async void PrintLine1_Click(object sender, RoutedEventArgs e) { await PrintLine(txtPrintLine1.Text, claimedPrinter1); } async void PrintLine2_Click(object sender, RoutedEventArgs e) { await PrintLine(txtPrintLine2.Text, claimedPrinter2); } private async Task<bool> PrintLine(string message, ClaimedPosPrinter claimedPrinter) { if (claimedPrinter == null) { rootPage.NotifyUser("Claimed printer object is null. Cannot print.", NotifyType.ErrorMessage); return false; } if (claimedPrinter.Receipt == null) { rootPage.NotifyUser("No receipt printer object in claimed printer.", NotifyType.ErrorMessage); return false; } ReceiptPrintJob job = claimedPrinter.Receipt.CreateJob(); job.PrintLine(message); if (await job.ExecuteAsync()) { rootPage.NotifyUser("Printed line", NotifyType.StatusMessage); return true; } rootPage.NotifyUser("Was not able to print line", NotifyType.StatusMessage); return false; } private void EndScenario_Click(object sender, RoutedEventArgs e) { ResetTheScenarioState(); rootPage.NotifyUser("Disconnected Receipt Printer", NotifyType.StatusMessage); } private void chkInstance1_Checked(object sender, RoutedEventArgs e) { IsAnImportantTransactionInstance1 = true; } private void chkInstance2_Checked(object sender, RoutedEventArgs e) { IsAnImportantTransactionInstance2 = true; } private void chkInstance2_Unchecked(object sender, RoutedEventArgs e) { IsAnImportantTransactionInstance2 = false; } private void chkInstance1_Unchecked(object sender, RoutedEventArgs e) { IsAnImportantTransactionInstance1 = false; } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Xml.Linq; using Newtonsoft.Json.Utilities; using System.Linq; namespace Newtonsoft.Json.Converters { #region XmlNodeWrappers #endregion #region Interfaces internal interface IXmlDocument : IXmlNode { IXmlNode CreateComment(string text); IXmlNode CreateTextNode(string text); IXmlNode CreateCDataSection(string data); IXmlNode CreateWhitespace(string text); IXmlNode CreateSignificantWhitespace(string text); IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone); IXmlNode CreateProcessingInstruction(string target, string data); IXmlElement CreateElement(string elementName); IXmlElement CreateElement(string qualifiedName, string namespaceUri); IXmlNode CreateAttribute(string name, string value); IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value); IXmlElement DocumentElement { get; } } internal interface IXmlDeclaration : IXmlNode { string Version { get; } string Encoding { get; set; } string Standalone { get; set; } } internal interface IXmlElement : IXmlNode { void SetAttributeNode(IXmlNode attribute); string GetPrefixOfNamespace(string namespaceUri); } internal interface IXmlNode { XmlNodeType NodeType { get; } string LocalName { get; } IList<IXmlNode> ChildNodes { get; } IList<IXmlNode> Attributes { get; } IXmlNode ParentNode { get; } string Value { get; set; } IXmlNode AppendChild(IXmlNode newChild); string NamespaceUri { get; } object WrappedNode { get; } } #endregion #region XNodeWrappers internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration { internal XDeclaration Declaration { get; private set; } public XDeclarationWrapper(XDeclaration declaration) : base(null) { Declaration = declaration; } public override XmlNodeType NodeType { get { return XmlNodeType.XmlDeclaration; } } public string Version { get { return Declaration.Version; } } public string Encoding { get { return Declaration.Encoding; } set { Declaration.Encoding = value; } } public string Standalone { get { return Declaration.Standalone; } set { Declaration.Standalone = value; } } } internal class XDocumentWrapper : XContainerWrapper, IXmlDocument { private XDocument Document { get { return (XDocument)WrappedNode; } } public XDocumentWrapper(XDocument document) : base(document) { } public override IList<IXmlNode> ChildNodes { get { IList<IXmlNode> childNodes = base.ChildNodes; if (Document.Declaration != null) childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration)); return childNodes; } } public IXmlNode CreateComment(string text) { return new XObjectWrapper(new XComment(text)); } public IXmlNode CreateTextNode(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateCDataSection(string data) { return new XObjectWrapper(new XCData(data)); } public IXmlNode CreateWhitespace(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateSignificantWhitespace(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) { return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone)); } public IXmlNode CreateProcessingInstruction(string target, string data) { return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data)); } public IXmlElement CreateElement(string elementName) { return new XElementWrapper(new XElement(elementName)); } public IXmlElement CreateElement(string qualifiedName, string namespaceUri) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri))); } public IXmlNode CreateAttribute(string name, string value) { return new XAttributeWrapper(new XAttribute(name, value)); } public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value)); } public IXmlElement DocumentElement { get { if (Document.Root == null) return null; return new XElementWrapper(Document.Root); } } public override IXmlNode AppendChild(IXmlNode newChild) { XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper; if (declarationWrapper != null) { Document.Declaration = declarationWrapper.Declaration; return declarationWrapper; } else { return base.AppendChild(newChild); } } } internal class XTextWrapper : XObjectWrapper { private XText Text { get { return (XText)WrappedNode; } } public XTextWrapper(XText text) : base(text) { } public override string Value { get { return Text.Value; } set { Text.Value = value; } } public override IXmlNode ParentNode { get { if (Text.Parent == null) return null; return XContainerWrapper.WrapNode(Text.Parent); } } } internal class XCommentWrapper : XObjectWrapper { private XComment Text { get { return (XComment)WrappedNode; } } public XCommentWrapper(XComment text) : base(text) { } public override string Value { get { return Text.Value; } set { Text.Value = value; } } public override IXmlNode ParentNode { get { if (Text.Parent == null) return null; return XContainerWrapper.WrapNode(Text.Parent); } } } internal class XProcessingInstructionWrapper : XObjectWrapper { private XProcessingInstruction ProcessingInstruction { get { return (XProcessingInstruction)WrappedNode; } } public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction) : base(processingInstruction) { } public override string LocalName { get { return ProcessingInstruction.Target; } } public override string Value { get { return ProcessingInstruction.Data; } set { ProcessingInstruction.Data = value; } } } internal class XContainerWrapper : XObjectWrapper { private XContainer Container { get { return (XContainer)WrappedNode; } } public XContainerWrapper(XContainer container) : base(container) { } public override IList<IXmlNode> ChildNodes { get { return Container.Nodes().Select(n => WrapNode(n)).ToList(); } } public override IXmlNode ParentNode { get { if (Container.Parent == null) return null; return WrapNode(Container.Parent); } } internal static IXmlNode WrapNode(XObject node) { if (node is XDocument) return new XDocumentWrapper((XDocument)node); else if (node is XElement) return new XElementWrapper((XElement)node); else if (node is XContainer) return new XContainerWrapper((XContainer)node); else if (node is XProcessingInstruction) return new XProcessingInstructionWrapper((XProcessingInstruction)node); else if (node is XText) return new XTextWrapper((XText)node); else if (node is XComment) return new XCommentWrapper((XComment)node); else if (node is XAttribute) return new XAttributeWrapper((XAttribute) node); else return new XObjectWrapper(node); } public override IXmlNode AppendChild(IXmlNode newChild) { Container.Add(newChild.WrappedNode); return newChild; } } internal class XObjectWrapper : IXmlNode { private readonly XObject _xmlObject; public XObjectWrapper(XObject xmlObject) { _xmlObject = xmlObject; } public object WrappedNode { get { return _xmlObject; } } public virtual XmlNodeType NodeType { get { return _xmlObject.NodeType; } } public virtual string LocalName { get { return null; } } public virtual IList<IXmlNode> ChildNodes { get { return new List<IXmlNode>(); } } public virtual IList<IXmlNode> Attributes { get { return null; } } public virtual IXmlNode ParentNode { get { return null; } } public virtual string Value { get { return null; } set { throw new InvalidOperationException(); } } public virtual IXmlNode AppendChild(IXmlNode newChild) { throw new InvalidOperationException(); } public virtual string NamespaceUri { get { return null; } } } internal class XAttributeWrapper : XObjectWrapper { private XAttribute Attribute { get { return (XAttribute)WrappedNode; } } public XAttributeWrapper(XAttribute attribute) : base(attribute) { } public override string Value { get { return Attribute.Value; } set { Attribute.Value = value; } } public override string LocalName { get { return Attribute.Name.LocalName; } } public override string NamespaceUri { get { return Attribute.Name.NamespaceName; } } public override IXmlNode ParentNode { get { if (Attribute.Parent == null) return null; return XContainerWrapper.WrapNode(Attribute.Parent); } } } internal class XElementWrapper : XContainerWrapper, IXmlElement { private XElement Element { get { return (XElement) WrappedNode; } } public XElementWrapper(XElement element) : base(element) { } public void SetAttributeNode(IXmlNode attribute) { XObjectWrapper wrapper = (XObjectWrapper)attribute; Element.Add(wrapper.WrappedNode); } public override IList<IXmlNode> Attributes { get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast<IXmlNode>().ToList(); } } public override string Value { get { return Element.Value; } set { Element.Value = value; } } public override string LocalName { get { return Element.Name.LocalName; } } public override string NamespaceUri { get { return Element.Name.NamespaceName; } } public string GetPrefixOfNamespace(string namespaceUri) { return Element.GetPrefixOfNamespace(namespaceUri); } } #endregion /// <summary> /// Converts XML to and from JSON. /// </summary> public class XmlNodeConverter : JsonConverter { private const string TextName = "#text"; private const string CommentName = "#comment"; private const string CDataName = "#cdata-section"; private const string WhitespaceName = "#whitespace"; private const string SignificantWhitespaceName = "#significant-whitespace"; private const string DeclarationName = "?xml"; private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json"; /// <summary> /// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements. /// </summary> /// <value>The name of the deserialize root element.</value> public string DeserializeRootElementName { get; set; } /// <summary> /// Gets or sets a flag to indicate whether to write the Json.NET array attribute. /// This attribute helps preserve arrays when converting the written XML back to JSON. /// </summary> /// <value><c>true</c> if the array attibute is written to the XML; otherwise, <c>false</c>.</value> public bool WriteArrayAttribute { get; set; } /// <summary> /// Gets or sets a value indicating whether to write the root JSON object. /// </summary> /// <value><c>true</c> if the JSON root object is omitted; otherwise, <c>false</c>.</value> public bool OmitRootObject { get; set; } #region Writing /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="serializer">The calling serializer.</param> /// <param name="value">The value.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IXmlNode node = WrapXml(value); XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); PushParentNamespaces(node, manager); if (!OmitRootObject) writer.WriteStartObject(); SerializeNode(writer, node, manager, !OmitRootObject); if (!OmitRootObject) writer.WriteEndObject(); } private IXmlNode WrapXml(object value) { if (value is XObject) return XContainerWrapper.WrapNode((XObject)value); throw new ArgumentException("Value must be an XML object.", "value"); } private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { List<IXmlNode> parentElements = null; IXmlNode parent = node; while ((parent = parent.ParentNode) != null) { if (parent.NodeType == XmlNodeType.Element) { if (parentElements == null) parentElements = new List<IXmlNode>(); parentElements.Add(parent); } } if (parentElements != null) { parentElements.Reverse(); foreach (IXmlNode parentElement in parentElements) { manager.PushScope(); foreach (IXmlNode attribute in parentElement.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns") manager.AddNamespace(attribute.LocalName, attribute.Value); } } } } private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager) { string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/")) ? null : manager.LookupPrefix(node.NamespaceUri); if (!string.IsNullOrEmpty(prefix)) return prefix + ":" + node.LocalName; else return node.LocalName; } private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager) { switch (node.NodeType) { case XmlNodeType.Attribute: if (node.NamespaceUri == JsonNamespaceUri) return "$" + node.LocalName; else return "@" + ResolveFullName(node, manager); case XmlNodeType.CDATA: return CDataName; case XmlNodeType.Comment: return CommentName; case XmlNodeType.Element: return ResolveFullName(node, manager); case XmlNodeType.ProcessingInstruction: return "?" + ResolveFullName(node, manager); case XmlNodeType.XmlDeclaration: return DeclarationName; case XmlNodeType.SignificantWhitespace: return SignificantWhitespaceName; case XmlNodeType.Text: return TextName; case XmlNodeType.Whitespace: return WhitespaceName; default: throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType); } } private bool IsArray(IXmlNode node) { IXmlNode jsonArrayAttribute = (node.Attributes != null) ? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceUri == JsonNamespaceUri) : null; return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value)); } private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { // group nodes together by name Dictionary<string, List<IXmlNode>> nodesGroupedByName = new Dictionary<string, List<IXmlNode>>(); for (int i = 0; i < node.ChildNodes.Count; i++) { IXmlNode childNode = node.ChildNodes[i]; string nodeName = GetPropertyName(childNode, manager); List<IXmlNode> nodes; if (!nodesGroupedByName.TryGetValue(nodeName, out nodes)) { nodes = new List<IXmlNode>(); nodesGroupedByName.Add(nodeName, nodes); } nodes.Add(childNode); } // loop through grouped nodes. write single name instances as normal, // write multiple names together in an array foreach (KeyValuePair<string, List<IXmlNode>> nodeNameGroup in nodesGroupedByName) { List<IXmlNode> groupedNodes = nodeNameGroup.Value; bool writeArray; if (groupedNodes.Count == 1) { writeArray = IsArray(groupedNodes[0]); } else { writeArray = true; } if (!writeArray) { SerializeNode(writer, groupedNodes[0], manager, writePropertyName); } else { string elementNames = nodeNameGroup.Key; if (writePropertyName) writer.WritePropertyName(elementNames); writer.WriteStartArray(); for (int i = 0; i < groupedNodes.Count; i++) { SerializeNode(writer, groupedNodes[i], manager, false); } writer.WriteEndArray(); } } } private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { switch (node.NodeType) { case XmlNodeType.Document: case XmlNodeType.DocumentFragment: SerializeGroupedNodes(writer, node, manager, writePropertyName); break; case XmlNodeType.Element: if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0) { SerializeGroupedNodes(writer, node, manager, false); } else { manager.PushScope(); foreach (IXmlNode attribute in node.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/") { string namespacePrefix = (attribute.LocalName != "xmlns") ? attribute.LocalName : string.Empty; string namespaceUri = attribute.Value; manager.AddNamespace(namespacePrefix, namespaceUri); } } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) { // write elements with a single text child as a name value pair writer.WriteValue(node.ChildNodes[0].Value); } else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes)) { // empty element writer.WriteNull(); } else { writer.WriteStartObject(); for (int i = 0; i < node.Attributes.Count; i++) { SerializeNode(writer, node.Attributes[i], manager, true); } SerializeGroupedNodes(writer, node, manager, true); writer.WriteEndObject(); } manager.PopScope(); } break; case XmlNodeType.Comment: if (writePropertyName) writer.WriteComment(node.Value); break; case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri) return; if (node.NamespaceUri == JsonNamespaceUri) { if (node.LocalName == "Array") return; } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteValue(node.Value); break; case XmlNodeType.XmlDeclaration: IXmlDeclaration declaration = (IXmlDeclaration)node; writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(declaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(declaration.Version); } if (!string.IsNullOrEmpty(declaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(declaration.Encoding); } if (!string.IsNullOrEmpty(declaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(declaration.Standalone); } writer.WriteEndObject(); break; default: throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType); } } #endregion #region Reading /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); IXmlDocument document = null; IXmlNode rootNode = null; if (typeof(XObject).IsAssignableFrom(objectType)) { if (objectType != typeof (XDocument) && objectType != typeof (XElement)) throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement."); XDocument d = new XDocument(); document = new XDocumentWrapper(d); rootNode = document; } if (document == null || rootNode == null) throw new JsonSerializationException("Unexpected type when converting XML: " + objectType); if (reader.TokenType != JsonToken.StartObject) throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object."); if (!string.IsNullOrEmpty(DeserializeRootElementName)) { //rootNode = document.CreateElement(DeserializeRootElementName); //document.AppendChild(rootNode); ReadElement(reader, document, rootNode, DeserializeRootElementName, manager); } else { reader.Read(); DeserializeNode(reader, document, manager, rootNode); } if (objectType == typeof(XElement)) { XElement element = (XElement)document.DocumentElement.WrappedNode; element.Remove(); return element; } return document.WrappedNode; } private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode) { switch (propertyName) { case TextName: currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString())); break; case CDataName: currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString())); break; case WhitespaceName: currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString())); break; case SignificantWhitespaceName: currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString())); break; default: // processing instructions and the xml declaration start with ? if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?') { CreateInstruction(reader, document, currentNode, propertyName); } else { if (reader.TokenType == JsonToken.StartArray) { // handle nested arrays ReadArrayElements(reader, document, propertyName, currentNode, manager); return; } // have to wait until attributes have been parsed before creating element // attributes may contain namespace info used by the element ReadElement(reader, document, currentNode, propertyName, manager); } break; } } private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { if (string.IsNullOrEmpty(propertyName)) throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML."); Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager); string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); if (propertyName.StartsWith("@")) { var attributeName = propertyName.Substring(1); var attributeValue = reader.Value.ToString(); var attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); var attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue) : document.CreateAttribute(attributeName, attributeValue); ((IXmlElement)currentNode).SetAttributeNode(attribute); } else { IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair<string, string> nameValue in attributeNameValues) { string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value) : document.CreateAttribute(nameValue.Key, nameValue.Value); element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Boolean || reader.TokenType == JsonToken.Date) { element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } } } } private string ConvertTokenToXmlValue(JsonReader reader) { if (reader.TokenType == JsonToken.String) { return reader.Value.ToString(); } else if (reader.TokenType == JsonToken.Integer) { return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Float) { return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Boolean) { return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Date) { DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture); return XmlConvert.ToString(d); } else if (reader.TokenType == JsonToken.Null) { return null; } else { throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager) { string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(nestedArrayElement); int count = 0; while (reader.Read() && reader.TokenType != JsonToken.EndArray) { DeserializeValue(reader, document, manager, propertyName, nestedArrayElement); count++; } if (WriteArrayAttribute) { AddJsonArrayAttribute(nestedArrayElement, document); } if (count == 1 && WriteArrayAttribute) { IXmlElement arrayElement = nestedArrayElement.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName); AddJsonArrayAttribute(arrayElement, document); } } private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document) { element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true")); // linq to xml doesn't automatically include prefixes via the namespace manager if (element is XElementWrapper) { if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null) { element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri)); } } } private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) { Dictionary<string, string> attributeNameValues = new Dictionary<string, string>(); bool finishedAttributes = false; bool finishedElement = false; // a string token means the element only has a single text child if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.Boolean && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Date && reader.TokenType != JsonToken.StartConstructor) { // read properties until first non-attribute is encountered while (!finishedAttributes && !finishedElement && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string attributeName = reader.Value.ToString(); if (!string.IsNullOrEmpty(attributeName)) { char firstChar = attributeName[0]; string attributeValue; switch (firstChar) { case '@': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = ConvertTokenToXmlValue(reader); attributeNameValues.Add(attributeName, attributeValue); string namespacePrefix; if (IsNamespaceAttribute(attributeName, out namespacePrefix)) { manager.AddNamespace(namespacePrefix, attributeValue); } break; case '$': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = reader.Value.ToString(); // check that JsonNamespaceUri is in scope // if it isn't then add it to document and namespace manager string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); if (jsonPrefix == null) { // ensure that the prefix used is free int? i = null; while (manager.LookupNamespace("json" + i) != null) { i = i.GetValueOrDefault() + 1; } jsonPrefix = "json" + i; attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri); manager.AddNamespace(jsonPrefix, JsonNamespaceUri); } attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue); break; default: finishedAttributes = true; break; } } else { finishedAttributes = true; } break; case JsonToken.EndObject: finishedElement = true; break; default: throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType); } } } return attributeNameValues; } private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName) { if (propertyName == DeclarationName) { string version = null; string encoding = null; string standalone = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { switch (reader.Value.ToString()) { case "@version": reader.Read(); version = reader.Value.ToString(); break; case "@encoding": reader.Read(); encoding = reader.Value.ToString(); break; case "@standalone": reader.Read(); standalone = reader.Value.ToString(); break; default: throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); } } IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone); currentNode.AppendChild(declaration); } else { IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString()); currentNode.AppendChild(instruction); } } private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) { string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(elementName, ns) : document.CreateElement(elementName); return element; } private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode) { do { switch (reader.TokenType) { case JsonToken.PropertyName: if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null) throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); string propertyName = reader.Value.ToString(); reader.Read(); if (reader.TokenType == JsonToken.StartArray) { int count = 0; while (reader.Read() && reader.TokenType != JsonToken.EndArray) { DeserializeValue(reader, document, manager, propertyName, currentNode); count++; } if (count == 1 && WriteArrayAttribute) { IXmlElement arrayElement = currentNode.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName); AddJsonArrayAttribute(arrayElement, document); } } else { DeserializeValue(reader, document, manager, propertyName, currentNode); } break; case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) { DeserializeValue(reader, document, manager, constructorName, currentNode); } break; case JsonToken.Comment: currentNode.AppendChild(document.CreateComment((string)reader.Value)); break; case JsonToken.EndObject: case JsonToken.EndArray: return; default: throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType); } } while (reader.TokenType == JsonToken.PropertyName || reader.Read()); // don't read if current token is a property. token was already read when parsing element attributes } /// <summary> /// Checks if the attributeName is a namespace attribute. /// </summary> /// <param name="attributeName">Attribute name to test.</param> /// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param> /// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns> private bool IsNamespaceAttribute(string attributeName, out string prefix) { if (attributeName.StartsWith("xmlns", StringComparison.Ordinal)) { if (attributeName.Length == 5) { prefix = string.Empty; return true; } else if (attributeName[5] == ':') { prefix = attributeName.Substring(6, attributeName.Length - 6); return true; } } prefix = null; return false; } private IEnumerable<IXmlNode> ValueAttributes(IEnumerable<IXmlNode> c) { return c.Where(a => a.NamespaceUri != JsonNamespaceUri); } #endregion /// <summary> /// Determines whether this instance can convert the specified value type. /// </summary> /// <param name="valueType">Type of the value.</param> /// <returns> /// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type valueType) { if (typeof(XObject).IsAssignableFrom(valueType)) return true; return false; } } } #endif
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using log4net; using NetGore.Collections; using NetGore.Graphics; using NetGore.World; using SFML.Graphics; namespace NetGore.Features.Emoticons { /// <summary> /// Handles displaying the individual emoticon instances. /// </summary> /// <typeparam name="TKey">The emoticon key.</typeparam> /// <typeparam name="TValue">The emoticon information.</typeparam> public class EmoticonDisplayManager<TKey, TValue> where TValue : EmoticonInfo<TKey> { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// A dictionary of the active emoticons. /// </summary> readonly Dictionary<ISpatial, EmoticonDisplayInfo> _activeEmoticons = new Dictionary<ISpatial, EmoticonDisplayInfo>(); readonly EmoticonInfoManagerBase<TKey, TValue> _emoticonInfoManager; /// <summary> /// Object pool used to spawn <see cref="EmoticonDisplayInfo"/> instances. /// </summary> readonly ObjectPool<EmoticonDisplayInfo> _objectPool = new ObjectPool<EmoticonDisplayInfo>( x => new EmoticonDisplayInfo(), false); Func<ISpatial, Vector2> _getDrawPositionHandler; /// <summary> /// Initializes a new instance of the <see cref="EmoticonDisplayManager{TKey, TValue}"/> class. /// </summary> /// <param name="emoticonInfoManager">The <see cref="EmoticonInfoManagerBase{TKey, TValue}"/> to use to look up the information /// for emoticons.</param> public EmoticonDisplayManager(EmoticonInfoManagerBase<TKey, TValue> emoticonInfoManager) { _emoticonInfoManager = emoticonInfoManager; } /// <summary> /// Gets or sets the <see cref="Func{T,U}"/> used to get the world position to draw an emoticon at for the given /// <see cref="ISpatial"/>. If set to null, the default handler will be used. /// </summary> public Func<ISpatial, Vector2> GetDrawPositionHandler { get { return _getDrawPositionHandler; } set { if (value == null) value = DefaultGetDrawPosition; if (_getDrawPositionHandler == value) return; _getDrawPositionHandler = value; } } /// <summary> /// Adds an emoticon display. /// </summary> /// <param name="entity">The entity that emoted.</param> /// <param name="emoticon">The emoticon to display.</param> /// <param name="currentTime">The current game time.</param> /// <exception cref="ArgumentNullException"><paramref name="entity"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="emoticon"/> is invalid.</exception> public void Add(ISpatial entity, TKey emoticon, TickCount currentTime) { if (entity == null) throw new ArgumentNullException("entity"); var emoticonInfo = _emoticonInfoManager[emoticon]; if (emoticonInfo == null) { const string errmsg = "No EmoticonInfo associated with the emoticon `{0}`."; var err = string.Format(errmsg, emoticon); if (log.IsErrorEnabled) log.Error(err); Debug.Fail(err); throw new ArgumentException(err, "emoticon"); } EmoticonDisplayInfo obj; bool keyExists; // If an emoticon already exists, reuse that. Otherwise, get a new one from the pool. if (_activeEmoticons.ContainsKey(entity)) { obj = _activeEmoticons[entity]; keyExists = true; } else { obj = _objectPool.Acquire(); keyExists = false; } // Initialize obj.Initialize(emoticonInfo.GrhIndex, currentTime); // Add to the dictionary of active emoticons if (keyExists) _activeEmoticons[entity] = obj; else _activeEmoticons.Add(entity, obj); } /// <summary> /// Gets the position to draw the emoticon at. /// </summary> /// <param name="spatial">The <see cref="ISpatial"/> to get the draw position for.</param> /// <returns>The position to draw the emoticon at.</returns> static Vector2 DefaultGetDrawPosition(ISpatial spatial) { return (spatial.Position + (spatial.Size / 2f)) - new Vector2(6); } /// <summary> /// Draws all of the emoticons in this collection. /// </summary> /// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to draw to.</param> public void Draw(ISpriteBatch spriteBatch) { foreach (var kvp in _activeEmoticons) { Vector2 drawPos; if (GetDrawPositionHandler != null) drawPos = GetDrawPositionHandler(kvp.Key); else drawPos = DefaultGetDrawPosition(kvp.Key); kvp.Value.Draw(spriteBatch, drawPos); } } /// <summary> /// Updates all of the emoticons in this collection. /// </summary> /// <param name="currentTime">The current game time.</param> public void Update(TickCount currentTime) { var removeCount = 0; // Update all the living emoticons foreach (var value in _activeEmoticons.Values) { value.Update(currentTime); if (!value.IsAlive) removeCount++; } // If we counted any dead emoticons, remove them if (removeCount > 0) { var toRemove = _activeEmoticons.Where(x => !x.Value.IsAlive).ToImmutable(); foreach (var kvp in toRemove) { _activeEmoticons.Remove(kvp.Key); _objectPool.Free(kvp.Value); } } } /// <summary> /// Contains the information for a single display of an emoticon. /// </summary> class EmoticonDisplayInfo : IPoolable { /// <summary> /// How long a stationary emoticon will live for, in milliseconds. /// </summary> const int _stationaryEmoticonLife = 1600; readonly Grh _grh = new Grh(); TickCount _initializeTime; bool _isAlive; /// <summary> /// Gets if the <see cref="EmoticonDisplayInfo"/> is still alive. If false, the emoticon will no longer /// display. /// </summary> public bool IsAlive { get { return _isAlive; } } /// <summary> /// Gets if this object is in a valid state to update and draw. /// </summary> bool IsValidStateToUse { get { return _grh != null && _grh.GrhData != null && IsAlive; } } /// <summary> /// Draws the emoticon. /// </summary> /// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to draw to.</param> /// <param name="position">The world position to draw the emoticon.</param> public void Draw(ISpriteBatch spriteBatch, Vector2 position) { // Check for a valid state if (!IsValidStateToUse) return; _grh.Draw(spriteBatch, position); } /// <summary> /// Sets up the <see cref="EmoticonDisplayInfo"/>. /// </summary> /// <param name="grhIndex">The <see cref="GrhIndex"/> of the emoticon.</param> /// <param name="currentTime">The current game time.</param> public void Initialize(GrhIndex grhIndex, TickCount currentTime) { _grh.SetGrh(grhIndex, AnimType.LoopOnce, currentTime); _initializeTime = currentTime; _isAlive = true; } /// <summary> /// Updates the emoticon. /// </summary> /// <param name="currentTime">The current game time.</param> public void Update(TickCount currentTime) { // Check for a valid state if (!IsValidStateToUse) return; // Update the sprite _grh.Update(currentTime); // Check if the emoticon is still alive if (_grh.GrhData.FramesCount <= 1) { // For stationary, check that the target amount of time has elapsed if (currentTime > _initializeTime + _stationaryEmoticonLife) _isAlive = false; } else { // If animated, check if the animation is still going _isAlive = (_grh.AnimType == AnimType.LoopOnce); } } #region IPoolable Members /// <summary> /// Gets or sets the index of the object in the pool. This value should never be used by anything /// other than the pool that owns this object. /// </summary> int IPoolable.PoolIndex { get; set; } #endregion } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.MenuItem.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { sealed public partial class MenuItem : System.Web.UI.IStateManager, ICloneable { #region Methods and constructors public MenuItem () { } public MenuItem (string text, string value) { } public MenuItem (string text, string value, string imageUrl, string navigateUrl, string target) { } public MenuItem (string text, string value, string imageUrl) { } public MenuItem (string text, string value, string imageUrl, string navigateUrl) { } public MenuItem (string text) { } Object System.ICloneable.Clone () { return default(Object); } void System.Web.UI.IStateManager.LoadViewState (Object state) { } Object System.Web.UI.IStateManager.SaveViewState () { return default(Object); } void System.Web.UI.IStateManager.TrackViewState () { } #endregion #region Properties and indexers public MenuItemCollection ChildItems { get { Contract.Ensures (Contract.Result<System.Web.UI.WebControls.MenuItemCollection>() != null); return default(MenuItemCollection); } } public bool DataBound { get { return default(bool); } } public Object DataItem { get { return default(Object); } } public string DataPath { get { return default(string); } } public int Depth { get { return default(int); } } public bool Enabled { get { return default(bool); } set { } } public string ImageUrl { get { return default(string); } set { } } public string NavigateUrl { get { return default(string); } set { } } public System.Web.UI.WebControls.MenuItem Parent { get { return default(System.Web.UI.WebControls.MenuItem); } } public string PopOutImageUrl { get { return default(string); } set { } } public bool Selectable { get { return default(bool); } set { } } public bool Selected { get { return default(bool); } set { } } public string SeparatorImageUrl { get { return default(string); } set { } } bool System.Web.UI.IStateManager.IsTrackingViewState { get { return default(bool); } } public string Target { get { return default(string); } set { } } public string Text { get { return default(string); } set { } } public string ToolTip { get { return default(string); } set { } } public string Value { get { return default(string); } set { } } public string ValuePath { get { return default(string); } } #endregion } }
using System.Collections.Generic; using System.Threading.Tasks; namespace Octokit { /// <summary> /// A client for GitHub's Collaborators on a Repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details. /// </remarks> public interface IRepoCollaboratorsClient { /// <summary> /// Gets all the collaborators on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<IReadOnlyList<User>> GetAll(string owner, string name); /// <summary> /// Gets all the collaborators on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<IReadOnlyList<User>> GetAll(long repositoryId); /// <summary> /// Gets all the collaborators on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<IReadOnlyList<User>> GetAll(string owner, string name, ApiOptions options); /// <summary> /// Gets all the collaborators on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<IReadOnlyList<User>> GetAll(long repositoryId, ApiOptions options); /// <summary> /// Gets all the collaborators on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="request">Used to request and filter a list of repository collaborators</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<IReadOnlyList<User>> GetAll(string owner, string name, RepositoryCollaboratorListRequest request); /// <summary> /// Gets all the collaborators on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository</param> /// <param name="request">Used to request and filter a list of repository collaborators</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<IReadOnlyList<User>> GetAll(long repositoryId, RepositoryCollaboratorListRequest request); /// <summary> /// Gets all the collaborators on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="request">Used to request and filter a list of repository collaborators</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<IReadOnlyList<User>> GetAll(string owner, string name, RepositoryCollaboratorListRequest request, ApiOptions options); /// <summary> /// Gets all the collaborators on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#list">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository</param> /// <param name="request">Used to request and filter a list of repository collaborators</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<IReadOnlyList<User>> GetAll(long repositoryId, RepositoryCollaboratorListRequest request, ApiOptions options); /// <summary> /// Checks if a user is a collaborator on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#get">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="user">Username of the prospective collaborator</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<bool> IsCollaborator(string owner, string name, string user); /// <summary> /// Checks if a user is a collaborator on a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#get">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository</param> /// <param name="user">Username of the prospective collaborator</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<bool> IsCollaborator(long repositoryId, string user); /// <summary> /// Review a user's permission level in a repository /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="user">Username of the collaborator to check permission for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<CollaboratorPermission> ReviewPermission(string owner, string name, string user); /// <summary> /// Review a user's permission level in a repository /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository</param> /// <param name="user">Username of the collaborator to check permission for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<CollaboratorPermission> ReviewPermission(long repositoryId, string user); /// <summary> /// Adds a new collaborator to the repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="user">Username of the new collaborator</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Add(string owner, string name, string user); /// <summary> /// Adds a new collaborator to the repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="user">Username of the new collaborator</param> /// <param name="permission">The permission to set. Only valid on organization-owned repositories.</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<bool> Add(string owner, string name, string user, CollaboratorRequest permission); /// <summary> /// Adds a new collaborator to the repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository</param> /// <param name="user">Username of the new collaborator</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Add(long repositoryId, string user); /// <summary> /// Adds a new collaborator to the repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository</param> /// <param name="user">Username of the new collaborator</param> /// <param name="permission">The permission to set. Only valid on organization-owned repositories.</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<bool> Add(long repositoryId, string user, CollaboratorRequest permission); /// <summary> /// Invites a new collaborator to the repo /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository.</param> /// <param name="name">The name of the repository.</param> /// <param name="user">The name of the user to invite.</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<RepositoryInvitation> Invite(string owner, string name, string user); /// <summary> /// Invites a new collaborator to the repo /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository.</param> /// <param name="name">The name of the repository.</param> /// <param name="user">The name of the user to invite.</param> /// <param name="permission">The permission to set. Only valid on organization-owned repositories.</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<RepositoryInvitation> Invite(string owner, string name, string user, CollaboratorRequest permission); /// <summary> /// Invites a new collaborator to the repo /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository.</param> /// <param name="user">The name of the user to invite.</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<RepositoryInvitation> Invite(long repositoryId, string user); /// <summary> /// Invites a new collaborator to the repo /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#add-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository.</param> /// <param name="user">The name of the user to invite.</param> /// <param name="permission">The permission to set. Only valid on organization-owned repositories.</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task<RepositoryInvitation> Invite(long repositoryId, string user, CollaboratorRequest permission); /// <summary> /// Deletes a collaborator from the repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#remove-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="user">Username of the removed collaborator</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(string owner, string name, string user); /// <summary> /// Deletes a collaborator from the repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/#remove-collaborator">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The id of the repository</param> /// <param name="user">Username of the removed collaborator</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(long repositoryId, string user); } }
// 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.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; #if MS_IO_REDIST namespace Microsoft.IO #else namespace System.IO #endif { // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. public static class File { private const int MaxByteArrayLength = 0x7FFFFFC7; private static Encoding s_UTF8NoBOM; internal const int DefaultBufferSize = 4096; public static StreamReader OpenText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return new StreamReader(path); } public static StreamWriter CreateText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return new StreamWriter(path, append: false); } public static StreamWriter AppendText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return new StreamWriter(path, append: true); } /// <summary> /// Copies an existing file to a new file. /// An exception is raised if the destination file already exists. /// </summary> public static void Copy(string sourceFileName, string destFileName) => Copy(sourceFileName, destFileName, overwrite: false); /// <summary> /// Copies an existing file to a new file. /// If <paramref name="overwrite"/> is false, an exception will be /// raised if the destination exists. Otherwise it will be overwritten. /// </summary> public static void Copy(string sourceFileName, string destFileName, bool overwrite) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); FileSystem.CopyFile(Path.GetFullPath(sourceFileName), Path.GetFullPath(destFileName), overwrite); } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite access and cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. public static FileStream Create(string path) { return Create(path, DefaultBufferSize); } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite access and cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. public static FileStream Create(string path, int bufferSize) => new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize); public static FileStream Create(string path, int bufferSize, FileOptions options) => new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options); // Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On Windows, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. public static void Delete(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); FileSystem.DeleteFile(Path.GetFullPath(path)); } // Tests whether a file exists. The result is true if the file // given by the specified path exists; otherwise, the result is // false. Note that if path describes a directory, // Exists will return true. public static bool Exists(string path) { try { if (path == null) return false; if (path.Length == 0) return false; path = Path.GetFullPath(path); // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPath should never return null Debug.Assert(path != null, "File.Exists: GetFullPath returned null"); if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1])) { return false; } return FileSystem.FileExists(path); } catch (ArgumentException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } public static FileStream Open(string path, FileMode mode) { return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None); } public static FileStream Open(string path, FileMode mode, FileAccess access) { return Open(path, mode, access, FileShare.None); } public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) { return new FileStream(path, mode, access, share); } internal static DateTimeOffset GetUtcDateTimeOffset(DateTime dateTime) { // File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas // ToUniversalTime treats this as local. if (dateTime.Kind == DateTimeKind.Unspecified) { return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); } return dateTime.ToUniversalTime(); } public static void SetCreationTime(string path, DateTime creationTime) { string fullPath = Path.GetFullPath(path); FileSystem.SetCreationTime(fullPath, creationTime, asDirectory: false); } public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc) { string fullPath = Path.GetFullPath(path); FileSystem.SetCreationTime(fullPath, GetUtcDateTimeOffset(creationTimeUtc), asDirectory: false); } public static DateTime GetCreationTime(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.GetCreationTime(fullPath).LocalDateTime; } public static DateTime GetCreationTimeUtc(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.GetCreationTime(fullPath).UtcDateTime; } public static void SetLastAccessTime(string path, DateTime lastAccessTime) { string fullPath = Path.GetFullPath(path); FileSystem.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: false); } public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc) { string fullPath = Path.GetFullPath(path); FileSystem.SetLastAccessTime(fullPath, GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: false); } public static DateTime GetLastAccessTime(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.GetLastAccessTime(fullPath).LocalDateTime; } public static DateTime GetLastAccessTimeUtc(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.GetLastAccessTime(fullPath).UtcDateTime; } public static void SetLastWriteTime(string path, DateTime lastWriteTime) { string fullPath = Path.GetFullPath(path); FileSystem.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: false); } public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) { string fullPath = Path.GetFullPath(path); FileSystem.SetLastWriteTime(fullPath, GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: false); } public static DateTime GetLastWriteTime(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.GetLastWriteTime(fullPath).LocalDateTime; } public static DateTime GetLastWriteTimeUtc(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.GetLastWriteTime(fullPath).UtcDateTime; } public static FileAttributes GetAttributes(string path) { string fullPath = Path.GetFullPath(path); return FileSystem.GetAttributes(fullPath); } public static void SetAttributes(string path, FileAttributes fileAttributes) { string fullPath = Path.GetFullPath(path); FileSystem.SetAttributes(fullPath, fileAttributes); } public static FileStream OpenRead(string path) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); } public static FileStream OpenWrite(string path) { return new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } public static string ReadAllText(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return InternalReadAllText(path, Encoding.UTF8); } public static string ReadAllText(string path, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return InternalReadAllText(path, encoding); } private static string InternalReadAllText(string path, Encoding encoding) { Debug.Assert(path != null); Debug.Assert(encoding != null); Debug.Assert(path.Length > 0); using (StreamReader sr = new StreamReader(path, encoding, detectEncodingFromByteOrderMarks: true)) return sr.ReadToEnd(); } public static void WriteAllText(string path, string contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); using (StreamWriter sw = new StreamWriter(path)) { sw.Write(contents); } } public static void WriteAllText(string path, string contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); using (StreamWriter sw = new StreamWriter(path, false, encoding)) { sw.Write(contents); } } public static byte[] ReadAllBytes(string path) { // bufferSize == 1 used to avoid unnecessary buffer in FileStream using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1)) { long fileLength = fs.Length; if (fileLength > int.MaxValue) { throw new IOException(SR.IO_FileTooLong2GB); } else if (fileLength == 0) { #if !MS_IO_REDIST // Some file systems (e.g. procfs on Linux) return 0 for length even when there's content. // Thus we need to assume 0 doesn't mean empty. return ReadAllBytesUnknownLength(fs); #endif } int index = 0; int count = (int)fileLength; byte[] bytes = new byte[count]; while (count > 0) { int n = fs.Read(bytes, index, count); if (n == 0) throw Error.GetEndOfFile(); index += n; count -= n; } return bytes; } } #if !MS_IO_REDIST private static byte[] ReadAllBytesUnknownLength(FileStream fs) { byte[] rentedArray = null; Span<byte> buffer = stackalloc byte[512]; try { int bytesRead = 0; while (true) { if (bytesRead == buffer.Length) { uint newLength = (uint)buffer.Length * 2; if (newLength > MaxByteArrayLength) { newLength = (uint)Math.Max(MaxByteArrayLength, buffer.Length + 1); } byte[] tmp = ArrayPool<byte>.Shared.Rent((int)newLength); buffer.CopyTo(tmp); if (rentedArray != null) { ArrayPool<byte>.Shared.Return(rentedArray); } buffer = rentedArray = tmp; } Debug.Assert(bytesRead < buffer.Length); int n = fs.Read(buffer.Slice(bytesRead)); if (n == 0) { return buffer.Slice(0, bytesRead).ToArray(); } bytesRead += n; } } finally { if (rentedArray != null) { ArrayPool<byte>.Shared.Return(rentedArray); } } } #endif public static void WriteAllBytes(string path, byte[] bytes) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (bytes == null) throw new ArgumentNullException(nameof(bytes)); InternalWriteAllBytes(path, bytes); } private static void InternalWriteAllBytes(string path, byte[] bytes) { Debug.Assert(path != null); Debug.Assert(path.Length != 0); Debug.Assert(bytes != null); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { fs.Write(bytes, 0, bytes.Length); } } public static string[] ReadAllLines(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return InternalReadAllLines(path, Encoding.UTF8); } public static string[] ReadAllLines(string path, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return InternalReadAllLines(path, encoding); } private static string[] InternalReadAllLines(string path, Encoding encoding) { Debug.Assert(path != null); Debug.Assert(encoding != null); Debug.Assert(path.Length != 0); string line; List<string> lines = new List<string>(); using (StreamReader sr = new StreamReader(path, encoding)) while ((line = sr.ReadLine()) != null) lines.Add(line); return lines.ToArray(); } public static IEnumerable<string> ReadLines(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return ReadLinesIterator.CreateIterator(path, Encoding.UTF8); } public static IEnumerable<string> ReadLines(string path, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return ReadLinesIterator.CreateIterator(path, encoding); } public static void WriteAllLines(string path, string[] contents) { WriteAllLines(path, (IEnumerable<string>)contents); } public static void WriteAllLines(string path, IEnumerable<string> contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); InternalWriteAllLines(new StreamWriter(path), contents); } public static void WriteAllLines(string path, string[] contents, Encoding encoding) { WriteAllLines(path, (IEnumerable<string>)contents, encoding); } public static void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); InternalWriteAllLines(new StreamWriter(path, false, encoding), contents); } private static void InternalWriteAllLines(TextWriter writer, IEnumerable<string> contents) { Debug.Assert(writer != null); Debug.Assert(contents != null); using (writer) { foreach (string line in contents) { writer.WriteLine(line); } } } public static void AppendAllText(string path, string contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); using (StreamWriter sw = new StreamWriter(path, append: true)) { sw.Write(contents); } } public static void AppendAllText(string path, string contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); using (StreamWriter sw = new StreamWriter(path, true, encoding)) { sw.Write(contents); } } public static void AppendAllLines(string path, IEnumerable<string> contents) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); InternalWriteAllLines(new StreamWriter(path, append: true), contents); } public static void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); InternalWriteAllLines(new StreamWriter(path, true, encoding), contents); } public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName) { Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors: false); } public static void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName)); if (destinationFileName == null) throw new ArgumentNullException(nameof(destinationFileName)); FileSystem.ReplaceFile( Path.GetFullPath(sourceFileName), Path.GetFullPath(destinationFileName), destinationBackupFileName != null ? Path.GetFullPath(destinationBackupFileName) : null, ignoreMetadataErrors); } // Moves a specified file to a new location and potentially a new file name. // This method does work across volumes. // // The caller must have certain FileIOPermissions. The caller must // have Read and Write permission to // sourceFileName and Write // permissions to destFileName. // public static void Move(string sourceFileName, string destFileName) { Move(sourceFileName, destFileName, false); } public static void Move(string sourceFileName, string destFileName, bool overwrite) { if (sourceFileName == null) throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName); if (destFileName == null) throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName); if (sourceFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName)); if (destFileName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName)); string fullSourceFileName = Path.GetFullPath(sourceFileName); string fullDestFileName = Path.GetFullPath(destFileName); if (!FileSystem.FileExists(fullSourceFileName)) { throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, fullSourceFileName), fullSourceFileName); } FileSystem.MoveFile(fullSourceFileName, fullDestFileName, overwrite); } public static void Encrypt(string path) { FileSystem.Encrypt(path ?? throw new ArgumentNullException(nameof(path))); } public static void Decrypt(string path) { FileSystem.Decrypt(path ?? throw new ArgumentNullException(nameof(path))); } // UTF-8 without BOM and with error detection. Same as the default encoding for StreamWriter. private static Encoding UTF8NoBOM => s_UTF8NoBOM ?? (s_UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); // If we use the path-taking constructors we will not have FileOptions.Asynchronous set and // we will have asynchronous file access faked by the thread pool. We want the real thing. private static StreamReader AsyncStreamReader(string path, Encoding encoding) { FileStream stream = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); return new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true); } private static StreamWriter AsyncStreamWriter(string path, Encoding encoding, bool append) { FileStream stream = new FileStream( path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); return new StreamWriter(stream, encoding); } public static Task<string> ReadAllTextAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) => ReadAllTextAsync(path, Encoding.UTF8, cancellationToken); public static Task<string> ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled<string>(cancellationToken) : InternalReadAllTextAsync(path, encoding, cancellationToken); } private static async Task<string> InternalReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(encoding != null); char[] buffer = null; StreamReader sr = AsyncStreamReader(path, encoding); try { cancellationToken.ThrowIfCancellationRequested(); buffer = ArrayPool<char>.Shared.Rent(sr.CurrentEncoding.GetMaxCharCount(DefaultBufferSize)); StringBuilder sb = new StringBuilder(); while (true) { #if MS_IO_REDIST int read = await sr.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); #else int read = await sr.ReadAsync(new Memory<char>(buffer), cancellationToken).ConfigureAwait(false); #endif if (read == 0) { return sb.ToString(); } sb.Append(buffer, 0, read); } } finally { sr.Dispose(); if (buffer != null) { ArrayPool<char>.Shared.Return(buffer); } } } public static Task WriteAllTextAsync(string path, string contents, CancellationToken cancellationToken = default(CancellationToken)) => WriteAllTextAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task WriteAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (string.IsNullOrEmpty(contents)) { new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read).Dispose(); return Task.CompletedTask; } return InternalWriteAllTextAsync(AsyncStreamWriter(path, encoding, append: false), contents, cancellationToken); } public static Task<byte[]> ReadAllBytesAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<byte[]>(cancellationToken); } var fs = new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1, // bufferSize == 1 used to avoid unnecessary buffer in FileStream FileOptions.Asynchronous | FileOptions.SequentialScan); bool returningInternalTask = false; try { long fileLength = fs.Length; if (fileLength > int.MaxValue) { var e = new IOException(SR.IO_FileTooLong2GB); #if !MS_IO_REDIST ExceptionDispatchInfo.SetCurrentStackTrace(e); #endif return Task.FromException<byte[]>(e); } returningInternalTask = true; return fileLength > 0 ? InternalReadAllBytesAsync(fs, (int)fileLength, cancellationToken) : InternalReadAllBytesUnknownLengthAsync(fs, cancellationToken); } finally { if (!returningInternalTask) { fs.Dispose(); } } } private static async Task<byte[]> InternalReadAllBytesAsync(FileStream fs, int count, CancellationToken cancellationToken) { using (fs) { int index = 0; byte[] bytes = new byte[count]; do { #if MS_IO_REDIST int n = await fs.ReadAsync(bytes, index, count - index, cancellationToken).ConfigureAwait(false); #else int n = await fs.ReadAsync(new Memory<byte>(bytes, index, count - index), cancellationToken).ConfigureAwait(false); #endif if (n == 0) { throw Error.GetEndOfFile(); } index += n; } while (index < count); return bytes; } } private static async Task<byte[]> InternalReadAllBytesUnknownLengthAsync(FileStream fs, CancellationToken cancellationToken) { byte[] rentedArray = ArrayPool<byte>.Shared.Rent(512); try { int bytesRead = 0; while (true) { if (bytesRead == rentedArray.Length) { uint newLength = (uint)rentedArray.Length * 2; if (newLength > MaxByteArrayLength) { newLength = (uint)Math.Max(MaxByteArrayLength, rentedArray.Length + 1); } byte[] tmp = ArrayPool<byte>.Shared.Rent((int)newLength); Buffer.BlockCopy(rentedArray, 0, tmp, 0, bytesRead); ArrayPool<byte>.Shared.Return(rentedArray); rentedArray = tmp; } Debug.Assert(bytesRead < rentedArray.Length); #if MS_IO_REDIST int n = await fs.ReadAsync(rentedArray, bytesRead, rentedArray.Length - bytesRead, cancellationToken).ConfigureAwait(false); #else int n = await fs.ReadAsync(rentedArray.AsMemory(bytesRead), cancellationToken).ConfigureAwait(false); #endif if (n == 0) { return rentedArray.AsSpan(0, bytesRead).ToArray(); } bytesRead += n; } } finally { fs.Dispose(); ArrayPool<byte>.Shared.Return(rentedArray); } } public static Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (bytes == null) throw new ArgumentNullException(nameof(bytes)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllBytesAsync(path, bytes, cancellationToken); } private static async Task InternalWriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(bytes != null); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan)) { #if MS_IO_REDIST await fs.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false); #else await fs.WriteAsync(new ReadOnlyMemory<byte>(bytes), cancellationToken).ConfigureAwait(false); #endif await fs.FlushAsync(cancellationToken).ConfigureAwait(false); } } public static Task<string[]> ReadAllLinesAsync(string path, CancellationToken cancellationToken = default(CancellationToken)) => ReadAllLinesAsync(path, Encoding.UTF8, cancellationToken); public static Task<string[]> ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled<string[]>(cancellationToken) : InternalReadAllLinesAsync(path, encoding, cancellationToken); } private static async Task<string[]> InternalReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken) { Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(encoding != null); using (StreamReader sr = AsyncStreamReader(path, encoding)) { cancellationToken.ThrowIfCancellationRequested(); string line; List<string> lines = new List<string>(); while ((line = await sr.ReadLineAsync().ConfigureAwait(false)) != null) { lines.Add(line); cancellationToken.ThrowIfCancellationRequested(); } return lines.ToArray(); } } public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken = default(CancellationToken)) => WriteAllLinesAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: false), contents, cancellationToken); } private static async Task InternalWriteAllLinesAsync(TextWriter writer, IEnumerable<string> contents, CancellationToken cancellationToken) { Debug.Assert(writer != null); Debug.Assert(contents != null); using (writer) { foreach (string line in contents) { cancellationToken.ThrowIfCancellationRequested(); // Note that this working depends on the fix to #14563, and cannot be ported without // either also porting that fix, or explicitly checking for line being null. await writer.WriteLineAsync(line).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); await writer.FlushAsync().ConfigureAwait(false); } } private static async Task InternalWriteAllTextAsync(StreamWriter sw, string contents, CancellationToken cancellationToken) { char[] buffer = null; try { buffer = ArrayPool<char>.Shared.Rent(DefaultBufferSize); int count = contents.Length; int index = 0; while (index < count) { int batchSize = Math.Min(DefaultBufferSize, count - index); contents.CopyTo(index, buffer, 0, batchSize); #if MS_IO_REDIST await sw.WriteAsync(buffer, 0, batchSize).ConfigureAwait(false); #else await sw.WriteAsync(new ReadOnlyMemory<char>(buffer, 0, batchSize), cancellationToken).ConfigureAwait(false); #endif index += batchSize; } cancellationToken.ThrowIfCancellationRequested(); await sw.FlushAsync().ConfigureAwait(false); } finally { sw.Dispose(); if (buffer != null) { ArrayPool<char>.Shared.Return(buffer); } } } public static Task AppendAllTextAsync(string path, string contents, CancellationToken cancellationToken = default(CancellationToken)) => AppendAllTextAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task AppendAllTextAsync(string path, string contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (string.IsNullOrEmpty(contents)) { // Just to throw exception if there is a problem opening the file. new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read).Dispose(); return Task.CompletedTask; } return InternalWriteAllTextAsync(AsyncStreamWriter(path, encoding, append: true), contents, cancellationToken); } public static Task AppendAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken = default(CancellationToken)) => AppendAllLinesAsync(path, contents, UTF8NoBOM, cancellationToken); public static Task AppendAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { if (path == null) throw new ArgumentNullException(nameof(path)); if (contents == null) throw new ArgumentNullException(nameof(contents)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: true), contents, cancellationToken); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Reflection; namespace ClosedXML_Tests { /// <summary> /// Summary description for ResourceFileExtractor. /// </summary> public sealed class ResourceFileExtractor { #region Static #region Private fields private static readonly IDictionary<string, ResourceFileExtractor> extractors = new ConcurrentDictionary<string, ResourceFileExtractor>(); #endregion Private fields #region Public properties /// <summary>Instance of resource extractor for executing assembly </summary> public static ResourceFileExtractor Instance { get { Assembly _assembly = Assembly.GetCallingAssembly(); string _key = _assembly.GetName().FullName; if (!extractors.TryGetValue(_key, out ResourceFileExtractor extractor) && !extractors.TryGetValue(_key, out extractor)) { extractor = new ResourceFileExtractor(_assembly, true, null); extractors.Add(_key, extractor); } return extractor; } } #endregion Public properties #endregion Static #region Private fields private readonly Assembly m_assembly; private readonly ResourceFileExtractor m_baseExtractor; private bool m_isStatic; //private string ResourceFilePath { get; } #endregion Private fields #region Constructors /// <summary> /// Create instance /// </summary> /// <param name="resourceFilePath"><c>ResourceFilePath</c> in assembly. Example: .Properties.Scripts.</param> /// <param name="baseExtractor"></param> public ResourceFileExtractor(string resourceFilePath, ResourceFileExtractor baseExtractor) : this(Assembly.GetCallingAssembly(), baseExtractor) { ResourceFilePath = resourceFilePath; } /// <summary> /// Create instance /// </summary> /// <param name="baseExtractor"></param> public ResourceFileExtractor(ResourceFileExtractor baseExtractor) : this(Assembly.GetCallingAssembly(), baseExtractor) { } /// <summary> /// Create instance /// </summary> /// <param name="resourcePath"><c>ResourceFilePath</c> in assembly. Example: .Properties.Scripts.</param> public ResourceFileExtractor(string resourcePath) : this(Assembly.GetCallingAssembly(), resourcePath) { } /// <summary> /// Instance constructor /// </summary> /// <param name="assembly"></param> /// <param name="resourcePath"></param> public ResourceFileExtractor(Assembly assembly, string resourcePath) : this(assembly ?? Assembly.GetCallingAssembly()) { ResourceFilePath = resourcePath; } /// <summary> /// Instance constructor /// </summary> public ResourceFileExtractor() : this(Assembly.GetCallingAssembly()) { } /// <summary> /// Instance constructor /// </summary> /// <param name="assembly"></param> public ResourceFileExtractor(Assembly assembly) : this(assembly ?? Assembly.GetCallingAssembly(), (ResourceFileExtractor)null) { } /// <summary> /// Instance constructor /// </summary> /// <param name="assembly"></param> /// <param name="baseExtractor"></param> public ResourceFileExtractor(Assembly assembly, ResourceFileExtractor baseExtractor) : this(assembly ?? Assembly.GetCallingAssembly(), false, baseExtractor) { } /// <summary> /// Instance constructor /// </summary> /// <param name="assembly"></param> /// <param name="isStatic"></param> /// <param name="baseExtractor"></param> /// <exception cref="ArgumentNullException">Argument is null.</exception> private ResourceFileExtractor(Assembly assembly, bool isStatic, ResourceFileExtractor baseExtractor) { #region Check if (assembly is null) { throw new ArgumentNullException("assembly"); } #endregion Check Assembly = assembly; m_baseExtractor = baseExtractor; AssemblyName = Assembly.GetName().Name; IsStatic = isStatic; ResourceFilePath = ".Resources."; } #endregion Constructors #region Public properties /// <summary> Work assembly </summary> public Assembly Assembly { get; } /// <summary> Work assembly name </summary> public string AssemblyName { get; } /// <summary> /// Path to read resource files. Example: .Resources.Upgrades. /// </summary> public string ResourceFilePath { get; } public bool IsStatic { get; set; } public IEnumerable<string> GetFileNames(Func<String, Boolean> predicate = null) { predicate = predicate ?? (s => true); string _path = AssemblyName + ResourceFilePath; foreach (string _resourceName in Assembly.GetManifestResourceNames()) { if (_resourceName.StartsWith(_path) && predicate(_resourceName)) { yield return _resourceName.Replace(_path, string.Empty); } } } #endregion Public properties #region Public methods public string ReadFileFromResource(string fileName) { Stream _stream = ReadFileFromResourceToStream(fileName); string _result; StreamReader sr = new StreamReader(_stream); try { _result = sr.ReadToEnd(); } finally { sr.Close(); } return _result; } public string ReadFileFromResourceFormat(string fileName, params object[] formatArgs) { return string.Format(ReadFileFromResource(fileName), formatArgs); } /// <summary> /// Read file in current assembly by specific path /// </summary> /// <param name="specificPath">Specific path</param> /// <param name="fileName">Read file name</param> /// <returns></returns> public string ReadSpecificFileFromResource(string specificPath, string fileName) { ResourceFileExtractor _ext = new ResourceFileExtractor(Assembly, specificPath); return _ext.ReadFileFromResource(fileName); } /// <summary> /// Read file in current assembly by specific file name /// </summary> /// <param name="fileName"></param> /// <returns></returns> /// <exception cref="ApplicationException"><c>ApplicationException</c>.</exception> public Stream ReadFileFromResourceToStream(string fileName) { string _nameResFile = AssemblyName + ResourceFilePath + fileName; Stream _stream = Assembly.GetManifestResourceStream(_nameResFile); #region Not found if (_stream is null) { #region Get from base extractor if (!(m_baseExtractor is null)) { return m_baseExtractor.ReadFileFromResourceToStream(fileName); } #endregion Get from base extractor throw new ArgumentException("Can't find resource file " + _nameResFile, nameof(fileName)); } #endregion Not found return _stream; } #endregion Public methods } }
/* * Copyright (c) 2017 Robert Adams * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using OpenSim.Services.Interfaces; using org.herbal3d.cs.CommonEntities; using org.herbal3d.cs.CommonEntitiesUtil; namespace org.herbal3d.convoar { // Class passed around for global context for this region module instance. // NOT FOR PASSING DATA! Only used for global resources like logging, configuration // parameters, statistics, and the such. public class GlobalContext { public ConvoarParams parms; public ConvoarStats stats; public BLogger log; public string contextName; // a unique identifier for this context -- used in filenames, ... public string version; public string buildDate; public string gitCommit; public GlobalContext() { stats = null; contextName = String.Empty; version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); // A command is added to the pre-build events that generates BuildDate resource: // echo %date% %time% > "$(ProjectDir)\Resources\BuildDate.txt" buildDate = Properties.Resources.BuildDate.Trim(); // A command is added to the pre-build events that generates last commit resource: // git rev-parse HEAD > "$(ProjectDir)\Resources\GitCommit.txt" gitCommit = Properties.Resources.GitCommit.Trim(); } } class ConvOAR { private static readonly string _logHeader = "[ConvOAR]"; public static GlobalContext Globals; string _outputDir; private string Invocation() { StringBuilder buff = new StringBuilder(); buff.AppendLine("Invocation: convoar <parameters> inputOARfile"); buff.AppendLine(" Possible parameters are (negate bool parameters by prepending 'no'):"); string[] paramDescs = Globals.parms.ParameterDefinitions.Select(pp => { return pp.ToString(); }).ToArray(); buff.AppendLine(String.Join(Environment.NewLine, paramDescs)); return buff.ToString(); } static void Main(string[] args) { ConvOAR prog = new ConvOAR(); CancellationToken cancelToken = new CancellationToken(); prog.Start(cancelToken, args).Wait(); return; } // If run from the command line, create instance and call 'Start' with args. // If run programmatically, create instance and call 'Start' with parameters. public async Task Start(CancellationToken cancelToken, string[] args) { Globals = new GlobalContext() { log = new LoggerLog4Net(), // log = new LoggerConsole(), stats = new ConvoarStats() }; Globals.parms = new ConvoarParams(Globals.log); // A single parameter of '--help' outputs the invocation parameters if (args.Length > 0 && args[0] == "--help") { System.Console.Write(Invocation()); return; } // 'ConvoarParams' initializes to default values. // Over ride default values with command line parameters. try { // Note that trailing parameters will be put into "InputOAR" parameter Globals.parms.MergeCommandLine(args, null, "InputOAR"); } catch (Exception e) { Globals.log.ErrorFormat("ERROR: bad parameters: " + e.Message); Globals.log.ErrorFormat(Invocation()); return; } if (Globals.parms.P<bool>("Verbose")) { Globals.log.SetVerbose(Globals.parms.P<bool>("Verbose")); } if (!Globals.parms.P<bool>("Quiet")) { System.Console.WriteLine("Convoar v" + Globals.version + " built " + Globals.buildDate + " commit " + Globals.gitCommit ); } // Validate parameters if (String.IsNullOrEmpty(Globals.parms.P<string>("InputOAR"))) { Globals.log.ErrorFormat("An input OAR file must be specified"); Globals.log.ErrorFormat(Invocation()); return; } if (String.IsNullOrEmpty(Globals.parms.P<string>("OutputDir"))) { _outputDir = "./out"; Globals.log.DebugFormat("Output directory defaulting to {0}", _outputDir); } // Base asset storage system -- 'MemAssetService' is in-memory storage using (MemAssetService memAssetService = new MemAssetService()) { // 'assetManager' is the asset cache and fetching code -- where all the mesh, // material, and instance information is stored for later processing. using (AssetManager assetManager = new AssetManager(memAssetService, Globals.log, Globals.parms)) { try { BScene bScene = await LoadOAR(memAssetService, assetManager); Globals.contextName = bScene.name; Globals.log.DebugFormat("{0} Scene created. name={1}, instances={2}", _logHeader, bScene.name, bScene.instances.Count); Globals.log.DebugFormat("{0} num assetFetcher.images={1}", _logHeader, assetManager.Assets.Images.Count); Globals.log.DebugFormat("{0} num assetFetcher.materials={1}", _logHeader, assetManager.Assets.Materials.Count); Globals.log.DebugFormat("{0} num assetFetcher.meshes={1}", _logHeader, assetManager.Assets.Meshes.Count); Globals.log.DebugFormat("{0} num assetFetcher.renderables={1}", _logHeader, assetManager.Assets.Renderables.Count); if (ConvOAR.Globals.parms.P<bool>("AddTerrainMesh")) { ConvOAR.Globals.log.DebugFormat("{0} Adding terrain to scene", _logHeader); bScene.instances.Add(bScene.terrainInstance); } if (ConvOAR.Globals.parms.P<bool>("TerrainOnly")) { ConvOAR.Globals.log.DebugFormat("{0} Clearing out scene so there's only terrain (TerrainOnly)", _logHeader); bScene.instances.Clear(); bScene.instances.Add(bScene.terrainInstance); } /* // Perform any optimizations on the scene and its instances if (Globals.parms.P<bool>("DoMeshSimplification")) { // TODO: } if (Globals.parms.P<bool>("DoSceneOptimizations")) { using (BSceneManipulation optimizer = new BSceneManipulation()) { bScene = optimizer.OptimizeScene(bScene); Globals.log.DebugFormat("{0} merged BScene. numInstances={1}", _logHeader, bScene.instances.Count); } } */ if (Globals.parms.P<bool>("MergeSharedMaterialMeshes")) { using (BSceneManipulation optimizer = new BSceneManipulation(Globals.log, Globals.parms)) { bScene = optimizer.RebuildSceneBasedOnSharedMeshes(bScene); Globals.log.DebugFormat("{0} merged meshes in scene. numInstances={1}", _logHeader, bScene.instances.Count); } } // Output the transformed scene as Gltf version 2 Gltf gltf = new Gltf(bScene.name, Globals.log, Globals.parms); try { gltf.LoadScene(bScene); Globals.log.DebugFormat("{0} num Gltf.nodes={1}", _logHeader, gltf.nodes.Count); Globals.log.DebugFormat("{0} num Gltf.meshes={1}", _logHeader, gltf.meshes.Count); Globals.log.DebugFormat("{0} num Gltf.materials={1}", _logHeader, gltf.materials.Count); Globals.log.DebugFormat("{0} num Gltf.images={1}", _logHeader, gltf.images.Count); Globals.log.DebugFormat("{0} num Gltf.accessor={1}", _logHeader, gltf.accessors.Count); Globals.log.DebugFormat("{0} num Gltf.buffers={1}", _logHeader, gltf.buffers.Count); Globals.log.DebugFormat("{0} num Gltf.bufferViews={1}", _logHeader, gltf.bufferViews.Count); } catch (Exception e) { Globals.log.ErrorFormat("{0} Exception loading GltfScene: {1}", _logHeader, e); } try { if (gltf.scenes.Count > 0) { string gltfFilename = gltf.GetFilename(gltf.IdentifyingString); using (var outm = new MemoryStream()) { using (var outt = new StreamWriter(outm)) { gltf.ToJSON(outt); } await assetManager.AssetStorage.Store(gltfFilename, outm.ToArray()); } gltf.WriteBinaryFiles(assetManager.AssetStorage); if (Globals.parms.P<bool>("ExportTextures")) { gltf.WriteImages(assetManager.AssetStorage); } } else { Globals.log.ErrorFormat("{0} Not writing out GLTF because no scenes", _logHeader); } } catch (Exception e) { Globals.log.ErrorFormat("{0} Exception writing GltfScene: {1}", _logHeader, e); } /* // Output all the instances in the scene as individual GLTF files if (Globals.parms.P<bool>("ExportIndividualGltf")) { bScene.instances.ForEach(instance => { string instanceName = instance.handle.ToString(); Gltf gltf = new Gltf(instanceName); gltf.persist.baseDirectory = bScene.name; // gltf.persist.baseDirectory = PersistRules.JoinFilePieces(bScene.name, instanceName); GltfScene gltfScene = new GltfScene(gltf, instanceName); gltf.defaultScene = gltfScene; Displayable rootDisp = instance.Representation; GltfNode rootNode = GltfNode.GltfNodeFactory(gltf, gltfScene, rootDisp, assetFetcher); rootNode.translation = instance.Position; rootNode.rotation = instance.Rotation; gltf.BuildAccessorsAndBuffers(); gltf.UpdateGltfv2ReferenceIndexes(); // After the building, get rid of the default scene name as we're not outputting a scene gltf.defaultScene = null; PersistRules.ResolveAndCreateDir(gltf.persist.filename); using (StreamWriter outt = File.CreateText(gltf.persist.filename)) { gltf.ToJSON(outt); } gltf.WriteBinaryFiles(); if (Globals.parms.P<bool>("ExportTextures")) { gltf.WriteImages(); } }); } */ } catch (Exception e) { Globals.log.ErrorFormat("{0} Global exception converting scene: {1}", _logHeader, e); // A common error is not having all the DLLs for OpenSimulator. Print out what's missing. if (e is ReflectionTypeLoadException refE) { foreach (var ee in refE.LoaderExceptions) { Globals.log.ErrorFormat("{0} reference exception: {1}", _logHeader, ee); } } } } } } // Initialization if using ConvOAR programmatically. public void Start(ConvoarParams pParameters, BLogger pLogger) { Globals = new GlobalContext() { log = pLogger, parms = pParameters, stats = new ConvoarStats() }; } // Load the OARfile specified in Globals.params.InputOAR. // Parameters are in 'ConvOAR.Globals.params'. // For the moment, the OAR file must be specified with a string because of how OpenSimulator // processes the input files. Note that the filename can be an 'http:' type URL. public async Task<BScene> LoadOAR(IAssetService assetService, AssetManager assetManager) { BScene ret = null; try { OarConverter converter = new OarConverter(Globals.log, Globals.parms); ret = await converter.ConvertOarToScene(assetService, assetManager); } catch (Exception e) { ConvOAR.Globals.log.ErrorFormat("{0} LoadOAR exception: {1}", _logHeader, e); throw (e); } return ret; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests { [Fact] public async Task Issue2753_CS_DiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlResolver resolver) { XmlDocument doc = new XmlDocument(); doc.XmlResolver = resolver; } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 13)); } [Fact] public async Task Issue2753_VB_DiagnosticAsync() { await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Module SomeClass Public Sub LoadXmlSafe(resolver As XmlResolver) Dim doc As New XmlDocument() doc.XmlResolver = resolver End Sub End Module", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(7, 9)); } [Fact] public async Task XmlDocumentNoCtorSetResolverToNullShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlDocument doc) { doc.XmlResolver = null; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(doc As XmlDocument) doc.XmlResolver = Nothing End Sub End Class End Namespace"); } [Fact] public async Task XmlDocumentNoCtorUseSecureResolverShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlDocument doc, XmlSecureResolver resolver) { doc.XmlResolver = resolver; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(doc As XmlDocument, resolver As XmlSecureResolver) doc.XmlResolver = resolver End Sub End Class End Namespace"); } [Fact] public async Task XmlDocumentNoCtorUseSecureResolverWithPermissionsShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Net; using System.Security; using System.Security.Permissions; using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlDocument doc) { PermissionSet myPermissions = new PermissionSet(PermissionState.None); WebPermission permission = new WebPermission(PermissionState.None); permission.AddPermission(NetworkAccess.Connect, ""http://www.contoso.com/""); permission.AddPermission(NetworkAccess.Connect, ""http://litwareinc.com/data/""); myPermissions.SetPermission(permission); XmlSecureResolver resolver = new XmlSecureResolver(new XmlUrlResolver(), myPermissions); doc.XmlResolver = resolver; } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Net Imports System.Security Imports System.Security.Permissions Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(doc As XmlDocument) Dim myPermissions As New PermissionSet(PermissionState.None) Dim permission As New WebPermission(PermissionState.None) permission.AddPermission(NetworkAccess.Connect, ""http://www.contoso.com/"") permission.AddPermission(NetworkAccess.Connect, ""http://litwareinc.com/data/"") myPermissions.SetPermission(permission) Dim resolver As New XmlSecureResolver(New XmlUrlResolver(), myPermissions) doc.XmlResolver = resolver End Sub End Class End Namespace"); } [Fact] public async Task XmlDocumentNoCtorSetResolverToNullInTryClauseShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlDocument doc) { try { doc.XmlResolver = null; } catch { throw; } } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(doc As XmlDocument) Try doc.XmlResolver = Nothing Catch Throw End Try End Sub End Class End Namespace"); } [Fact] public async Task XmlDocumentNoCtorUseNonSecureResolverInCatchClauseShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlDocument doc) { try { } catch { doc.XmlResolver = new XmlUrlResolver(); } finally {} } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(12, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(doc As XmlDocument) Try Catch doc.XmlResolver = New XmlUrlResolver() Finally End Try End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(9, 17) ); } [Fact] public async Task XmlDocumentNoCtorUseNonSecureResolverInFinallyClauseShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlDocument doc) { try { } catch { throw; } finally { doc.XmlResolver = new XmlUrlResolver(); } } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(13, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(doc As XmlDocument) Try Catch Throw Finally doc.XmlResolver = New XmlUrlResolver() End Try End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(11, 17) ); } [Fact] public async Task XmlDocumentNoCtorDoNotSetResolverShouldNotGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlDocument doc, XmlReader reader) { doc.Load(reader); } } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(doc As XmlDocument, reader As XmlReader) doc.Load(reader) End Sub End Class End Namespace"); } [Fact] public async Task XmlDocumentNoCtorUseNonSecureResolverShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlDocument doc) { doc.XmlResolver = new XmlUrlResolver(); } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(10, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(doc As XmlDocument) doc.XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(7, 13) ); } [Fact] public async Task XmlDocumentNoCtorUseNonSecureResolverInTryClauseShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { private static void TestMethod(XmlDocument doc) { try { doc.XmlResolver = new XmlUrlResolver(); } catch { throw; } } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(12, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Private Shared Sub TestMethod(doc As XmlDocument) Try doc.XmlResolver = New XmlUrlResolver() Catch Throw End Try End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(8, 17) ); } [Fact] public async Task XmlDocumentDerivedTypeSetInsecureResolverShouldGenerateDiagnosticAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Xml; namespace TestNamespace { class DerivedType : XmlDocument {} class TestClass { void TestMethod() { var c = new DerivedType(){ XmlResolver = new XmlUrlResolver() }; } } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(13, 40) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class DerivedType Inherits XmlDocument End Class Class TestClass Private Sub TestMethod() Dim c = New DerivedType() With { _ .XmlResolver = New XmlUrlResolver() _ } End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(12, 17) ); } [Fact] public async Task XmlDocumentCreatedAsTempSetResolverToNullShouldNotGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public void Method1() { Method2(new XmlDocument(){ XmlResolver = null }); } public void Method2(XmlDocument doc){} } }" ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public Sub Method1() Method2(New XmlDocument() With { _ .XmlResolver = Nothing _ }) End Sub Public Sub Method2(doc As XmlDocument) End Sub End Class End Namespace" ); } [Fact] public async Task XmlDocumentCreatedAsTempSetInsecureResolverShouldGenerateDiagnosticsAsync() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; namespace TestNamespace { class TestClass { public void Method1() { Method2(new XmlDocument(){XmlResolver = new XmlUrlResolver()}); } public void Method2(XmlDocument doc){} } }", GetCA3075XmlDocumentWithNoSecureResolverCSharpResultAt(11, 39) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Namespace TestNamespace Class TestClass Public Sub Method1() Method2(New XmlDocument() With { _ .XmlResolver = New XmlUrlResolver() _ }) End Sub Public Sub Method2(doc As XmlDocument) End Sub End Class End Namespace", GetCA3075XmlDocumentWithNoSecureResolverBasicResultAt(9, 17) ); } } }
// 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.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class SumTests { public static IEnumerable<object[]> SumData(int[] counts) { foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), x => Functions.SumRange(0L, x))) yield return results; } // // Sum // [Theory] [MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })] public static void Sum_Int(Labeled<ParallelQuery<int>> labeled, int count, int sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Sum()); Assert.Equal(sum, query.Select(x => (int?)x).Sum()); Assert.Equal(default(int), query.Select(x => (int?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -x)); Assert.Equal(-sum, query.Sum(x => -(int?)x)); Assert.Equal(default(int), query.Sum(x => (int?)null)); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (int?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(int?)x : null)); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (int?)null).Sum()); Assert.Equal(0, query.Sum(x => (int?)null)); } [Theory] [OuterLoop] [MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 64 })] public static void Sum_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int sum) { Sum_Int(labeled, count, sum); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))] public static void Sum_Int_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : (int?)x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -x)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -(int?)x)); } [Theory] [MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })] public static void Sum_Long(Labeled<ParallelQuery<int>> labeled, int count, long sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (long)x).Sum()); Assert.Equal(sum, query.Select(x => (long?)x).Sum()); Assert.Equal(default(long), query.Select(x => (long?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(long)x)); Assert.Equal(-sum, query.Sum(x => -(long?)x)); Assert.Equal(default(long), query.Sum(x => (long?)null)); } [Theory] [OuterLoop] [MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 1024 })] public static void Sum_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long sum) { Sum_Long(labeled, count, sum); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0L, count / 2), query.Select(x => x < count / 2 ? (long?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0L, count / 2), query.Sum(x => x < count / 2 ? -(long?)x : null)); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (long?)null).Sum()); Assert.Equal(0, query.Sum(x => (long?)null)); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))] public static void Sum_Long_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : (long?)x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -x)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -(long?)x)); } [Theory] [MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })] public static void Sum_Float(Labeled<ParallelQuery<int>> labeled, int count, float sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (float)x).Sum()); Assert.Equal(sum, query.Select(x => (float?)x).Sum()); Assert.Equal(default(float), query.Select(x => (float?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(float)x)); Assert.Equal(-sum, query.Sum(x => -(float?)x)); Assert.Equal(default(float), query.Sum(x => (float?)null)); } [Theory] [OuterLoop] [MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 1024 })] public static void Sum_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float sum) { Sum_Float(labeled, count, sum); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))] public static void Sum_Float_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => float.MaxValue).Sum()); Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => (float?)float.MaxValue).Sum().Value); Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => float.MaxValue)); Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => (float?)float.MaxValue).Value); Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => float.PositiveInfinity).Sum()); Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => (float?)float.PositiveInfinity).Sum().Value); Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => float.PositiveInfinity)); Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => (float?)float.PositiveInfinity).Value); Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => float.MinValue).Sum()); Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => (float?)float.MinValue).Sum().Value); Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => float.MinValue)); Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => (float?)float.MinValue).Value); Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => float.NegativeInfinity).Sum()); Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => (float?)float.NegativeInfinity).Sum().Value); Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => float.NegativeInfinity)); Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => (float?)float.NegativeInfinity).Value); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))] public static void Sum_Float_NaN(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum()); Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value); Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x)); Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value); Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum()); Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value); Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x)); Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value); Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : -x).Sum()); Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value); Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : -x)); Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : -x)).Value); Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum()); Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value); Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x)); Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (float?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(float?)x : null)); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (float?)null).Sum()); Assert.Equal(0, query.Sum(x => (float?)null)); } [Theory] [MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })] public static void Sum_Double(Labeled<ParallelQuery<int>> labeled, int count, double sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (double)x).Sum()); Assert.Equal(sum, query.Select(x => (double?)x).Sum()); Assert.Equal(default(double), query.Select(x => (double?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(double)x)); Assert.Equal(-sum, query.Sum(x => -(double?)x)); Assert.Equal(default(double), query.Sum(x => (double?)null)); } [Theory] [OuterLoop] [MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 1024 })] public static void Sum_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double sum) { Sum_Double(labeled, count, sum); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))] public static void Sum_Double_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => double.MaxValue).Sum()); Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => (double?)double.MaxValue).Sum().Value); Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => double.MaxValue)); Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => (double?)double.MaxValue).Value); Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => double.PositiveInfinity).Sum()); Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => (double?)double.PositiveInfinity).Sum().Value); Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => double.PositiveInfinity)); Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => (double?)double.PositiveInfinity).Value); Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => double.MinValue).Sum()); Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => (double?)double.MinValue).Sum().Value); Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => double.MinValue)); Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => (double?)double.MinValue).Value); Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => double.NegativeInfinity).Sum()); Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => (double?)double.NegativeInfinity).Sum().Value); Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => double.NegativeInfinity)); Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => (double?)double.NegativeInfinity).Value); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))] public static void Sum_Double_NaN(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum()); Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value); Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x)); Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value); Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum()); Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value); Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x)); Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value); Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : -x).Sum()); Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value); Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : -x)); Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : -x)).Value); Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum()); Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value); Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x)); Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (double?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(double?)x : null)); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (double?)null).Sum()); Assert.Equal(0, query.Sum(x => (double?)null)); } [Theory] [MemberData(nameof(SumData), new[] { 0, 1, 2, 16 })] public static void Sum_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (decimal)x).Sum()); Assert.Equal(sum, query.Select(x => (decimal?)x).Sum()); Assert.Equal(default(decimal), query.Select(x => (decimal?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(decimal)x)); Assert.Equal(default(decimal), query.Sum(x => (decimal?)null)); } [Theory] [OuterLoop] [MemberData(nameof(SumData), new[] { 1024 * 4, 1024 * 1024 })] public static void Sum_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { Sum_Decimal(labeled, count, sum); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))] public static void Sum_Decimal_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : (decimal?)x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -x)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -(decimal?)x)); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (decimal?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(decimal?)x : null)); } [Theory] [MemberData(nameof(SumData), new[] { 1, 2, 16 })] public static void Sum_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (decimal?)null).Sum()); Assert.Equal(0, query.Sum(x => (decimal?)null)); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))] public static void Sum_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (int?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal?)x)); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))] public static void Sum_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal?>)(x => { throw new DeliberateTestException(); }))); } [Fact] public static void Sum_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Sum((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Sum((Func<int?, int?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Sum((Func<long, long>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Sum((Func<long?, long?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Sum((Func<float, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Sum((Func<float?, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Sum((Func<double, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Sum((Func<double?, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Sum((Func<decimal, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Sum((Func<decimal?, decimal>)null)); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Graph.RBAC.Version1_6 { using Microsoft.Azure; using Microsoft.Azure.Graph; using Microsoft.Azure.Graph.RBAC; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ServicePrincipalsOperations. /// </summary> public static partial class ServicePrincipalsOperationsExtensions { /// <summary> /// Creates a service principal in the directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// Parameters to create a service principal. /// </param> public static ServicePrincipal Create(this IServicePrincipalsOperations operations, ServicePrincipalCreateParameters parameters) { return operations.CreateAsync(parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates a service principal in the directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// Parameters to create a service principal. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ServicePrincipal> CreateAsync(this IServicePrincipalsOperations operations, ServicePrincipalCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of service principals from the current tenant. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<ServicePrincipal> List(this IServicePrincipalsOperations operations, ODataQuery<ServicePrincipal> odataQuery = default(ODataQuery<ServicePrincipal>)) { return ((IServicePrincipalsOperations)operations).ListAsync(odataQuery).GetAwaiter().GetResult(); } /// <summary> /// Gets a list of service principals from the current tenant. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ServicePrincipal>> ListAsync(this IServicePrincipalsOperations operations, ODataQuery<ServicePrincipal> odataQuery = default(ODataQuery<ServicePrincipal>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a service principal from the directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal to delete. /// </param> public static void Delete(this IServicePrincipalsOperations operations, string objectId) { operations.DeleteAsync(objectId).GetAwaiter().GetResult(); } /// <summary> /// Deletes a service principal from the directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal to delete. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IServicePrincipalsOperations operations, string objectId, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(objectId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets service principal information from the directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal to get. /// </param> public static ServicePrincipal Get(this IServicePrincipalsOperations operations, string objectId) { return operations.GetAsync(objectId).GetAwaiter().GetResult(); } /// <summary> /// Gets service principal information from the directory. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal to get. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ServicePrincipal> GetAsync(this IServicePrincipalsOperations operations, string objectId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(objectId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get the keyCredentials associated with the specified service principal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal for which to get keyCredentials. /// </param> public static IEnumerable<KeyCredential> ListKeyCredentials(this IServicePrincipalsOperations operations, string objectId) { return operations.ListKeyCredentialsAsync(objectId).GetAwaiter().GetResult(); } /// <summary> /// Get the keyCredentials associated with the specified service principal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal for which to get keyCredentials. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<KeyCredential>> ListKeyCredentialsAsync(this IServicePrincipalsOperations operations, string objectId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeyCredentialsWithHttpMessagesAsync(objectId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update the keyCredentials associated with a service principal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID for which to get service principal information. /// </param> /// <param name='parameters'> /// Parameters to update the keyCredentials of an existing service principal. /// </param> public static void UpdateKeyCredentials(this IServicePrincipalsOperations operations, string objectId, KeyCredentialsUpdateParameters parameters) { operations.UpdateKeyCredentialsAsync(objectId, parameters).GetAwaiter().GetResult(); } /// <summary> /// Update the keyCredentials associated with a service principal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID for which to get service principal information. /// </param> /// <param name='parameters'> /// Parameters to update the keyCredentials of an existing service principal. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateKeyCredentialsAsync(this IServicePrincipalsOperations operations, string objectId, KeyCredentialsUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateKeyCredentialsWithHttpMessagesAsync(objectId, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the passwordCredentials associated with a service principal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal. /// </param> public static IEnumerable<PasswordCredential> ListPasswordCredentials(this IServicePrincipalsOperations operations, string objectId) { return operations.ListPasswordCredentialsAsync(objectId).GetAwaiter().GetResult(); } /// <summary> /// Gets the passwordCredentials associated with a service principal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<PasswordCredential>> ListPasswordCredentialsAsync(this IServicePrincipalsOperations operations, string objectId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListPasswordCredentialsWithHttpMessagesAsync(objectId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the passwordCredentials associated with a service principal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal. /// </param> /// <param name='parameters'> /// Parameters to update the passwordCredentials of an existing service /// principal. /// </param> public static void UpdatePasswordCredentials(this IServicePrincipalsOperations operations, string objectId, PasswordCredentialsUpdateParameters parameters) { operations.UpdatePasswordCredentialsAsync(objectId, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates the passwordCredentials associated with a service principal. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='objectId'> /// The object ID of the service principal. /// </param> /// <param name='parameters'> /// Parameters to update the passwordCredentials of an existing service /// principal. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePasswordCredentialsAsync(this IServicePrincipalsOperations operations, string objectId, PasswordCredentialsUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdatePasswordCredentialsWithHttpMessagesAsync(objectId, parameters, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets a list of service principals from the current tenant. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextLink'> /// Next link for the list operation. /// </param> public static IPage<ServicePrincipal> ListNext(this IServicePrincipalsOperations operations, string nextLink) { return operations.ListNextAsync(nextLink).GetAwaiter().GetResult(); } /// <summary> /// Gets a list of service principals from the current tenant. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextLink'> /// Next link for the list operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ServicePrincipal>> ListNextAsync(this IServicePrincipalsOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
//Josip Medved <[email protected]> www.medo64.com //2018-02-24: Added option to raise event on read/write instead of using registry. //2010-10-31: Added option to skip registry writes (NoRegistryWrites). //2010-10-17: Limited all loaded forms to screen's working area. // Changed LoadNowAndSaveOnClose to use SetupOnLoadAndClose. //2009-07-04: Compatibility with Mono 2.4. //2008-12-27: Added LoadNowAndSaveOnClose method. //2008-07-10: Fixed resize on load when window is maximized. //2008-05-11: Windows with fixed borders are no longer resized. //2008-04-11: Cleaned code to match FxCop 1.36 beta 2 (CompoundWordsShouldBeCasedCorrectly). //2008-02-15: Fixed bug with positioning of centered forms. //2008-01-31: Fixed bug that caused only first control to be loaded/saved. //2008-01-10: Moved private methods to Helper class. //2008-01-05: Removed obsoleted methods. //2008-01-02: Calls to MoveSplitterTo method are now checked. //2007-12-27: Added Load overloads for multiple controls. // Obsoleted Subscribe method. //2007-12-24: Changed SubKeyPath to include full path. //2007-11-21: Initial version. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.IO; using System.Reflection; using System.Security; using System.Text; using System.Windows.Forms; using Microsoft.Win32; namespace Medo.Windows.Forms { /// <summary> /// Enables storing and loading of windows control's state. /// It is written in State key at HKEY_CURRENT_USER branch withing SubKeyPath of Settings class. /// This class is not thread-safe since it should be called only from one thread - one that has interface. /// </summary> public static class State { private static string _subkeyPath; /// <summary> /// Gets/sets subkey used for registry storage. /// </summary> public static string SubkeyPath { get { if (_subkeyPath == null) { var assembly = Assembly.GetEntryAssembly(); string company = null; var companyAttributes = assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true); if ((companyAttributes != null) && (companyAttributes.Length >= 1)) { company = ((AssemblyCompanyAttribute)companyAttributes[companyAttributes.Length - 1]).Company; } string product = null; var productAttributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true); if ((productAttributes != null) && (productAttributes.Length >= 1)) { product = ((AssemblyProductAttribute)productAttributes[productAttributes.Length - 1]).Product; } else { var titleAttributes = assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), true); if ((titleAttributes != null) && (titleAttributes.Length >= 1)) { product = ((AssemblyTitleAttribute)titleAttributes[titleAttributes.Length - 1]).Title; } else { product = assembly.GetName().Name; } } var path = "Software"; if (!string.IsNullOrEmpty(company)) { path += "\\" + company; } if (!string.IsNullOrEmpty(product)) { path += "\\" + product; } _subkeyPath = path + "\\State"; } return _subkeyPath; } set { _subkeyPath = value; } } /// <summary> /// Gets/sets whether settings should be written to registry. /// </summary> public static bool NoRegistryWrites { get; set; } #region Load Save - All /// <summary> /// Loads previous state. /// Supported controls are Form, PropertyGrid, ListView and SplitContainer. /// </summary> /// <param name="form">Form on which's FormClosing handler this function will attach. State will not be altered for this parameter.</param> /// <param name="controls">Controls to load and to save.</param> /// <exception cref="ArgumentNullException">Form is null.</exception> /// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception> /// <exception cref="ArgumentException">Form already used.</exception> [Obsolete("Use SetupOnLoadAndClose instead.")] public static void LoadNowAndSaveOnClose(Form form, params Control[] controls) { SetupOnLoadAndClose(form, controls); } /// <summary> /// Loads previous state. /// Supported controls are Form, PropertyGrid, ListView and SplitContainer. /// </summary> /// <param name="form">Form on which's FormClosing handler this function will attach. State will not be altered for this parameter.</param> /// <param name="controls">Controls to load and to save.</param> /// <exception cref="ArgumentNullException">Form is null.</exception> /// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception> /// <exception cref="ArgumentException">Form setup already done.</exception> public static void SetupOnLoadAndClose(Form form, params Control[] controls) { if (form == null) { throw new ArgumentNullException("form", "Form is null."); } if (formSetup.ContainsKey(form)) { throw new ArgumentException("Form setup already done.", "form"); } Load(form); if (controls != null) { Load(controls); } formSetup.Add(form, controls); form.Load += new EventHandler(form_Load); form.FormClosed += new FormClosedEventHandler(form_FormClosed); } private static Dictionary<Form, Control[]> formSetup = new Dictionary<Form, Control[]>(); private static void form_Load(object sender, EventArgs e) { var form = sender as Form; if (formSetup.ContainsKey(form)) { Load(form); Load(formSetup[form]); } } private static void form_FormClosed(object sender, FormClosedEventArgs e) { var form = sender as Form; if (formSetup.ContainsKey(form)) { Save(form); Save(formSetup[form]); formSetup.Remove(form); } } /// <summary> /// Loads previous state. /// Supported controls are Form, PropertyGrid, ListView and SplitContainer. /// </summary> /// <param name="controls">Controls to load.</param> /// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception> public static void Load(params Control[] controls) { if (controls == null) { return; } for (var i = 0; i < controls.Length; ++i) { if (controls[i] is Form form) { Load(form); } else if (controls[i] is PropertyGrid propertyGrid) { Load(propertyGrid); } else if (controls[i] is ListView listView) { Load(listView); } else if (controls[i] is SplitContainer splitContainer) { Load(splitContainer); } } } /// <summary> /// Saves control's state. /// Supported controls are Form, PropertyGrid, ListView and SplitContainer. /// </summary> /// <param name="controls">Controls to save.</param> /// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception> public static void Save(params Control[] controls) { if (controls == null) { return; } for (var i = 0; i < controls.Length; ++i) { if (controls[i] is Form form) { Save(form); } else if (controls[i] is PropertyGrid propertyGrid) { Save(propertyGrid); } else if (controls[i] is ListView listView) { Save(listView); } else if (controls[i] is SplitContainer splitContainer) { Save(splitContainer); } } } #endregion #region Load Save - Form /// <summary> /// Saves Form state (Left,Top,Width,Height,WindowState). /// </summary> /// <param name="form">Form.</param> /// <exception cref="ArgumentNullException">Form is null.</exception> /// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception> public static void Save(Form form) { if (form == null) { throw new ArgumentNullException("form", "Form is null."); } var baseValueName = Helper.GetControlPath(form); Write(baseValueName + ".WindowState", Convert.ToInt32(form.WindowState, CultureInfo.InvariantCulture)); if (form.WindowState == FormWindowState.Normal) { Write(baseValueName + ".Left", form.Bounds.Left); Write(baseValueName + ".Top", form.Bounds.Top); Write(baseValueName + ".Width", form.Bounds.Width); Write(baseValueName + ".Height", form.Bounds.Height); } else { Write(baseValueName + ".Left", form.RestoreBounds.Left); Write(baseValueName + ".Top", form.RestoreBounds.Top); Write(baseValueName + ".Width", form.RestoreBounds.Width); Write(baseValueName + ".Height", form.RestoreBounds.Height); } } /// <summary> /// Loads previous Form state (Left,Top,Width,Height,WindowState). /// If StartupPosition value is Manual, saved settings are used, for other types, it tryes to resemble original behaviour. /// </summary> /// <param name="form">Form.</param> /// <exception cref="ArgumentNullException">Form is null.</exception> /// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception> public static void Load(Form form) { if (form == null) { throw new ArgumentNullException("form", "Form is null."); } var baseValueName = Helper.GetControlPath(form); var currWindowState = Convert.ToInt32(form.WindowState, CultureInfo.InvariantCulture); int currLeft, currTop, currWidth, currHeight; if (form.WindowState == FormWindowState.Normal) { currLeft = form.Bounds.Left; currTop = form.Bounds.Top; currWidth = form.Bounds.Width; currHeight = form.Bounds.Height; } else { currLeft = form.RestoreBounds.Left; currTop = form.RestoreBounds.Top; currWidth = form.RestoreBounds.Width; currHeight = form.RestoreBounds.Height; } var newLeft = Read(baseValueName + ".Left", currLeft); var newTop = Read(baseValueName + ".Top", currTop); var newWidth = Read(baseValueName + ".Width", currWidth); var newHeight = Read(baseValueName + ".Height", currHeight); var newWindowState = Read(baseValueName + ".WindowState", currWindowState); if ((form.FormBorderStyle == FormBorderStyle.Fixed3D) || (form.FormBorderStyle == FormBorderStyle.FixedDialog) || (form.FormBorderStyle == FormBorderStyle.FixedSingle) || (form.FormBorderStyle == FormBorderStyle.FixedToolWindow)) { newWidth = currWidth; newHeight = currHeight; } var screen = Screen.FromRectangle(new Rectangle(newLeft, newTop, newWidth, newHeight)); switch (form.StartPosition) { case FormStartPosition.CenterParent: { if (form.Parent != null) { newLeft = form.Parent.Left + (form.Parent.Width - newWidth) / 2; newTop = form.Parent.Top + (form.Parent.Height - newHeight) / 2; } else if (form.Owner != null) { newLeft = form.Owner.Left + (form.Owner.Width - newWidth) / 2; newTop = form.Owner.Top + (form.Owner.Height - newHeight) / 2; } else { newLeft = screen.WorkingArea.Left + (screen.WorkingArea.Width - newWidth) / 2; newTop = screen.WorkingArea.Top + (screen.WorkingArea.Height - newHeight) / 2; } } break; case FormStartPosition.CenterScreen: { newLeft = screen.WorkingArea.Left + (screen.WorkingArea.Width - newWidth) / 2; newTop = screen.WorkingArea.Top + (screen.WorkingArea.Height - newHeight) / 2; } break; } if (newWidth <= 0) { newWidth = currWidth; } if (newHeight <= 0) { newHeight = currHeight; } if (newWidth > screen.WorkingArea.Width) { newWidth = screen.WorkingArea.Width; } if (newHeight > screen.WorkingArea.Height) { newHeight = screen.WorkingArea.Height; } if (newLeft + newWidth > screen.WorkingArea.Right) { newLeft = screen.WorkingArea.Left + (screen.WorkingArea.Width - newWidth); } if (newTop + newHeight > screen.WorkingArea.Bottom) { newTop = screen.WorkingArea.Top + (screen.WorkingArea.Height - newHeight); } if (newLeft < screen.WorkingArea.Left) { newLeft = screen.WorkingArea.Left; } if (newTop < screen.WorkingArea.Top) { newTop = screen.WorkingArea.Top; } form.Location = new Point(newLeft, newTop); form.Size = new Size(newWidth, newHeight); if (newWindowState == Convert.ToInt32(FormWindowState.Maximized, CultureInfo.InvariantCulture)) { form.WindowState = FormWindowState.Maximized; } //no need for any code - it is already either in normal state or minimized (will be restored to normal). } #endregion #region Load Save - PropertyGrid /// <summary> /// Loads previous PropertyGrid state (LabelWidth, PropertySort). /// </summary> /// <param name="control">PropertyGrid.</param> /// <exception cref="ArgumentNullException">Control is null.</exception> /// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "PropertyGrid is passed because of reflection upon its member.")] public static void Load(PropertyGrid control) { if (control == null) { throw new ArgumentNullException("control", "Control is null."); } var baseValueName = Helper.GetControlPath(control); try { control.PropertySort = (PropertySort)(Read(baseValueName + ".PropertySort", Convert.ToInt32(control.PropertySort, CultureInfo.InvariantCulture))); } catch (InvalidEnumArgumentException) { } var fieldGridView = control.GetType().GetField("gridView", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); var gridViewObject = fieldGridView.GetValue(control); if (gridViewObject != null) { var currentlabelWidth = 0; var propertyInternalLabelWidth = gridViewObject.GetType().GetProperty("InternalLabelWidth", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance); if (propertyInternalLabelWidth != null) { var val = propertyInternalLabelWidth.GetValue(gridViewObject, null); if (val is int) { currentlabelWidth = (int)val; } } var labelWidth = Read(baseValueName + ".LabelWidth", currentlabelWidth); if ((labelWidth > 0) && (labelWidth < control.Width)) { var methodMoveSplitterToFlags = BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance; var methodMoveSplitterTo = gridViewObject.GetType().GetMethod("MoveSplitterTo", methodMoveSplitterToFlags); if (methodMoveSplitterTo != null) { methodMoveSplitterTo.Invoke(gridViewObject, methodMoveSplitterToFlags, null, new object[] { labelWidth }, CultureInfo.CurrentCulture); } } } } /// <summary> /// Saves PropertyGrid state (LabelWidth). /// </summary> /// <param name="control">PropertyGrid.</param> /// <exception cref="ArgumentNullException">Control is null.</exception> /// <exception cref="NotSupportedException">This control's parents cannot be resolved using Name property.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "PropertyGrid is passed because of reflection upon its member.")] public static void Save(PropertyGrid control) { if (control == null) { throw new ArgumentNullException("control", "Control is null."); } var baseValueName = Helper.GetControlPath(control); Write(baseValueName + ".PropertySort", Convert.ToInt32(control.PropertySort, CultureInfo.InvariantCulture)); var fieldGridView = control.GetType().GetField("gridView", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); var gridViewObject = fieldGridView.GetValue(control); if (gridViewObject != null) { var propertyInternalLabelWidth = gridViewObject.GetType().GetProperty("InternalLabelWidth", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance); if (propertyInternalLabelWidth != null) { var val = propertyInternalLabelWidth.GetValue(gridViewObject, null); if (val is int) { Write(baseValueName + ".LabelWidth", (int)val); } } } } #endregion #region Load Save - ListView /// <summary> /// Loads previous ListView state (Column header width). /// </summary> /// <param name="control">ListView.</param> /// <exception cref="ArgumentNullException">Control is null.</exception> public static void Load(ListView control) { if (control == null) { throw new ArgumentNullException("control", "Control is null."); } var baseValueName = Helper.GetControlPath(control); for (var i = 0; i < control.Columns.Count; i++) { var width = Read(baseValueName + ".ColumnHeaderWidth[" + i.ToString(CultureInfo.InvariantCulture) + "]", control.Columns[i].Width); if (width > control.ClientRectangle.Width) { width = control.ClientRectangle.Width; } control.Columns[i].Width = width; } } /// <summary> /// Saves ListView state (Column header width). /// </summary> /// <param name="control">ListView.</param> /// <exception cref="ArgumentNullException">Control is null.</exception> public static void Save(ListView control) { if (control == null) { throw new ArgumentNullException("control", "Control is null."); } var baseValueName = Helper.GetControlPath(control); for (var i = 0; i < control.Columns.Count; i++) { Write(baseValueName + ".ColumnHeaderWidth[" + i.ToString(CultureInfo.InvariantCulture) + "]", control.Columns[i].Width); } } #endregion #region Load Save - SplitContainer /// <summary> /// Loads previous SplitContainer state. /// </summary> /// <param name="control">SplitContainer.</param> /// <exception cref="ArgumentNullException">Control is null.</exception> public static void Load(SplitContainer control) { if (control == null) { throw new ArgumentNullException("control", "Control is null."); } var baseValueName = Helper.GetControlPath(control); try { control.Orientation = (Orientation)(Read(baseValueName + ".Orientation", Convert.ToInt32(control.Orientation, CultureInfo.InvariantCulture))); } catch (InvalidEnumArgumentException) { } try { var distance = Read(baseValueName + ".SplitterDistance", control.SplitterDistance); try { control.SplitterDistance = distance; } catch (ArgumentOutOfRangeException) { } } catch (InvalidEnumArgumentException) { } } /// <summary> /// Saves SplitContainer state. /// </summary> /// <param name="control">SplitContainer.</param> /// <exception cref="ArgumentNullException">Control is null.</exception> public static void Save(SplitContainer control) { if (control == null) { throw new ArgumentNullException("control", "Control is null."); } var baseValueName = Helper.GetControlPath(control); Write(baseValueName + ".Orientation", Convert.ToInt32(control.Orientation, CultureInfo.InvariantCulture)); Write(baseValueName + ".SplitterDistance", control.SplitterDistance); } #endregion #region Store /// <summary> /// Event handler used to read state. /// If used, registry is not read. /// </summary> public static event EventHandler<StateReadEventArgs> ReadState; /// <summary> /// Event handler used to write state. /// If used, registry is not written to. /// </summary> public static event EventHandler<StateWriteEventArgs> WriteState; private static void Write(string valueName, int value) { var ev = WriteState; if (ev != null) { ev.Invoke(null, new StateWriteEventArgs(valueName, value)); } else { Helper.RegistryWrite(valueName, value); } } private static int Read(string valueName, int defaultValue) { var ev = ReadState; if (ev != null) { var state = new StateReadEventArgs(valueName, defaultValue); ev.Invoke(null, state); return state.Value; } else { return Helper.RegistryRead(valueName, defaultValue); } } #endregion Store private static class Helper { internal static void RegistryWrite(string valueName, int value) { if (State.NoRegistryWrites == false) { try { if (State.SubkeyPath.Length == 0) { return; } using (var rk = Registry.CurrentUser.CreateSubKey(State.SubkeyPath)) { if (rk != null) { rk.SetValue(valueName, value, RegistryValueKind.DWord); } } } catch (IOException) { //key is deleted. } catch (UnauthorizedAccessException) { } //key is write protected. } } internal static int RegistryRead(string valueName, int defaultValue) { try { using (var rk = Registry.CurrentUser.OpenSubKey(State.SubkeyPath, false)) { if (rk != null) { var value = rk.GetValue(valueName, null); if (value == null) { return defaultValue; } var valueKind = RegistryValueKind.DWord; if (!State.Helper.IsRunningOnMono) { valueKind = rk.GetValueKind(valueName); } if ((value != null) && (valueKind == RegistryValueKind.DWord)) { return (int)value; } } } } catch (SecurityException) { } return defaultValue; } internal static string GetControlPath(Control control) { var sbPath = new StringBuilder(); var currControl = control; while (true) { var parentControl = currControl.Parent; if (parentControl == null) { if (sbPath.Length > 0) { sbPath.Insert(0, "."); } sbPath.Insert(0, currControl.GetType().FullName); break; } else { if (string.IsNullOrEmpty(currControl.Name)) { throw new NotSupportedException("This control's parents cannot be resolved using Name property."); } else { if (sbPath.Length > 0) { sbPath.Insert(0, "."); } sbPath.Insert(0, currControl.Name); } } currControl = parentControl; } return sbPath.ToString(); } private static bool IsRunningOnMono { get { return (Type.GetType("Mono.Runtime") != null); } } } } /// <summary> /// State read event arguments. /// </summary> public class StateReadEventArgs : EventArgs { /// <summary> /// Create a new instance. /// </summary> /// <param name="name">Property name.</param> /// <param name="defaultValue">Default property value.</param> public StateReadEventArgs(string name, int defaultValue) { if (name == null) { throw new ArgumentNullException(nameof(name), "Name cannot be null."); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentOutOfRangeException(nameof(name), "Name cannot be empty."); } this.Name = name; this.DefaultValue = defaultValue; this.Value = defaultValue; } /// <summary> /// Gets property name. /// </summary> public string Name { get; } /// <summary> /// Gets default property value. /// </summary> public int DefaultValue { get; } /// <summary> /// Gets/sets property value. /// </summary> public int Value { get; set; } } /// <summary> /// State write event arguments. /// </summary> public class StateWriteEventArgs : EventArgs { /// <summary> /// Create a new instance. /// </summary> /// <param name="name">Property name.</param> /// <param name="value">Property value.</param> public StateWriteEventArgs(string name, int value) { if (name == null) { throw new ArgumentNullException(nameof(name), "Name cannot be null."); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentOutOfRangeException(nameof(name), "Name cannot be empty."); } this.Name = name; this.Value = value; } /// <summary> /// Gets property name. /// </summary> public string Name { get; } /// <summary> /// Gets property value. /// </summary> public int Value { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TrueCraft.API { public enum ContainmentType { Disjoint, Contains, Intersects } // Mostly taken from the MonoXna project, which is licensed under the MIT license public struct BoundingBox : IEquatable<BoundingBox> { #region Public Fields public Vector3 Min; public Vector3 Max; public const int CornerCount = 8; #endregion Public Fields #region Public Constructors public BoundingBox(Vector3 min, Vector3 max) { this.Min = min; this.Max = max; } public BoundingBox(BoundingBox b) { this.Min = new Vector3(b.Min); this.Max = new Vector3(b.Max); } #endregion Public Constructors #region Public Methods public ContainmentType Contains(BoundingBox box) { //test if all corner is in the same side of a face by just checking min and max if (box.Max.X < Min.X || box.Min.X > Max.X || box.Max.Y < Min.Y || box.Min.Y > Max.Y || box.Max.Z < Min.Z || box.Min.Z > Max.Z) return ContainmentType.Disjoint; if (box.Min.X >= Min.X && box.Max.X <= Max.X && box.Min.Y >= Min.Y && box.Max.Y <= Max.Y && box.Min.Z >= Min.Z && box.Max.Z <= Max.Z) return ContainmentType.Contains; return ContainmentType.Intersects; } public bool Contains(Vector3 vec) { return Min.X <= vec.X && vec.X <= Max.X && Min.Y <= vec.Y && vec.Y <= Max.Y && Min.Z <= vec.Z && vec.Z <= Max.Z; } public static BoundingBox CreateFromPoints(IEnumerable<Vector3> points) { if (points == null) throw new ArgumentNullException(); bool empty = true; Vector3 vector2 = new Vector3(float.MaxValue); Vector3 vector1 = new Vector3(float.MinValue); foreach (Vector3 vector3 in points) { vector2 = Vector3.Min(vector2, vector3); vector1 = Vector3.Max(vector1, vector3); empty = false; } if (empty) throw new ArgumentException(); return new BoundingBox(vector2, vector1); } /// <summary> /// Offsets this BoundingBox. Does not modify this object, but returns a new one /// </summary> /// <returns> /// The offset bounding box. /// </returns> /// <param name='Offset'> /// The offset. /// </param> public BoundingBox OffsetBy(Vector3 Offset) { return new BoundingBox(Min + Offset, Max + Offset); } public Vector3[] GetCorners() { return new Vector3[] { new Vector3(this.Min.X, this.Max.Y, this.Max.Z), new Vector3(this.Max.X, this.Max.Y, this.Max.Z), new Vector3(this.Max.X, this.Min.Y, this.Max.Z), new Vector3(this.Min.X, this.Min.Y, this.Max.Z), new Vector3(this.Min.X, this.Max.Y, this.Min.Z), new Vector3(this.Max.X, this.Max.Y, this.Min.Z), new Vector3(this.Max.X, this.Min.Y, this.Min.Z), new Vector3(this.Min.X, this.Min.Y, this.Min.Z) }; } public bool Equals(BoundingBox other) { return (this.Min == other.Min) && (this.Max == other.Max); } public override bool Equals(object obj) { return (obj is BoundingBox) && this.Equals((BoundingBox)obj); } public override int GetHashCode() { return this.Min.GetHashCode() + this.Max.GetHashCode(); } public bool Intersects(BoundingBox box) { bool result; Intersects(ref box, out result); return result; } public void Intersects(ref BoundingBox box, out bool result) { if ((this.Max.X > box.Min.X) && (this.Min.X < box.Max.X)) { if ((this.Max.Y < box.Min.Y) || (this.Min.Y > box.Max.Y)) { result = false; return; } result = (this.Max.Z > box.Min.Z) && (this.Min.Z < box.Max.Z); return; } result = false; } public static bool operator ==(BoundingBox a, BoundingBox b) { return a.Equals(b); } public static bool operator !=(BoundingBox a, BoundingBox b) { return !a.Equals(b); } public override string ToString() { return string.Format("{{Min:{0} Max:{1}}}", this.Min.ToString(), this.Max.ToString()); } #endregion public double Height { get { return Max.Y - Min.Y; } } public double Width { get { return Max.X - Min.X; } } public double Depth { get { return Max.Z - Min.Z; } } public Vector3 Center { get { return (this.Min + this.Max) / 2; } } } }
/* * Copyright 2012 dotlucene.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Data; using System.IO; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Standard; using Lucene.Net.Documents; using Lucene.Net.QueryParsers; using Lucene.Net.Search; using Lucene.Net.Search.Highlight; using Lucene.Net.Store; using Version = Lucene.Net.Util.Version; namespace Searcher { /// <summary> /// Summary description for WebForm1. /// </summary> public partial class Search : System.Web.UI.Page { /// <summary> /// Search results. /// </summary> protected DataTable Results = new DataTable(); /// <summary> /// First item on page (index format). /// </summary> private int startAt; /// <summary> /// First item on page (user format). /// </summary> private int fromItem; /// <summary> /// Last item on page (user format). /// </summary> private int toItem; /// <summary> /// Total items returned by search. /// </summary> private int total; /// <summary> /// Time it took to make the search. /// </summary> private TimeSpan duration; /// <summary> /// How many items can be showed on one page. /// </summary> private readonly int maxResults = 10; protected void Page_Load(object sender, System.EventArgs e) { // Press ButtonSearch on enter Page.RegisterHiddenField("__EVENTTARGET", "ButtonSearch"); if (!IsPostBack) { if (this.Query != null) { search(); DataBind(); } else { Response.Redirect("~/"); } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.ButtonSearch.Click += new System.EventHandler(this.ButtonSearch_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion /// <summary> /// Does the search and stores the information about the results. /// </summary> private void search() { DateTime start = DateTime.Now; // create the searcher // index is placed in "index" subdirectory string indexDirectory = Server.MapPath("~/App_Data/index"); //var analyzer = new StandardAnalyzer(Version.LUCENE_30); var analyzer = new Lucene.Net.Analysis.PanGu.PanGuAnalyzer(); IndexSearcher searcher = new IndexSearcher(FSDirectory.Open(indexDirectory)); // parse the query, "text" is the default field to search var parser = new QueryParser(Version.LUCENE_30, "name", analyzer); parser.AllowLeadingWildcard = true; Query query = parser.Parse(this.Query); // create the result DataTable this.Results.Columns.Add("title", typeof(string)); this.Results.Columns.Add("sample", typeof(string)); this.Results.Columns.Add("path", typeof(string)); this.Results.Columns.Add("url", typeof(string)); // search TopDocs hits = searcher.Search(query, 200); this.total = hits.TotalHits; // create highlighter IFormatter formatter = new SimpleHTMLFormatter("<span style=\"font-weight:bold;\">", "</span>"); SimpleFragmenter fragmenter = new SimpleFragmenter(80); QueryScorer scorer = new QueryScorer(query); Highlighter highlighter = new Highlighter(formatter, scorer); highlighter.TextFragmenter = fragmenter; // initialize startAt this.startAt = InitStartAt(); // how many items we should show - less than defined at the end of the results int resultsCount = Math.Min(total, this.maxResults + this.startAt); for (int i = startAt; i < resultsCount; i++) { // get the document from index Document doc = searcher.Doc(hits.ScoreDocs[i].Doc); TokenStream stream = analyzer.TokenStream("", new StringReader(doc.Get("name"))); String sample= highlighter.GetBestFragments(stream, doc.Get("name"), 2, "..."); String path = doc.Get("path"); // create a new row with the result data DataRow row = this.Results.NewRow(); row["title"] = doc.Get("name"); //row["path"] = "api/" + path; //row["url"] = "www.dotlucene.net/documentation/api/" + path; //row["sample"] = sample; this.Results.Rows.Add(row); } searcher.Dispose(); // result information this.duration = DateTime.Now - start; this.fromItem = startAt + 1; this.toItem = Math.Min(startAt + maxResults, total); } /// <summary> /// Page links. DataTable might be overhead but there used to be more fields in previous version so I'm keeping it for now. /// </summary> protected DataTable Paging { get { // pageNumber starts at 1 int pageNumber = (startAt + maxResults - 1) / maxResults; DataTable dt = new DataTable(); dt.Columns.Add("html", typeof(string)); DataRow ar = dt.NewRow(); ar["html"] = PagingItemHtml(startAt, pageNumber + 1, false); dt.Rows.Add(ar); int previousPagesCount = 4; for (int i = pageNumber - 1; i >= 0 && i >= pageNumber - previousPagesCount; i--) { int step = i - pageNumber; DataRow r = dt.NewRow(); r["html"] = PagingItemHtml(startAt + (maxResults * step), i + 1, true); dt.Rows.InsertAt(r, 0); } int nextPagesCount = 4; for (int i = pageNumber + 1; i <= PageCount && i <= pageNumber + nextPagesCount; i++) { int step = i - pageNumber; DataRow r = dt.NewRow(); r["html"] = PagingItemHtml(startAt + (maxResults * step), i + 1, true); dt.Rows.Add(r); } return dt; } } /// <summary> /// Prepares HTML of a paging item (bold number for current page, links for others). /// </summary> /// <param name="start"></param> /// <param name="number"></param> /// <param name="active"></param> /// <returns></returns> private string PagingItemHtml(int start, int number, bool active) { if (active) return "<a href=\"Search.aspx?q=" + this.Query + "&start=" + start + "\">" + number + "</a>"; else return "<b>" + number + "</b>"; } /// <summary> /// Prepares the string with seach summary information. /// </summary> protected string Summary { get { if (total > 0) return "Results <b>" + this.fromItem + " - " + this.toItem + "</b> of <b>" + this.total + "</b> for <b>" + this.Query + "</b>. (" + this.duration.TotalSeconds + " seconds)"; return "No results found"; } } /// <summary> /// Return search query or null if not provided. /// </summary> protected string Query { get { string query = this.Request.Params["q"]; if (query == String.Empty) return null; return query; } } /// <summary> /// Initializes startAt value. Checks for bad values. /// </summary> /// <returns></returns> private int InitStartAt() { try { int sa = Convert.ToInt32(this.Request.Params["start"]); // too small starting item, return first page if (sa < 0) return 0; // too big starting item, return last page if (sa >= total - 1) { return LastPageStartsAt; } return sa; } catch { return 0; } } /// <summary> /// How many pages are there in the results. /// </summary> private int PageCount { get { return (total - 1) / maxResults; // floor } } /// <summary> /// First item of the last page /// </summary> private int LastPageStartsAt { get { return PageCount * maxResults; } } /// <summary> /// This should be replaced with a direct client-side get /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ButtonSearch_Click(object sender, System.EventArgs e) { this.Response.Redirect("Search.aspx?q=" + this.TextBoxQuery.Text); } } }
using System; using TDCOLib; namespace DCUnitTest { class MyDco : IDCO { int ICustomTMDco.Setup(string lpszDCOID) { throw new NotImplementedException(); } string IDCO.Options { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string ID { get; set; } public string Type { get; set; } public int Status { get; set; } public string BatchDir { get; set; } public int BatchPriority { get; set; } public string ImageName { get; set; } public string Text { get; set; } public string ConfidenceString { get; set; } public string get_Variable(string lpszName) { throw new NotImplementedException(); } public void set_Variable(string lpszName, string pVal) { throw new NotImplementedException(); } public int get_CharValue(int nIndex) { throw new NotImplementedException(); } public void set_CharValue(int nIndex, int pVal) { throw new NotImplementedException(); } public int get_CharConfidence(int nIndex) { throw new NotImplementedException(); } public void set_CharConfidence(int nIndex, int pVal) { throw new NotImplementedException(); } public string get_AltText(int nIndex) { throw new NotImplementedException(); } public void set_AltText(int nIndex, string pVal) { throw new NotImplementedException(); } public string get_AltConfidenceString(int nIndex) { throw new NotImplementedException(); } public void set_AltConfidenceString(int nIndex, string pVal) { throw new NotImplementedException(); } public int get_OMRValue(int nIndex) { throw new NotImplementedException(); } public void set_OMRValue(int nIndex, int pVal) { throw new NotImplementedException(); } public string XML { get; set; } public bool Clear() { throw new NotImplementedException(); } public bool CreateDocuments() { throw new NotImplementedException(); } public bool AddVariable(string strName, object newValue) { throw new NotImplementedException(); } public bool AddVariableFloat(string strName, double fValue) { throw new NotImplementedException(); } public bool AddVariableInt(string strName, int nValue) { throw new NotImplementedException(); } public bool AddVariableString(string strName, string strValue) { throw new NotImplementedException(); } public int CheckIntegrity(out object pLastChecked) { throw new NotImplementedException(); } public bool DeleteChild(int nIndex) { throw new NotImplementedException(); } public bool DeleteVariable(string lpszName) { throw new NotImplementedException(); } public DCO FindChild(string lpszName) { throw new NotImplementedException(); } public int FindChildIndex(string lpszName) { throw new NotImplementedException(); } public int FindVariable(string lpszName) { throw new NotImplementedException(); } public DCO GetChild(int nIndex) { throw new NotImplementedException(); } public DCO Parent() { throw new NotImplementedException(); } public bool GetPosition(out object pnLeft, out object pnTop, out object pnRight, out object pnBottom) { throw new NotImplementedException(); } public bool MoveChild(int nOldIndex, int nNewIndex) { throw new NotImplementedException(); } public int NumOfChildren() { throw new NotImplementedException(); } public int NumOfVars() { throw new NotImplementedException(); } public int ObjectType() { throw new NotImplementedException(); } public bool Read(string lpszFileName) { throw new NotImplementedException(); } public bool ReadSetup(string lpszFileName) { throw new NotImplementedException(); } public bool SetPosition(int nLeft, int nTop, int nRight, int nBottom) { throw new NotImplementedException(); } public DCOSetupNode SetupNode() { throw new NotImplementedException(); } public DCOSetup SetupObject() { throw new NotImplementedException(); } public bool Write(string lpszFileName) { throw new NotImplementedException(); } public bool WriteSetup(string lpszFileName) { throw new NotImplementedException(); } public DCO AddChild(int nType, string lpszID, int nIndex) { throw new NotImplementedException(); } public bool ShowSetupDialog(string lpszFileName) { throw new NotImplementedException(); } public bool IsValid() { throw new NotImplementedException(); } public string GetVariableName(int nIndex) { throw new NotImplementedException(); } public object GetVariableValue(int nIndex) { throw new NotImplementedException(); } public bool MoveIn(object pNewParent, int nIndex) { throw new NotImplementedException(); } public int AddValue(int nValue, int nConfidence) { throw new NotImplementedException(); } public bool DeleteValue(int nIndexValue) { throw new NotImplementedException(); } public bool IsError() { throw new NotImplementedException(); } public string GetLastError() { throw new NotImplementedException(); } public bool CreateFields() { throw new NotImplementedException(); } public object RunScript(string lpszFuncName, ref object pParams) { throw new NotImplementedException(); } public string GetRoute(bool bRuntime) { throw new NotImplementedException(); } public DCO FindRouteChild(string bszRoute) { throw new NotImplementedException(); } public bool IsRoute(string lpszRoute) { throw new NotImplementedException(); } int IDCO.Setup(string lpszDCOID) { throw new NotImplementedException(); } string ICustomTMDco.Options { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } }
using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent (typeof(Camera))] [AddComponentMenu ("Image Effects/Bloom and Glow/Bloom")] public class Bloom : PostEffectsBase { public enum LensFlareStyle { Ghosting = 0, Anamorphic = 1, Combined = 2, } public enum TweakMode { Basic = 0, Complex = 1, } public enum HDRBloomMode { Auto = 0, On = 1, Off = 2, } public enum BloomScreenBlendMode { Screen = 0, Add = 1, } public enum BloomQuality { Cheap = 0, High = 1, } public TweakMode tweakMode = 0; public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add; public HDRBloomMode hdr = HDRBloomMode.Auto; private bool doHdr = false; public float sepBlurSpread = 2.5f; public BloomQuality quality = BloomQuality.High; public float bloomIntensity = 0.5f; public float bloomThreshold = 0.5f; public Color bloomThresholdColor = Color.white; public int bloomBlurIterations = 2; public int hollywoodFlareBlurIterations = 2; public float flareRotation = 0.0f; public LensFlareStyle lensflareMode = (LensFlareStyle) 1; public float hollyStretchWidth = 2.5f; public float lensflareIntensity = 0.0f; public float lensflareThreshold = 0.3f; public float lensFlareSaturation = 0.75f; public Color flareColorA = new Color (0.4f, 0.4f, 0.8f, 0.75f); public Color flareColorB = new Color (0.4f, 0.8f, 0.8f, 0.75f); public Color flareColorC = new Color (0.8f, 0.4f, 0.8f, 0.75f); public Color flareColorD = new Color (0.8f, 0.4f, 0.0f, 0.75f); public Texture2D lensFlareVignetteMask; public Shader lensFlareShader; private Material lensFlareMaterial; public Shader screenBlendShader; private Material screenBlend; public Shader blurAndFlaresShader; private Material blurAndFlaresMaterial; public Shader brightPassFilterShader; private Material brightPassFilterMaterial; public override bool CheckResources () { CheckSupport (false); screenBlend = CheckShaderAndCreateMaterial (screenBlendShader, screenBlend); lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader,lensFlareMaterial); blurAndFlaresMaterial = CheckShaderAndCreateMaterial (blurAndFlaresShader, blurAndFlaresMaterial); brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial); if (!isSupported) ReportAutoDisable (); return isSupported; } public void OnRenderImage (RenderTexture source, RenderTexture destination) { if (CheckResources()==false) { Graphics.Blit (source, destination); return; } // screen blend is not supported when HDR is enabled (will cap values) doHdr = false; if (hdr == HDRBloomMode.Auto) doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr; else { doHdr = hdr == HDRBloomMode.On; } doHdr = doHdr && supportHDRTextures; BloomScreenBlendMode realBlendMode = screenBlendMode; if (doHdr) realBlendMode = BloomScreenBlendMode.Add; var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; var rtW2= source.width/2; var rtH2= source.height/2; var rtW4= source.width/4; var rtH4= source.height/4; float widthOverHeight = (1.0f * source.width) / (1.0f * source.height); float oneOverBaseSize = 1.0f / 512.0f; // downsample RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); if (quality > BloomQuality.Cheap) { Graphics.Blit (source, halfRezColorDown, screenBlend, 2); RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2); Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6); RenderTexture.ReleaseTemporary(rtDown4); } else { Graphics.Blit (source, halfRezColorDown); Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6); } RenderTexture.ReleaseTemporary (halfRezColorDown); // cut colors (thresholding) RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); BrightFilter (bloomThreshold * bloomThresholdColor, quarterRezColor, secondQuarterRezColor); // blurring if (bloomBlurIterations < 1) bloomBlurIterations = 1; else if (bloomBlurIterations > 10) bloomBlurIterations = 10; for (int iter = 0; iter < bloomBlurIterations; iter++) { float spreadForPass = (1.0f + (iter * 0.25f)) * sepBlurSpread; // vertical blur RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); RenderTexture.ReleaseTemporary(secondQuarterRezColor); secondQuarterRezColor = blur4; // horizontal blur blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); RenderTexture.ReleaseTemporary (secondQuarterRezColor); secondQuarterRezColor = blur4; if (quality > BloomQuality.Cheap) { if (iter == 0) { Graphics.SetRenderTarget(quarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (secondQuarterRezColor, quarterRezColor); } else { quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10); } } } if (quality > BloomQuality.Cheap) { Graphics.SetRenderTarget(secondQuarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6); } // lens flares: ghosting, anamorphic or both (ghosted anamorphic flares) if (lensflareIntensity > Mathf.Epsilon) { RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); if (lensflareMode == 0) { // ghosting only BrightFilter (lensflareThreshold, secondQuarterRezColor, rtFlares4); if (quality > BloomQuality.Cheap) { // smooth a little blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f)); Graphics.SetRenderTarget(quarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f)); Graphics.SetRenderTarget(rtFlares4); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); } // no ugly edges! Vignette (0.975f, rtFlares4, rtFlares4); BlendFlares (rtFlares4, secondQuarterRezColor); } else { //Vignette (0.975ff, rtFlares4, rtFlares4); //DrawBorder(rtFlares4, screenBlend, 8); float flareXRot = 1.0f * Mathf.Cos(flareRotation); float flareyRot = 1.0f * Mathf.Sin(flareRotation); float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize; blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f)); blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshold, 1.0f, 0.0f, 0.0f)); blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity); blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation); // "pre and cut" quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2); // "post" rtFlares4.DiscardContents(); Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f)); // stretch 1st blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth); quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); // stretch 2nd blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f); rtFlares4.DiscardContents(); Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1); // stretch 3rd blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f); quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); // additional blur passes for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++) { stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize; blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); rtFlares4.DiscardContents(); Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); } if (lensflareMode == (LensFlareStyle) 1) // anamorphic lens flares AddTo (1.0f, quarterRezColor, secondQuarterRezColor); else { // "combined" lens flares Vignette (1.0f, quarterRezColor, rtFlares4); BlendFlares (rtFlares4, quarterRezColor); AddTo (1.0f, quarterRezColor, secondQuarterRezColor); } } RenderTexture.ReleaseTemporary (rtFlares4); } int blendPass = (int) realBlendMode; //if (Mathf.Abs(chromaticBloom) < Mathf.Epsilon) // blendPass += 4; screenBlend.SetFloat ("_Intensity", bloomIntensity); screenBlend.SetTexture ("_ColorBuffer", source); if (quality > BloomQuality.Cheap) { RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); Graphics.Blit (secondQuarterRezColor, halfRezColorUp); Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPass); RenderTexture.ReleaseTemporary (halfRezColorUp); } else Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPass); RenderTexture.ReleaseTemporary (quarterRezColor); RenderTexture.ReleaseTemporary (secondQuarterRezColor); } private void AddTo (float intensity_, RenderTexture from, RenderTexture to) { screenBlend.SetFloat ("_Intensity", intensity_); to.MarkRestoreExpected(); // additive blending, RT restore expected Graphics.Blit (from, to, screenBlend, 9); } private void BlendFlares (RenderTexture from, RenderTexture to) { lensFlareMaterial.SetVector ("colorA", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity); lensFlareMaterial.SetVector ("colorB", new Vector4 (flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity); lensFlareMaterial.SetVector ("colorC", new Vector4 (flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity); lensFlareMaterial.SetVector ("colorD", new Vector4 (flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity); to.MarkRestoreExpected(); // additive blending, RT restore expected Graphics.Blit (from, to, lensFlareMaterial); } private void BrightFilter (float thresh, RenderTexture from, RenderTexture to) { brightPassFilterMaterial.SetVector ("_Threshhold", new Vector4 (thresh, thresh, thresh, thresh)); Graphics.Blit (from, to, brightPassFilterMaterial, 0); } private void BrightFilter (Color threshColor, RenderTexture from, RenderTexture to) { brightPassFilterMaterial.SetVector ("_Threshhold", threshColor); Graphics.Blit (from, to, brightPassFilterMaterial, 1); } private void Vignette (float amount, RenderTexture from, RenderTexture to) { if (lensFlareVignetteMask) { screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask); to.MarkRestoreExpected(); // using blending, RT restore expected Graphics.Blit (from == to ? null : from, to, screenBlend, from == to ? 7 : 3); } else if (from != to) { Graphics.SetRenderTarget (to); GL.Clear(false, true, Color.black); // clear destination to avoid RT restore Graphics.Blit (from, to); } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Ntfs { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Text; /// <summary> /// Class that checks NTFS file system integrity. /// </summary> /// <remarks>Poor relation of chkdsk/fsck.</remarks> public sealed class NtfsFileSystemChecker : DiscFileSystemChecker { private Stream _target; private NtfsContext _context; private TextWriter _report; private ReportLevels _reportLevels; private ReportLevels _levelsDetected; private ReportLevels _levelsConsideredFail = ReportLevels.Errors; /// <summary> /// Initializes a new instance of the NtfsFileSystemChecker class. /// </summary> /// <param name="diskData">The file system to check.</param> public NtfsFileSystemChecker(Stream diskData) { SnapshotStream protectiveStream = new SnapshotStream(diskData, Ownership.None); protectiveStream.Snapshot(); protectiveStream.Freeze(); _target = protectiveStream; } /// <summary> /// Checks the integrity of an NTFS file system held in a stream. /// </summary> /// <param name="reportOutput">A report on issues found.</param> /// <param name="levels">The amount of detail to report.</param> /// <returns><c>true</c> if the file system appears valid, else <c>false</c>.</returns> public override bool Check(TextWriter reportOutput, ReportLevels levels) { _context = new NtfsContext(); _context.RawStream = _target; _context.Options = new NtfsOptions(); _report = reportOutput; _reportLevels = levels; _levelsDetected = ReportLevels.None; try { DoCheck(); } catch (AbortException ae) { ReportError("File system check aborted: " + ae.ToString()); return false; } catch (Exception e) { ReportError("File system check aborted with exception: " + e.ToString()); return false; } return (_levelsDetected & _levelsConsideredFail) == 0; } /// <summary> /// Gets an object that can convert between clusters and files. /// </summary> /// <returns>The cluster map.</returns> public ClusterMap BuildClusterMap() { _context = new NtfsContext(); _context.RawStream = _target; _context.Options = new NtfsOptions(); _context.RawStream.Position = 0; byte[] bytes = Utilities.ReadFully(_context.RawStream, 512); _context.BiosParameterBlock = BiosParameterBlock.FromBytes(bytes, 0); _context.Mft = new MasterFileTable(_context); File mftFile = new File(_context, _context.Mft.GetBootstrapRecord()); _context.Mft.Initialize(mftFile); return _context.Mft.GetClusterMap(); } private static void Abort() { throw new AbortException(); } private void DoCheck() { _context.RawStream.Position = 0; byte[] bytes = Utilities.ReadFully(_context.RawStream, 512); _context.BiosParameterBlock = BiosParameterBlock.FromBytes(bytes, 0); //----------------------------------------------------------------------- // MASTER FILE TABLE // // Bootstrap the Master File Table _context.Mft = new MasterFileTable(_context); File mftFile = new File(_context, _context.Mft.GetBootstrapRecord()); // Verify basic MFT records before initializing the Master File Table PreVerifyMft(mftFile); _context.Mft.Initialize(mftFile); // Now the MFT is up and running, do more detailed analysis of it's contents - double-accounted clusters, etc VerifyMft(); _context.Mft.Dump(_report, "INFO: "); //----------------------------------------------------------------------- // INDEXES // // Need UpperCase in order to verify some indexes (i.e. directories). File ucFile = new File(_context, _context.Mft.GetRecord(MasterFileTable.UpCaseIndex, false)); _context.UpperCase = new UpperCase(ucFile); SelfCheckIndexes(); //----------------------------------------------------------------------- // DIRECTORIES // VerifyDirectories(); //----------------------------------------------------------------------- // WELL KNOWN FILES // VerifyWellKnownFilesExist(); //----------------------------------------------------------------------- // OBJECT IDS // VerifyObjectIds(); //----------------------------------------------------------------------- // FINISHED // // Temporary... using (NtfsFileSystem fs = new NtfsFileSystem(_context.RawStream)) { if ((_reportLevels & ReportLevels.Information) != 0) { ReportDump(fs); } } } private void VerifyWellKnownFilesExist() { Directory rootDir = new Directory(_context, _context.Mft.GetRecord(MasterFileTable.RootDirIndex, false)); DirectoryEntry extendDirEntry = rootDir.GetEntryByName("$Extend"); if (extendDirEntry == null) { ReportError("$Extend does not exist in root directory"); Abort(); } Directory extendDir = new Directory(_context, _context.Mft.GetRecord(extendDirEntry.Reference)); DirectoryEntry objIdDirEntry = extendDir.GetEntryByName("$ObjId"); if (objIdDirEntry == null) { ReportError("$ObjId does not exist in $Extend directory"); Abort(); } // Stash ObjectIds _context.ObjectIds = new ObjectIds(new File(_context, _context.Mft.GetRecord(objIdDirEntry.Reference))); DirectoryEntry sysVolInfDirEntry = rootDir.GetEntryByName("System Volume Information"); if (sysVolInfDirEntry == null) { ReportError("'System Volume Information' does not exist in root directory"); Abort(); } ////Directory sysVolInfDir = new Directory(_context, _context.Mft.GetRecord(sysVolInfDirEntry.Reference)); } private void VerifyObjectIds() { foreach (FileRecord fr in _context.Mft.Records) { if (fr.BaseFile.Value != 0) { File f = new File(_context, fr); foreach (var stream in f.AllStreams) { if (stream.AttributeType == AttributeType.ObjectId) { ObjectId objId = stream.GetContent<ObjectId>(); ObjectIdRecord objIdRec; if (!_context.ObjectIds.TryGetValue(objId.Id, out objIdRec)) { ReportError("ObjectId {0} for file {1} is not indexed", objId.Id, f.BestName); } else if (objIdRec.MftReference != f.MftReference) { ReportError("ObjectId {0} for file {1} points to {2}", objId.Id, f.BestName, objIdRec.MftReference); } } } } } foreach (var objIdRec in _context.ObjectIds.All) { if (_context.Mft.GetRecord(objIdRec.Value.MftReference) == null) { ReportError("ObjectId {0} refers to non-existant file {1}", objIdRec.Key, objIdRec.Value.MftReference); } } } private void VerifyDirectories() { foreach (FileRecord fr in _context.Mft.Records) { if (fr.BaseFile.Value != 0) { continue; } File f = new File(_context, fr); foreach (var stream in f.AllStreams) { if (stream.AttributeType == AttributeType.IndexRoot && stream.Name == "$I30") { IndexView<FileNameRecord, FileRecordReference> dir = new IndexView<FileNameRecord, FileRecordReference>(f.GetIndex("$I30")); foreach (var entry in dir.Entries) { FileRecord refFile = _context.Mft.GetRecord(entry.Value); // Make sure each referenced file actually exists... if (refFile == null) { ReportError("Directory {0} references non-existent file {1}", f, entry.Key); } File referencedFile = new File(_context, refFile); StandardInformation si = referencedFile.StandardInformation; if (si.CreationTime != entry.Key.CreationTime || si.MftChangedTime != entry.Key.MftChangedTime || si.ModificationTime != entry.Key.ModificationTime) { ReportInfo("Directory entry {0} in {1} is out of date", entry.Key, f); } } } } } } private void SelfCheckIndexes() { foreach (FileRecord fr in _context.Mft.Records) { File f = new File(_context, fr); foreach (var stream in f.AllStreams) { if (stream.AttributeType == AttributeType.IndexRoot) { SelfCheckIndex(f, stream.Name); } } } } private void SelfCheckIndex(File file, string name) { ReportInfo("About to self-check index {0} in file {1} (MFT:{2})", name, file.BestName, file.IndexInMft); IndexRoot root = file.GetStream(AttributeType.IndexRoot, name).GetContent<IndexRoot>(); byte[] rootBuffer; using (Stream s = file.OpenStream(AttributeType.IndexRoot, name, FileAccess.Read)) { rootBuffer = Utilities.ReadFully(s, (int)s.Length); } Bitmap indexBitmap = null; if (file.GetStream(AttributeType.Bitmap, name) != null) { indexBitmap = new Bitmap(file.OpenStream(AttributeType.Bitmap, name, FileAccess.Read), long.MaxValue); } if (!SelfCheckIndexNode(rootBuffer, IndexRoot.HeaderOffset, indexBitmap, root, file.BestName, name)) { ReportError("Index {0} in file {1} (MFT:{2}) has corrupt IndexRoot attribute", name, file.BestName, file.IndexInMft); } else { ReportInfo("Self-check of index {0} in file {1} (MFT:{2}) complete", name, file.BestName, file.IndexInMft); } } private bool SelfCheckIndexNode(byte[] buffer, int offset, Bitmap bitmap, IndexRoot root, string fileName, string indexName) { bool ok = true; IndexHeader header = new IndexHeader(buffer, offset); IndexEntry lastEntry = null; IComparer<byte[]> collator = root.GetCollator(_context.UpperCase); int pos = (int)header.OffsetToFirstEntry; while (pos < header.TotalSizeOfEntries) { IndexEntry entry = new IndexEntry(indexName == "$I30"); entry.Read(buffer, offset + pos); pos += entry.Size; if ((entry.Flags & IndexEntryFlags.Node) != 0) { long bitmapIdx = entry.ChildrenVirtualCluster / Utilities.Ceil(root.IndexAllocationSize, _context.BiosParameterBlock.SectorsPerCluster * _context.BiosParameterBlock.BytesPerSector); if (!bitmap.IsPresent(bitmapIdx)) { ReportError("Index entry {0} is non-leaf, but child vcn {1} is not in bitmap at index {2}", Index.EntryAsString(entry, fileName, indexName), entry.ChildrenVirtualCluster, bitmapIdx); } } if ((entry.Flags & IndexEntryFlags.End) != 0) { if (pos != header.TotalSizeOfEntries) { ReportError("Found END index entry {0}, but not at end of node", Index.EntryAsString(entry, fileName, indexName)); ok = false; } } if (lastEntry != null && collator.Compare(lastEntry.KeyBuffer, entry.KeyBuffer) >= 0) { ReportError("Found entries out of order {0} was before {1}", Index.EntryAsString(lastEntry, fileName, indexName), Index.EntryAsString(entry, fileName, indexName)); ok = false; } lastEntry = entry; } return ok; } private void PreVerifyMft(File file) { int recordLength = _context.BiosParameterBlock.MftRecordSize; int bytesPerSector = _context.BiosParameterBlock.BytesPerSector; // Check out the MFT's clusters foreach (var range in file.GetAttribute(AttributeType.Data, null).GetClusters()) { if (!VerifyClusterRange(range)) { ReportError("Corrupt cluster range in MFT data attribute {0}", range.ToString()); Abort(); } } foreach (var range in file.GetAttribute(AttributeType.Bitmap, null).GetClusters()) { if (!VerifyClusterRange(range)) { ReportError("Corrupt cluster range in MFT bitmap attribute {0}", range.ToString()); Abort(); } } using (Stream mftStream = file.OpenStream(AttributeType.Data, null, FileAccess.Read)) using (Stream bitmapStream = file.OpenStream(AttributeType.Bitmap, null, FileAccess.Read)) { Bitmap bitmap = new Bitmap(bitmapStream, long.MaxValue); long index = 0; while (mftStream.Position < mftStream.Length) { byte[] recordData = Utilities.ReadFully(mftStream, recordLength); string magic = Utilities.BytesToString(recordData, 0, 4); if (magic != "FILE") { if (bitmap.IsPresent(index)) { ReportError("Invalid MFT record magic at index {0} - was ({2},{3},{4},{5}) \"{1}\"", index, magic.Trim('\0'), (int)magic[0], (int)magic[1], (int)magic[2], (int)magic[3]); } } else { if (!VerifyMftRecord(recordData, bitmap.IsPresent(index), bytesPerSector)) { ReportError("Invalid MFT record at index {0}", index); StringBuilder bldr = new StringBuilder(); for (int i = 0; i < recordData.Length; ++i) { bldr.Append(string.Format(CultureInfo.InvariantCulture, " {0:X2}", recordData[i])); } ReportInfo("MFT record binary data for index {0}:{1}", index, bldr.ToString()); } } index++; } } } private void VerifyMft() { // Cluster allocation check - check for double allocations Dictionary<long, string> clusterMap = new Dictionary<long, string>(); foreach (FileRecord fr in _context.Mft.Records) { if ((fr.Flags & FileRecordFlags.InUse) != 0) { File f = new File(_context, fr); foreach (NtfsAttribute attr in f.AllAttributes) { string attrKey = fr.MasterFileTableIndex + ":" + attr.Id; foreach (var range in attr.GetClusters()) { if (!VerifyClusterRange(range)) { ReportError("Attribute {0} contains bad cluster range {1}", attrKey, range); } for (long cluster = range.Offset; cluster < range.Offset + range.Count; ++cluster) { string existingKey; if (clusterMap.TryGetValue(cluster, out existingKey)) { ReportError("Two attributes referencing cluster {0} (0x{0:X16}) - {1} and {2} (as MftIndex:AttrId)", cluster, existingKey, attrKey); } } } } } } } private bool VerifyMftRecord(byte[] recordData, bool presentInBitmap, int bytesPerSector) { bool ok = true; // // Verify the attributes seem OK... // byte[] tempBuffer = new byte[recordData.Length]; Array.Copy(recordData, tempBuffer, tempBuffer.Length); GenericFixupRecord genericRecord = new GenericFixupRecord(bytesPerSector); genericRecord.FromBytes(tempBuffer, 0); int pos = Utilities.ToUInt16LittleEndian(genericRecord.Content, 0x14); while (Utilities.ToUInt32LittleEndian(genericRecord.Content, pos) != 0xFFFFFFFF) { int attrLen; try { AttributeRecord ar = AttributeRecord.FromBytes(genericRecord.Content, pos, out attrLen); if (attrLen != ar.Size) { ReportError("Attribute size is different to calculated size. AttrId={0}", ar.AttributeId); ok = false; } if (ar.IsNonResident) { NonResidentAttributeRecord nrr = (NonResidentAttributeRecord)ar; if (nrr.DataRuns.Count > 0) { long totalVcn = 0; foreach (var run in nrr.DataRuns) { totalVcn += run.RunLength; } if (totalVcn != nrr.LastVcn - nrr.StartVcn + 1) { ReportError("Declared VCNs doesn't match data runs. AttrId={0}", ar.AttributeId); ok = false; } } } } catch { ReportError("Failure parsing attribute at pos={0}", pos); return false; } pos += attrLen; } // // Now consider record as a whole // FileRecord record = new FileRecord(bytesPerSector); record.FromBytes(recordData, 0); bool inUse = (record.Flags & FileRecordFlags.InUse) != 0; if (inUse != presentInBitmap) { ReportError("MFT bitmap and record in-use flag don't agree. Mft={0}, Record={1}", presentInBitmap ? "InUse" : "Free", inUse ? "InUse" : "Free"); ok = false; } if (record.Size != record.RealSize) { ReportError("MFT record real size is different to calculated size. Stored in MFT={0}, Calculated={1}", record.RealSize, record.Size); ok = false; } if (Utilities.ToUInt32LittleEndian(recordData, (int)record.RealSize - 8) != uint.MaxValue) { ReportError("MFT record is not correctly terminated with 0xFFFFFFFF"); ok = false; } return ok; } private bool VerifyClusterRange(Range<long, long> range) { bool ok = true; if (range.Offset < 0) { ReportError("Invalid cluster range {0} - negative start", range); ok = false; } if (range.Count <= 0) { ReportError("Invalid cluster range {0} - negative/zero count", range); ok = false; } if ((range.Offset + range.Count) * _context.BiosParameterBlock.BytesPerCluster > _context.RawStream.Length) { ReportError("Invalid cluster range {0} - beyond end of disk", range); ok = false; } return ok; } private void ReportDump(IDiagnosticTraceable toDump) { _levelsDetected |= ReportLevels.Information; if ((_reportLevels & ReportLevels.Information) != 0) { toDump.Dump(_report, "INFO: "); } } private void ReportInfo(string str, params object[] args) { _levelsDetected |= ReportLevels.Information; if ((_reportLevels & ReportLevels.Information) != 0) { _report.WriteLine("INFO: " + str, args); } } private void ReportError(string str, params object[] args) { _levelsDetected |= ReportLevels.Errors; if ((_reportLevels & ReportLevels.Errors) != 0) { _report.WriteLine("ERROR: " + str, args); } } [Serializable] private sealed class AbortException : InvalidFileSystemException { public AbortException() : base() { } private AbortException(SerializationInfo info, StreamingContext ctxt) : base(info, ctxt) { } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Drawing; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Reflection; using System.Xml; using System.IO; namespace fyiReporting.RdlDesign { /// <summary> /// Summary description for DialogAbout. /// </summary> public class DialogToolOptions : System.Windows.Forms.Form { RdlDesigner _RdlDesigner; bool bDesktop=false; bool bToolbar=false; bool bMaps = false; // Desktop server configuration XmlDocument _DesktopDocument; XmlNode _DesktopPort; XmlNode _DesktopDirectory; XmlNode _DesktopLocal; private System.Windows.Forms.Button bOK; private System.Windows.Forms.Button bCancel; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tpGeneral; private System.Windows.Forms.TabPage tpToolbar; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tbRecentFilesMax; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox tbHelpUrl; private System.Windows.Forms.ListBox lbOperation; private System.Windows.Forms.ListBox lbToolbar; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Button bCopyItem; private System.Windows.Forms.Button bUp; private System.Windows.Forms.Button bDown; private System.Windows.Forms.Button bReset; private System.Windows.Forms.Button bRemove; private System.Windows.Forms.Button bApply; private System.Windows.Forms.TabPage tpDesktop; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox tbPort; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox tbDirectory; private System.Windows.Forms.CheckBox ckLocal; private System.Windows.Forms.Button bBrowse; private CheckBox cbEditLines; private CheckBox cbOutline; private CheckBox cbTabInterface; private GroupBox gbPropLoc; private RadioButton rbPBBottom; private RadioButton rbPBTop; private RadioButton rbPBLeft; private RadioButton rbPBRight; private CheckBox chkPBAutoHide; private TabPage tabPage1; private Button bRemoveMap; private Button bAddMap; private ListBox lbMaps; private Label label10; private CheckBox cbShowReportWaitDialog; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public DialogToolOptions(RdlDesigner rdl) { _RdlDesigner = rdl; // // Required for Windows Form Designer support // InitializeComponent(); Init(); return; } private void Init() { this.tbRecentFilesMax.Text = _RdlDesigner.RecentFilesMax.ToString(); this.tbHelpUrl.Text = _RdlDesigner.HelpUrl; // init the toolbar // list of items in current toolbar foreach (string ti in _RdlDesigner.Toolbar) { this.lbToolbar.Items.Add(ti); } this.cbEditLines.Checked = _RdlDesigner.ShowEditLines; this.cbOutline.Checked = _RdlDesigner.ShowReportItemOutline; this.cbTabInterface.Checked = _RdlDesigner.ShowTabbedInterface; chkPBAutoHide.Checked = _RdlDesigner.PropertiesAutoHide; this.cbShowReportWaitDialog.Checked = _RdlDesigner.ShowPreviewWaitDialog; switch (_RdlDesigner.PropertiesLocation) { case DockStyle.Top: this.rbPBTop.Checked = true; break; case DockStyle.Bottom: this.rbPBBottom.Checked = true; break; case DockStyle.Right: this.rbPBRight.Checked = true; break; case DockStyle.Left: default: this.rbPBLeft.Checked = true; break; } InitOperations(); InitDesktop(); InitMaps(); bDesktop = bToolbar = bMaps = false; // start with no changes } private void InitDesktop() { string optFileName = AppDomain.CurrentDomain.BaseDirectory + "config.xml"; try { XmlDocument xDoc = _DesktopDocument = new XmlDocument(); xDoc.PreserveWhitespace = true; xDoc.Load(optFileName); XmlNode xNode; xNode = xDoc.SelectSingleNode("//config"); // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name.ToLower()) { case "port": this.tbPort.Text = xNodeLoop.InnerText; _DesktopPort = xNodeLoop; break; case "localhostonly": string tf = xNodeLoop.InnerText.ToLower(); this.ckLocal.Checked = !(tf == "false"); _DesktopLocal = xNodeLoop; break; case "serverroot": this.tbDirectory.Text = xNodeLoop.InnerText; _DesktopDirectory = xNodeLoop; break; case "cachedirectory": // wd = xNodeLoop.InnerText; break; case "tracelevel": break; case "maxreadcache": break; case "maxreadcacheentrysize": break; case "mimetypes": break; default: break; } } } catch (Exception ex) { // Didn't sucessfully get the startup state: use defaults MessageBox.Show(string.Format("Error processing Desktop Configuration; using defaults.\n{0}", ex.Message), "Options"); this.tbPort.Text = "8080"; this.ckLocal.Checked = true; this.tbDirectory.Text = "Examples"; } } private void InitMaps() { lbMaps.Items.Clear(); lbMaps.Items.AddRange(RdlDesigner.MapSubtypes); } private void InitOperations() { // list of operations; lbOperation.Items.Clear(); List<string> dups = _RdlDesigner.ToolbarAllowDups; foreach (string ti in _RdlDesigner.ToolbarOperations) { // if item is allowed to be duplicated or if // item has not already been used we add to operation list if (dups.Contains(ti) || !lbToolbar.Items.Contains(ti)) this.lbOperation.Items.Add(ti); } } /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DialogToolOptions)); this.bOK = new System.Windows.Forms.Button(); this.bCancel = new System.Windows.Forms.Button(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tpGeneral = new System.Windows.Forms.TabPage(); this.gbPropLoc = new System.Windows.Forms.GroupBox(); this.chkPBAutoHide = new System.Windows.Forms.CheckBox(); this.rbPBBottom = new System.Windows.Forms.RadioButton(); this.rbPBTop = new System.Windows.Forms.RadioButton(); this.rbPBLeft = new System.Windows.Forms.RadioButton(); this.rbPBRight = new System.Windows.Forms.RadioButton(); this.cbTabInterface = new System.Windows.Forms.CheckBox(); this.cbOutline = new System.Windows.Forms.CheckBox(); this.cbEditLines = new System.Windows.Forms.CheckBox(); this.tbHelpUrl = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.tbRecentFilesMax = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.tpToolbar = new System.Windows.Forms.TabPage(); this.bRemove = new System.Windows.Forms.Button(); this.bReset = new System.Windows.Forms.Button(); this.bDown = new System.Windows.Forms.Button(); this.bUp = new System.Windows.Forms.Button(); this.bCopyItem = new System.Windows.Forms.Button(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.lbToolbar = new System.Windows.Forms.ListBox(); this.lbOperation = new System.Windows.Forms.ListBox(); this.tpDesktop = new System.Windows.Forms.TabPage(); this.bBrowse = new System.Windows.Forms.Button(); this.tbDirectory = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.ckLocal = new System.Windows.Forms.CheckBox(); this.tbPort = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.label10 = new System.Windows.Forms.Label(); this.bRemoveMap = new System.Windows.Forms.Button(); this.bAddMap = new System.Windows.Forms.Button(); this.lbMaps = new System.Windows.Forms.ListBox(); this.bApply = new System.Windows.Forms.Button(); this.cbShowReportWaitDialog = new System.Windows.Forms.CheckBox(); this.tabControl1.SuspendLayout(); this.tpGeneral.SuspendLayout(); this.gbPropLoc.SuspendLayout(); this.tpToolbar.SuspendLayout(); this.tpDesktop.SuspendLayout(); this.tabPage1.SuspendLayout(); this.SuspendLayout(); // // bOK // this.bOK.Location = new System.Drawing.Point(210, 275); this.bOK.Name = "bOK"; this.bOK.Size = new System.Drawing.Size(75, 23); this.bOK.TabIndex = 1; this.bOK.Text = "OK"; this.bOK.Click += new System.EventHandler(this.bOK_Click); // // bCancel // this.bCancel.CausesValidation = false; this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.Location = new System.Drawing.Point(298, 275); this.bCancel.Name = "bCancel"; this.bCancel.Size = new System.Drawing.Size(75, 23); this.bCancel.TabIndex = 2; this.bCancel.Text = "Cancel"; // // tabControl1 // this.tabControl1.Controls.Add(this.tpGeneral); this.tabControl1.Controls.Add(this.tpToolbar); this.tabControl1.Controls.Add(this.tpDesktop); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Location = new System.Drawing.Point(3, 3); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(466, 269); this.tabControl1.TabIndex = 0; // // tpGeneral // this.tpGeneral.Controls.Add(this.cbShowReportWaitDialog); this.tpGeneral.Controls.Add(this.gbPropLoc); this.tpGeneral.Controls.Add(this.cbTabInterface); this.tpGeneral.Controls.Add(this.cbOutline); this.tpGeneral.Controls.Add(this.cbEditLines); this.tpGeneral.Controls.Add(this.tbHelpUrl); this.tpGeneral.Controls.Add(this.label3); this.tpGeneral.Controls.Add(this.label2); this.tpGeneral.Controls.Add(this.tbRecentFilesMax); this.tpGeneral.Controls.Add(this.label1); this.tpGeneral.Location = new System.Drawing.Point(4, 22); this.tpGeneral.Name = "tpGeneral"; this.tpGeneral.Size = new System.Drawing.Size(458, 243); this.tpGeneral.TabIndex = 0; this.tpGeneral.Tag = "general"; this.tpGeneral.Text = "General"; // // gbPropLoc // this.gbPropLoc.Controls.Add(this.chkPBAutoHide); this.gbPropLoc.Controls.Add(this.rbPBBottom); this.gbPropLoc.Controls.Add(this.rbPBTop); this.gbPropLoc.Controls.Add(this.rbPBLeft); this.gbPropLoc.Controls.Add(this.rbPBRight); this.gbPropLoc.Location = new System.Drawing.Point(14, 174); this.gbPropLoc.Name = "gbPropLoc"; this.gbPropLoc.Size = new System.Drawing.Size(401, 61); this.gbPropLoc.TabIndex = 9; this.gbPropLoc.TabStop = false; this.gbPropLoc.Text = "Properties Window"; // // chkPBAutoHide // this.chkPBAutoHide.AutoSize = true; this.chkPBAutoHide.Location = new System.Drawing.Point(13, 42); this.chkPBAutoHide.Name = "chkPBAutoHide"; this.chkPBAutoHide.Size = new System.Drawing.Size(73, 17); this.chkPBAutoHide.TabIndex = 4; this.chkPBAutoHide.Text = "Auto Hide"; this.chkPBAutoHide.UseVisualStyleBackColor = true; // // rbPBBottom // this.rbPBBottom.AutoSize = true; this.rbPBBottom.Location = new System.Drawing.Point(301, 19); this.rbPBBottom.Name = "rbPBBottom"; this.rbPBBottom.Size = new System.Drawing.Size(58, 17); this.rbPBBottom.TabIndex = 3; this.rbPBBottom.TabStop = true; this.rbPBBottom.Text = "Bottom"; this.rbPBBottom.UseVisualStyleBackColor = true; // // rbPBTop // this.rbPBTop.AutoSize = true; this.rbPBTop.Location = new System.Drawing.Point(205, 19); this.rbPBTop.Name = "rbPBTop"; this.rbPBTop.Size = new System.Drawing.Size(44, 17); this.rbPBTop.TabIndex = 2; this.rbPBTop.TabStop = true; this.rbPBTop.Text = "Top"; this.rbPBTop.UseVisualStyleBackColor = true; // // rbPBLeft // this.rbPBLeft.AutoSize = true; this.rbPBLeft.Location = new System.Drawing.Point(109, 19); this.rbPBLeft.Name = "rbPBLeft"; this.rbPBLeft.Size = new System.Drawing.Size(43, 17); this.rbPBLeft.TabIndex = 1; this.rbPBLeft.TabStop = true; this.rbPBLeft.Text = "Left"; this.rbPBLeft.UseVisualStyleBackColor = true; // // rbPBRight // this.rbPBRight.AutoSize = true; this.rbPBRight.Location = new System.Drawing.Point(13, 19); this.rbPBRight.Name = "rbPBRight"; this.rbPBRight.Size = new System.Drawing.Size(50, 17); this.rbPBRight.TabIndex = 0; this.rbPBRight.TabStop = true; this.rbPBRight.Text = "Right"; this.rbPBRight.UseVisualStyleBackColor = true; // // cbTabInterface // this.cbTabInterface.AutoSize = true; this.cbTabInterface.Location = new System.Drawing.Point(14, 132); this.cbTabInterface.Name = "cbTabInterface"; this.cbTabInterface.Size = new System.Drawing.Size(133, 17); this.cbTabInterface.TabIndex = 7; this.cbTabInterface.Text = "Show tabbed interface"; this.cbTabInterface.UseVisualStyleBackColor = true; this.cbTabInterface.CheckedChanged += new System.EventHandler(this.cbTabInterface_CheckedChanged); // // cbOutline // this.cbOutline.AutoSize = true; this.cbOutline.Location = new System.Drawing.Point(14, 109); this.cbOutline.Name = "cbOutline"; this.cbOutline.Size = new System.Drawing.Size(172, 17); this.cbOutline.TabIndex = 6; this.cbOutline.Text = "Outline report items in Designer"; this.cbOutline.UseVisualStyleBackColor = true; // // cbEditLines // this.cbEditLines.AutoSize = true; this.cbEditLines.Location = new System.Drawing.Point(14, 86); this.cbEditLines.Name = "cbEditLines"; this.cbEditLines.Size = new System.Drawing.Size(175, 17); this.cbEditLines.TabIndex = 5; this.cbEditLines.Text = "Show line numbers in RDL Text"; this.cbEditLines.UseVisualStyleBackColor = true; // // tbHelpUrl // this.tbHelpUrl.Location = new System.Drawing.Point(27, 60); this.tbHelpUrl.Name = "tbHelpUrl"; this.tbHelpUrl.Size = new System.Drawing.Size(404, 20); this.tbHelpUrl.TabIndex = 4; this.tbHelpUrl.Text = "tbHelpUrl"; // // label3 // this.label3.Location = new System.Drawing.Point(11, 40); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(404, 23); this.label3.TabIndex = 3; this.label3.Text = "Help System URL (Empty string means use default help url.)"; // // label2 // this.label2.Location = new System.Drawing.Point(100, 15); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(174, 23); this.label2.TabIndex = 2; this.label2.Text = "items in most recently used lists."; // // tbRecentFilesMax // this.tbRecentFilesMax.Location = new System.Drawing.Point(58, 11); this.tbRecentFilesMax.Name = "tbRecentFilesMax"; this.tbRecentFilesMax.Size = new System.Drawing.Size(31, 20); this.tbRecentFilesMax.TabIndex = 1; // // label1 // this.label1.Location = new System.Drawing.Point(11, 13); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(45, 23); this.label1.TabIndex = 0; this.label1.Text = "Display"; // // tpToolbar // this.tpToolbar.Controls.Add(this.bRemove); this.tpToolbar.Controls.Add(this.bReset); this.tpToolbar.Controls.Add(this.bDown); this.tpToolbar.Controls.Add(this.bUp); this.tpToolbar.Controls.Add(this.bCopyItem); this.tpToolbar.Controls.Add(this.label5); this.tpToolbar.Controls.Add(this.label4); this.tpToolbar.Controls.Add(this.lbToolbar); this.tpToolbar.Controls.Add(this.lbOperation); this.tpToolbar.Location = new System.Drawing.Point(4, 22); this.tpToolbar.Name = "tpToolbar"; this.tpToolbar.Size = new System.Drawing.Size(458, 243); this.tpToolbar.TabIndex = 1; this.tpToolbar.Tag = "toolbar"; this.tpToolbar.Text = "Toolbar"; // // bRemove // this.bRemove.Location = new System.Drawing.Point(179, 74); this.bRemove.Name = "bRemove"; this.bRemove.Size = new System.Drawing.Size(23, 23); this.bRemove.TabIndex = 2; this.bRemove.Text = "<"; this.bRemove.Click += new System.EventHandler(this.bRemove_Click); // // bReset // this.bReset.Location = new System.Drawing.Point(374, 104); this.bReset.Name = "bReset"; this.bReset.Size = new System.Drawing.Size(53, 23); this.bReset.TabIndex = 6; this.bReset.Text = "Reset"; this.bReset.Click += new System.EventHandler(this.bReset_Click); // // bDown // this.bDown.Location = new System.Drawing.Point(374, 65); this.bDown.Name = "bDown"; this.bDown.Size = new System.Drawing.Size(53, 23); this.bDown.TabIndex = 5; this.bDown.Text = "Down"; this.bDown.Click += new System.EventHandler(this.bDown_Click); // // bUp // this.bUp.Location = new System.Drawing.Point(374, 35); this.bUp.Name = "bUp"; this.bUp.Size = new System.Drawing.Size(53, 23); this.bUp.TabIndex = 4; this.bUp.Text = "Up"; this.bUp.Click += new System.EventHandler(this.bUp_Click); // // bCopyItem // this.bCopyItem.Location = new System.Drawing.Point(179, 40); this.bCopyItem.Name = "bCopyItem"; this.bCopyItem.Size = new System.Drawing.Size(23, 23); this.bCopyItem.TabIndex = 1; this.bCopyItem.Text = ">"; this.bCopyItem.Click += new System.EventHandler(this.bCopyItem_Click); // // label5 // this.label5.Location = new System.Drawing.Point(213, 8); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(100, 23); this.label5.TabIndex = 8; this.label5.Text = "Toolbar Layout"; // // label4 // this.label4.Location = new System.Drawing.Point(15, 8); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(112, 23); this.label4.TabIndex = 7; this.label4.Text = "ToolBar Operations"; // // lbToolbar // this.lbToolbar.Location = new System.Drawing.Point(213, 33); this.lbToolbar.Name = "lbToolbar"; this.lbToolbar.Size = new System.Drawing.Size(152, 199); this.lbToolbar.TabIndex = 3; // // lbOperation // this.lbOperation.Location = new System.Drawing.Point(14, 33); this.lbOperation.Name = "lbOperation"; this.lbOperation.Size = new System.Drawing.Size(152, 199); this.lbOperation.TabIndex = 0; // // tpDesktop // this.tpDesktop.Controls.Add(this.bBrowse); this.tpDesktop.Controls.Add(this.tbDirectory); this.tpDesktop.Controls.Add(this.label9); this.tpDesktop.Controls.Add(this.label8); this.tpDesktop.Controls.Add(this.label7); this.tpDesktop.Controls.Add(this.ckLocal); this.tpDesktop.Controls.Add(this.tbPort); this.tpDesktop.Controls.Add(this.label6); this.tpDesktop.Location = new System.Drawing.Point(4, 22); this.tpDesktop.Name = "tpDesktop"; this.tpDesktop.Size = new System.Drawing.Size(458, 243); this.tpDesktop.TabIndex = 2; this.tpDesktop.Tag = "desktop"; this.tpDesktop.Text = "Desktop Server"; // // bBrowse // this.bBrowse.Location = new System.Drawing.Point(411, 102); this.bBrowse.Name = "bBrowse"; this.bBrowse.Size = new System.Drawing.Size(26, 19); this.bBrowse.TabIndex = 2; this.bBrowse.Text = "..."; this.bBrowse.Click += new System.EventHandler(this.bBrowse_Click); // // tbDirectory // this.tbDirectory.Location = new System.Drawing.Point(68, 100); this.tbDirectory.Name = "tbDirectory"; this.tbDirectory.Size = new System.Drawing.Size(334, 20); this.tbDirectory.TabIndex = 1; this.tbDirectory.Text = "textBox1"; this.tbDirectory.TextChanged += new System.EventHandler(this.Desktop_Changed); // // label9 // this.label9.Location = new System.Drawing.Point(13, 101); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(56, 23); this.label9.TabIndex = 5; this.label9.Text = "Directory:"; // // label8 // this.label8.Location = new System.Drawing.Point(33, 156); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(414, 26); this.label8.TabIndex = 4; this.label8.Text = "Important: Desktop server is not intended to be used as a production web server. " + " Use an ASP enabled server for anything other than local desktop use."; // // label7 // this.label7.Location = new System.Drawing.Point(10, 6); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(435, 57); this.label7.TabIndex = 3; this.label7.Text = resources.GetString("label7.Text"); // // ckLocal // this.ckLocal.Location = new System.Drawing.Point(15, 131); this.ckLocal.Name = "ckLocal"; this.ckLocal.Size = new System.Drawing.Size(190, 24); this.ckLocal.TabIndex = 3; this.ckLocal.Text = "Restrict access to local machine"; this.ckLocal.CheckedChanged += new System.EventHandler(this.Desktop_Changed); // // tbPort // this.tbPort.Location = new System.Drawing.Point(44, 66); this.tbPort.Name = "tbPort"; this.tbPort.Size = new System.Drawing.Size(50, 20); this.tbPort.TabIndex = 0; this.tbPort.TextChanged += new System.EventHandler(this.Desktop_Changed); // // label6 // this.label6.Location = new System.Drawing.Point(10, 68); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(33, 23); this.label6.TabIndex = 0; this.label6.Text = "Port"; // // tabPage1 // this.tabPage1.Controls.Add(this.label10); this.tabPage1.Controls.Add(this.bRemoveMap); this.tabPage1.Controls.Add(this.bAddMap); this.tabPage1.Controls.Add(this.lbMaps); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(458, 243); this.tabPage1.TabIndex = 3; this.tabPage1.Text = "Maps"; this.tabPage1.UseVisualStyleBackColor = true; // // label10 // this.label10.Location = new System.Drawing.Point(12, 15); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(435, 62); this.label10.TabIndex = 3; this.label10.Text = resources.GetString("label10.Text"); // // bRemoveMap // this.bRemoveMap.Location = new System.Drawing.Point(226, 110); this.bRemoveMap.Name = "bRemoveMap"; this.bRemoveMap.Size = new System.Drawing.Size(75, 23); this.bRemoveMap.TabIndex = 2; this.bRemoveMap.Text = "Remove"; this.bRemoveMap.UseVisualStyleBackColor = true; this.bRemoveMap.Click += new System.EventHandler(this.bRemoveMap_Click); // // bAddMap // this.bAddMap.Location = new System.Drawing.Point(226, 81); this.bAddMap.Name = "bAddMap"; this.bAddMap.Size = new System.Drawing.Size(75, 23); this.bAddMap.TabIndex = 1; this.bAddMap.Text = "Add..."; this.bAddMap.UseVisualStyleBackColor = true; this.bAddMap.Click += new System.EventHandler(this.bAddMap_Click); // // lbMaps // this.lbMaps.FormattingEnabled = true; this.lbMaps.Location = new System.Drawing.Point(15, 80); this.lbMaps.Name = "lbMaps"; this.lbMaps.Size = new System.Drawing.Size(188, 147); this.lbMaps.TabIndex = 0; // // bApply // this.bApply.Location = new System.Drawing.Point(386, 275); this.bApply.Name = "bApply"; this.bApply.Size = new System.Drawing.Size(75, 23); this.bApply.TabIndex = 3; this.bApply.Text = "Apply"; this.bApply.Click += new System.EventHandler(this.bApply_Click); // // cbShowReportWaitDialog // this.cbShowReportWaitDialog.AutoSize = true; this.cbShowReportWaitDialog.Location = new System.Drawing.Point(14, 155); this.cbShowReportWaitDialog.Name = "cbShowReportWaitDialog"; this.cbShowReportWaitDialog.Size = new System.Drawing.Size(229, 17); this.cbShowReportWaitDialog.TabIndex = 8; this.cbShowReportWaitDialog.Text = "Show Rendering Report Dialog on Preview"; this.cbShowReportWaitDialog.UseVisualStyleBackColor = true; // // DialogToolOptions // this.AcceptButton = this.bOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.bCancel; this.ClientSize = new System.Drawing.Size(466, 304); this.Controls.Add(this.bApply); this.Controls.Add(this.tabControl1); this.Controls.Add(this.bCancel); this.Controls.Add(this.bOK); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DialogToolOptions"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Options"; this.tabControl1.ResumeLayout(false); this.tpGeneral.ResumeLayout(false); this.tpGeneral.PerformLayout(); this.gbPropLoc.ResumeLayout(false); this.gbPropLoc.PerformLayout(); this.tpToolbar.ResumeLayout(false); this.tpDesktop.ResumeLayout(false); this.tpDesktop.PerformLayout(); this.tabPage1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private bool Verify() { try { int i = Convert.ToInt32(this.tbRecentFilesMax.Text); return (i >= 1 || i <= 50); } catch { MessageBox.Show("Recent files maximum must be an integer between 1 and 50", "Options"); return false; } } private void bOK_Click(object sender, System.EventArgs e) { if (DoApply()) { DialogResult = DialogResult.OK; this.Close(); } } private bool DoApply() { lock(this) { try { if (!Verify()) return false; HandleRecentFilesMax(); _RdlDesigner.HelpUrl = this.tbHelpUrl.Text; HandleShows(); HandleProperties(); if (bToolbar) HandleToolbar(); if (bDesktop) HandleDesktop(); if (bMaps) HandleMaps(); bToolbar = bDesktop = false; // no changes now return true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Options"); return false; } } } private void HandleProperties() { DockStyle ds = DockStyle.Right; if (this.rbPBTop.Checked) ds = DockStyle.Top; else if (this.rbPBBottom.Checked) ds = DockStyle.Bottom; else if (this.rbPBLeft.Checked) ds = DockStyle.Left; _RdlDesigner.PropertiesLocation = ds; _RdlDesigner.PropertiesAutoHide = chkPBAutoHide.Checked; } private void HandleDesktop() { if (_DesktopDocument == null) { _DesktopDocument = new XmlDocument(); XmlProcessingInstruction xPI; xPI = _DesktopDocument.CreateProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); _DesktopDocument.AppendChild(xPI); } if (_DesktopPort == null) { _DesktopPort = _DesktopDocument.CreateElement("port"); _DesktopDocument.AppendChild(_DesktopPort); } _DesktopPort.InnerText = this.tbPort.Text; if (_DesktopDirectory == null) { _DesktopDirectory = _DesktopDocument.CreateElement("serverroot"); _DesktopDocument.AppendChild(_DesktopDirectory); } _DesktopDirectory.InnerText = this.tbDirectory.Text; if (_DesktopLocal == null) { _DesktopLocal = _DesktopDocument.CreateElement("localhostonly"); _DesktopDocument.AppendChild(_DesktopLocal); } _DesktopLocal.InnerText = this.ckLocal.Checked? "true": "false"; string optFileName = AppDomain.CurrentDomain.BaseDirectory + "config.xml"; _DesktopDocument.Save(optFileName); this._RdlDesigner.menuToolsCloseProcess(false); // close the server } private void HandleMaps() { string[] maps = new string[lbMaps.Items.Count]; for (int i = 0; i < lbMaps.Items.Count; i++) { maps[i] = lbMaps.Items[i] as string; } RdlDesigner.MapSubtypes = maps; } private void HandleRecentFilesMax() { // Handle the RecentFilesMax int i = Convert.ToInt32(this.tbRecentFilesMax.Text); if (i < 1 || i > 50) throw new Exception("Recent files maximum must be an integer between 1 and 50"); if (this._RdlDesigner.RecentFilesMax == i) // if not different we don't need to do anything return; this._RdlDesigner.RecentFilesMax = i; // Make the list match the maximum size bool bChangeMenu=false; while (_RdlDesigner.RecentFiles.Count > _RdlDesigner.RecentFilesMax) { _RdlDesigner.RecentFiles.RemoveAt(0); // remove the first entry bChangeMenu = true; } if (bChangeMenu) _RdlDesigner.RecentFilesMenu(); // reset the menu since the list changed return; } private void HandleToolbar() { List<string> ar = new List<string>(); foreach (string item in this.lbToolbar.Items) ar.Add(item); this._RdlDesigner.Toolbar = ar; } private void HandleShows() { _RdlDesigner.ShowEditLines = this.cbEditLines.Checked; _RdlDesigner.ShowReportItemOutline = this.cbOutline.Checked; _RdlDesigner.ShowTabbedInterface = this.cbTabInterface.Checked; _RdlDesigner.ShowPreviewWaitDialog = this.cbShowReportWaitDialog.Checked; foreach (MDIChild mc in _RdlDesigner.MdiChildren) { mc.ShowEditLines(this.cbEditLines.Checked); mc.ShowReportItemOutline = this.cbOutline.Checked; mc.ShowPreviewWaitDialog(this.cbShowReportWaitDialog.Checked); } } private void bCopyItem_Click(object sender, System.EventArgs e) { bToolbar=true; int i = this.lbOperation.SelectedIndex; if (i < 0) return; string itm = lbOperation.Items[i] as String; lbToolbar.Items.Add(itm); // Remove from list if not allowed to be duplicated in toolbar if (!_RdlDesigner.ToolbarAllowDups.Contains(itm)) lbOperation.Items.RemoveAt(i); } private void bRemove_Click(object sender, System.EventArgs e) { bToolbar = true; int i = this.lbToolbar.SelectedIndex; if (i < 0) return; string itm = lbToolbar.Items[i] as String; if (itm == "Newline" || itm == "Space") {} else lbOperation.Items.Add(itm); lbToolbar.Items.RemoveAt(i); } private void bUp_Click(object sender, System.EventArgs e) { int i = this.lbToolbar.SelectedIndex; if (i <= 0) return; Swap(i-1, i); } private void bDown_Click(object sender, System.EventArgs e) { int i = this.lbToolbar.SelectedIndex; if (i < 0 || i == lbToolbar.Items.Count-1) return; Swap(i, i+1); } /// <summary> /// Swap items in the toolbar listbox. i1 should always be less than i2 /// </summary> /// <param name="i1"></param> /// <param name="i2"></param> private void Swap(int i1, int i2) { bToolbar = true; bool b1 = (i1 == lbToolbar.SelectedIndex); string s1 = lbToolbar.Items[i1] as string; string s2 = lbToolbar.Items[i2] as string; lbToolbar.SuspendLayout(); lbToolbar.Items.RemoveAt(i2); lbToolbar.Items.RemoveAt(i1); lbToolbar.Items.Insert(i1, s2); lbToolbar.Items.Insert(i2, s1); lbToolbar.SelectedIndex = b1? i2: i1; lbToolbar.ResumeLayout(true); } private void bReset_Click(object sender, System.EventArgs e) { bToolbar = true; this.lbToolbar.Items.Clear(); List<string> ar = this._RdlDesigner.ToolbarDefault; foreach (string itm in ar) this.lbToolbar.Items.Add(itm); InitOperations(); } private void bApply_Click(object sender, System.EventArgs e) { DoApply(); } private void Desktop_Changed(object sender, System.EventArgs e) { bDesktop = true; } private void bBrowse_Click(object sender, System.EventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); // Set the help text description for the FolderBrowserDialog. fbd.Description = "Select the directory that will contain reports."; // Do not allow the user to create new files via the FolderBrowserDialog. fbd.ShowNewFolderButton = false; // fbd.RootFolder = System.Environment.SpecialFolder.MyComputer; fbd.SelectedPath = this.tbDirectory.Text.Length == 0? "Examples": tbDirectory.Text; try { if (fbd.ShowDialog(this) == DialogResult.Cancel) return; tbDirectory.Text = fbd.SelectedPath; bDesktop = true; // we modified Desktop settings } finally { fbd.Dispose(); } return; } static internal DesktopConfig DesktopConfiguration { get { string optFileName = AppDomain.CurrentDomain.BaseDirectory + "config.xml"; DesktopConfig dc = new DesktopConfig(); try { XmlDocument xDoc = new XmlDocument(); xDoc.Load(optFileName); XmlNode xNode; xNode = xDoc.SelectSingleNode("//config"); // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name.ToLower()) { case "serverroot": dc.Directory = xNodeLoop.InnerText; break; case "port": dc.Port = xNodeLoop.InnerText; break; } } return dc; } catch (Exception ex) { throw new Exception(string.Format("Unable to obtain Desktop config information.\n{0}", ex.Message)); } } } private void cbTabInterface_CheckedChanged(object sender, EventArgs e) { this.bToolbar = true; // tabbed interface is part of the toolbar } private void bAddMap_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; ofd.DefaultExt = "rdl"; ofd.Filter = "Map files (*.xml)|*.xml|" + "All files (*.*)|*.*"; ofd.FilterIndex = 1; ofd.CheckFileExists = true; ofd.Multiselect = true; try { if (ofd.ShowDialog(this) == DialogResult.OK) { foreach (string file in ofd.FileNames) { string nm = Path.GetFileNameWithoutExtension(file); if (!lbMaps.Items.Contains(nm)) { lbMaps.Items.Add(nm); bMaps = true; } } } } finally { ofd.Dispose(); } } private void bRemoveMap_Click(object sender, EventArgs e) { if (lbMaps.SelectedIndex < 0) return; lbMaps.Items.RemoveAt(lbMaps.SelectedIndex); bMaps = true; return; } } internal class DesktopConfig { internal string Directory; internal string Port; } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.IO; #if HAVE_ASYNC using System.Threading; using System.Threading.Tasks; #endif using System.Collections.Generic; using System.Diagnostics; #if !HAVE_LINQ using Microsoft.Identity.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Microsoft.Identity.Json.Utilities { internal static class BufferUtils { public static char[] RentBuffer(IArrayPool<char> bufferPool, int minSize) { if (bufferPool == null) { return new char[minSize]; } char[] buffer = bufferPool.Rent(minSize); return buffer; } public static void ReturnBuffer(IArrayPool<char> bufferPool, char[] buffer) { bufferPool?.Return(buffer); } public static char[] EnsureBufferSize(IArrayPool<char> bufferPool, int size, char[] buffer) { if (bufferPool == null) { return new char[size]; } if (buffer != null) { bufferPool.Return(buffer); } return bufferPool.Rent(size); } } internal static class JavaScriptUtils { internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; private const int UnicodeTextLength = 6; static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (int i = 0; i < ' '; i++) { escapeChars.Add((char)i); } foreach (char escapeChar in escapeChars.Union(new[] { '\'' })) { SingleQuoteCharEscapeFlags[escapeChar] = true; } foreach (char escapeChar in escapeChars.Union(new[] { '"' })) { DoubleQuoteCharEscapeFlags[escapeChar] = true; } foreach (char escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) { HtmlCharEscapeFlags[escapeChar] = true; } } private const string EscapedUnicodeText = "!"; public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) { if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) { return HtmlCharEscapeFlags; } if (quoteChar == '"') { return DoubleQuoteCharEscapeFlags; } return SingleQuoteCharEscapeFlags; } public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) { if (s == null) { return false; } foreach (char c in s) { if (c >= charEscapeFlags.Length || charEscapeFlags[c]) { return true; } } return false; } public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char> bufferPool, ref char[] writeBuffer) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (!string.IsNullOrEmpty(s)) { int lastWritePosition = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling); if (lastWritePosition == -1) { writer.Write(s); } else { if (lastWritePosition != 0) { if (writeBuffer == null || writeBuffer.Length < lastWritePosition) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, lastWritePosition, writeBuffer); } // write unchanged chars at start of text. s.CopyTo(0, writeBuffer, 0, lastWritePosition); writer.Write(writeBuffer, 0, lastWritePosition); } int length; for (int i = lastWritePosition; i < s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); } StringUtils.ToCharAsUnicode(c, writeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); if (i > lastWritePosition) { length = i - lastWritePosition + (isEscapedUnicodeText ? UnicodeTextLength : 0); int start = isEscapedUnicodeText ? UnicodeTextLength : 0; if (writeBuffer == null || writeBuffer.Length < length) { char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length); // the unicode text is already in the buffer // copy it over when creating new buffer if (isEscapedUnicodeText) { Debug.Assert(writeBuffer != null, "Write buffer should never be null because it is set when the escaped unicode text is encountered."); Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); } BufferUtils.ReturnBuffer(bufferPool, writeBuffer); writeBuffer = newBuffer; } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text writer.Write(writeBuffer, start, length - start); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { writer.Write(escapedValue); } else { writer.Write(writeBuffer, 0, UnicodeTextLength); } } Debug.Assert(lastWritePosition != 0); length = s.Length - lastWritePosition; if (length > 0) { if (writeBuffer == null || writeBuffer.Length < length) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer); } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text writer.Write(writeBuffer, 0, length); } } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16)) { char[] buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); return w.ToString(); } } private static int FirstCharToEscape(string s, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling) { for (int i = 0; i != s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length) { if (charEscapeFlags[c]) { return i; } } else if (stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { return i; } else { switch (c) { case '\u0085': case '\u2028': case '\u2029': return i; } } } return -1; } #if HAVE_ASYNC public static Task WriteEscapedJavaScriptStringAsync(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return cancellationToken.FromCanceled(); } if (appendDelimiters) { return WriteEscapedJavaScriptStringWithDelimitersAsync(writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } if (string.IsNullOrEmpty(s)) { return cancellationToken.CancelIfRequestedAsync() ?? AsyncUtils.CompletedTask; } return WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } private static Task WriteEscapedJavaScriptStringWithDelimitersAsync(TextWriter writer, string s, char delimiter, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { Task task = writer.WriteAsync(delimiter, cancellationToken); if (!task.IsCompletedSucessfully()) { return WriteEscapedJavaScriptStringWithDelimitersAsync(task, writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } if (!string.IsNullOrEmpty(s)) { task = WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); if (task.IsCompletedSucessfully()) { return writer.WriteAsync(delimiter, cancellationToken); } } return WriteCharAsync(task, writer, delimiter, cancellationToken); } private static async Task WriteEscapedJavaScriptStringWithDelimitersAsync(Task task, TextWriter writer, string s, char delimiter, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { await task.ConfigureAwait(false); if (!string.IsNullOrEmpty(s)) { await WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken).ConfigureAwait(false); } await writer.WriteAsync(delimiter).ConfigureAwait(false); } public static async Task WriteCharAsync(Task task, TextWriter writer, char c, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await writer.WriteAsync(c, cancellationToken).ConfigureAwait(false); } private static Task WriteEscapedJavaScriptStringWithoutDelimitersAsync( TextWriter writer, string s, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { int i = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling); return i == -1 ? writer.WriteAsync(s, cancellationToken) : WriteDefinitelyEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, i, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } private static async Task WriteDefinitelyEscapedJavaScriptStringWithoutDelimitersAsync( TextWriter writer, string s, int lastWritePosition, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { if (writeBuffer == null || writeBuffer.Length < lastWritePosition) { writeBuffer = client.EnsureWriteBuffer(lastWritePosition, UnicodeTextLength); } if (lastWritePosition != 0) { s.CopyTo(0, writeBuffer, 0, lastWritePosition); // write unchanged chars at start of text. await writer.WriteAsync(writeBuffer, 0, lastWritePosition, cancellationToken).ConfigureAwait(false); } int length; bool isEscapedUnicodeText = false; string escapedValue = null; for (int i = lastWritePosition; i < s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer.Length < UnicodeTextLength) { writeBuffer = client.EnsureWriteBuffer(UnicodeTextLength, 0); } StringUtils.ToCharAsUnicode(c, writeBuffer); isEscapedUnicodeText = true; } } else { continue; } break; } if (i > lastWritePosition) { length = i - lastWritePosition + (isEscapedUnicodeText ? UnicodeTextLength : 0); int start = isEscapedUnicodeText ? UnicodeTextLength : 0; if (writeBuffer.Length < length) { writeBuffer = client.EnsureWriteBuffer(length, UnicodeTextLength); } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text await writer.WriteAsync(writeBuffer, start, length - start, cancellationToken).ConfigureAwait(false); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { await writer.WriteAsync(escapedValue, cancellationToken).ConfigureAwait(false); } else { await writer.WriteAsync(writeBuffer, 0, UnicodeTextLength, cancellationToken).ConfigureAwait(false); isEscapedUnicodeText = false; } } length = s.Length - lastWritePosition; if (length != 0) { if (writeBuffer.Length < length) { writeBuffer = client.EnsureWriteBuffer(length, 0); } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text await writer.WriteAsync(writeBuffer, 0, length, cancellationToken).ConfigureAwait(false); } } #endif public static bool TryGetDateFromConstructorJson(JsonReader reader, out DateTime dateTime, out string errorMessage) { dateTime = default; errorMessage = null; if (!TryGetDateConstructorValue(reader, out long? t1, out errorMessage) || t1 == null) { errorMessage = errorMessage ?? "Date constructor has no arguments."; return false; } if (!TryGetDateConstructorValue(reader, out long? t2, out errorMessage)) { return false; } else if (t2 != null) { // Only create a list when there is more than one argument List<long> dateArgs = new List<long> { t1.Value, t2.Value }; while (true) { if (!TryGetDateConstructorValue(reader, out long? integer, out errorMessage)) { return false; } else if (integer != null) { dateArgs.Add(integer.Value); } else { break; } } if (dateArgs.Count > 7) { errorMessage = "Unexpected number of arguments when reading date constructor."; return false; } // Pad args out to the number used by the ctor while (dateArgs.Count < 7) { dateArgs.Add(0); } dateTime = new DateTime((int)dateArgs[0], (int)dateArgs[1] + 1, dateArgs[2] == 0 ? 1 : (int)dateArgs[2], (int)dateArgs[3], (int)dateArgs[4], (int)dateArgs[5], (int)dateArgs[6]); } else { dateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(t1.Value); } return true; } private static bool TryGetDateConstructorValue(JsonReader reader, out long? integer, out string errorMessage) { integer = null; errorMessage = null; if (!reader.Read()) { errorMessage = "Unexpected end when reading date constructor."; return false; } if (reader.TokenType == JsonToken.EndConstructor) { return true; } if (reader.TokenType != JsonToken.Integer) { errorMessage = "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType; return false; } integer = (long)reader.Value; return true; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 3/2/2010 10:56:27 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections; using System.Collections.Generic; namespace DotSpatial.Data { /// <summary> /// The FeatureSetPack contains a MultiPoint, Line and Polygon FeatureSet which can /// handle the various types of geometries that can arrive from a mixed geometry. /// </summary> public class FeatureSetPack : IEnumerable<IFeatureSet> { /// <summary> /// The featureset with all the lines /// </summary> public IFeatureSet Lines { get; set; } /// <summary> /// The featureset with all the points /// </summary> public IFeatureSet Points { get; set; } /// <summary> /// The featureset with all the polygons /// </summary> public IFeatureSet Polygons { get; set; } private int _lineLength; private List<double[]> _lineVertices; private int _pointLength; private List<double[]> _pointVertices; private int _polygonLength; /// <summary> /// Stores the raw vertices from the different shapes in a list while being created. /// That way, the final array can be created one time. /// </summary> private List<double[]> _polygonVertices; /// <summary> /// Creates a new instance of the FeatureSetPack /// </summary> public FeatureSetPack() { Polygons = new FeatureSet(FeatureType.Polygon) {IndexMode = true}; Points = new FeatureSet(FeatureType.MultiPoint) {IndexMode = true}; Lines = new FeatureSet(FeatureType.Line) {IndexMode = true}; _polygonVertices = new List<double[]>(); _pointVertices = new List<double[]>(); _lineVertices = new List<double[]>(); } #region IEnumerable<IFeatureSet> Members /// <inheritdoc /> public IEnumerator<IFeatureSet> GetEnumerator() { return new FeatureSetPackEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion /// <summary> /// Clears the vertices and sets up new featuresets. /// </summary> public void Clear() { _polygonVertices = new List<double[]>(); _pointVertices = new List<double[]>(); _lineVertices = new List<double[]>(); Polygons = new FeatureSet(FeatureType.Polygon); Polygons.IndexMode = true; Points = new FeatureSet(FeatureType.MultiPoint); Points.IndexMode = true; Lines = new FeatureSet(FeatureType.Line); Lines.IndexMode = true; _lineLength = 0; _polygonLength = 0; _pointLength = 0; } /// <summary> /// Adds the shape. Assumes that the "part" indices are created with a 0 base, and the number of /// vertices is specified. The start range of each part will be updated with the new shape range. /// The vertices array itself iwll be updated during hte stop editing step. /// </summary> /// <param name="shapeVertices"></param> /// <param name="shape"></param> public void Add(double[] shapeVertices, ShapeRange shape) { if (shape.FeatureType == FeatureType.Point || shape.FeatureType == FeatureType.MultiPoint) { _pointVertices.Add(shapeVertices); shape.StartIndex = _pointLength / 2; // point offset, not double offset Points.ShapeIndices.Add(shape); _pointLength += shapeVertices.Length; } if (shape.FeatureType == FeatureType.Line) { _lineVertices.Add(shapeVertices); shape.StartIndex = _lineLength / 2; // point offset Lines.ShapeIndices.Add(shape); _lineLength += shapeVertices.Length; } if (shape.FeatureType == FeatureType.Polygon) { _polygonVertices.Add(shapeVertices); shape.StartIndex = _polygonLength / 2; // point offset Polygons.ShapeIndices.Add(shape); _polygonLength += shapeVertices.Length / 2; } } /// <summary> /// Finishes the featuresets by converting the lists /// </summary> public void StopEditing() { Points.Vertex = Combine(_pointVertices, _pointLength); Points.UpdateExtent(); Lines.Vertex = Combine(_lineVertices, _lineLength); Lines.UpdateExtent(); Polygons.Vertex = Combine(_polygonVertices, _polygonLength); Polygons.UpdateExtent(); } /// <summary> /// Combines the vertices, finalizing the creation /// </summary> /// <param name="verts"></param> /// <param name="length"></param> /// <returns></returns> public static double[] Combine(IEnumerable<double[]> verts, int length) { double[] result = new double[length * 2]; int offset = 0; foreach (double[] shape in verts) { Array.Copy(shape, 0, result, offset, shape.Length); offset += shape.Length; } return result; } #region Nested type: FeatureSetPackEnumerator /// <summary> /// Enuemratres the FeatureSetPack in Polygon, Line, Point order. If any member /// is null, it skips that member. /// </summary> private class FeatureSetPackEnumerator : IEnumerator<IFeatureSet> { private readonly FeatureSetPack _parent; private IFeatureSet _current; private int _index; /// <summary> /// Creates the FeatureSetPackEnumerator based on the specified FeaturSetPack /// </summary> /// <param name="parent">The Pack</param> public FeatureSetPackEnumerator(FeatureSetPack parent) { _parent = parent; _index = -1; } #region IEnumerator<IFeatureSet> Members /// <inheritdoc /> public IFeatureSet Current { get { return _current; } } object IEnumerator.Current { get { return _current; } } /// <inheritdoc /> public void Dispose() { } /// <inheritdoc /> public bool MoveNext() { _current = null; while (_current == null || _current.Vertex == null || _current.Vertex.Length == 0) { _index++; if (_index > 2) return false; switch (_index) { case 0: _current = _parent.Polygons; break; case 1: _current = _parent.Lines; break; case 2: _current = _parent.Points; break; } } return true; } /// <inheritdoc /> public void Reset() { _index = -1; _current = null; } #endregion } #endregion } }
namespace ExcelDataReader.Silverlight.Core.BinaryFormat { using System; /// <summary> /// Represents basic BIFF record /// Base class for all BIFF record types /// </summary> internal class XlsBiffRecord { protected byte[] m_bytes; protected int m_readoffset; /// <summary> /// Basic entry constructor /// </summary> /// <param name="bytes">array representing this entry</param> protected XlsBiffRecord(byte[] bytes) : this(bytes, 0) { } protected XlsBiffRecord(byte[] bytes, uint offset) { if (bytes.Length - offset < 4) throw new ArgumentException(Errors.ErrorBIFFRecordSize); m_bytes = bytes; m_readoffset = (int)(4 + offset); if (bytes.Length < offset + Size) throw new ArgumentException(Errors.ErrorBIFFBufferSize); } internal byte[] Bytes { get { return m_bytes; } } internal int Offset { get { return m_readoffset - 4; } } /// <summary> /// Returns type ID of this entry /// </summary> public BIFFRECORDTYPE ID { get { return (BIFFRECORDTYPE)BitConverter.ToUInt16(m_bytes, m_readoffset - 4); } } /// <summary> /// Returns data size of this entry /// </summary> public ushort RecordSize { get { return BitConverter.ToUInt16(m_bytes, m_readoffset - 2); } } /// <summary> /// Returns whole size of structure /// </summary> public int Size { get { return 4 + RecordSize; } } /// <summary> /// Returns record at specified offset /// </summary> /// <param name="bytes">byte array</param> /// <param name="offset">position in array</param> /// <returns></returns> public static XlsBiffRecord GetRecord(byte[] bytes, uint offset) { uint ID = BitConverter.ToUInt16(bytes, (int)offset); switch ((BIFFRECORDTYPE)ID) { case BIFFRECORDTYPE.BOF_V2: case BIFFRECORDTYPE.BOF_V3: case BIFFRECORDTYPE.BOF_V4: case BIFFRECORDTYPE.BOF: return new XlsBiffBOF(bytes, offset); case BIFFRECORDTYPE.EOF: return new XlsBiffEOF(bytes, offset); case BIFFRECORDTYPE.INTERFACEHDR: return new XlsBiffInterfaceHdr(bytes, offset); case BIFFRECORDTYPE.SST: return new XlsBiffSST(bytes, offset); case BIFFRECORDTYPE.INDEX: return new XlsBiffIndex(bytes, offset); case BIFFRECORDTYPE.ROW: return new XlsBiffRow(bytes, offset); case BIFFRECORDTYPE.DBCELL: return new XlsBiffDbCell(bytes, offset); case BIFFRECORDTYPE.BLANK: case BIFFRECORDTYPE.BLANK_OLD: return new XlsBiffBlankCell(bytes, offset); case BIFFRECORDTYPE.MULBLANK: return new XlsBiffMulBlankCell(bytes, offset); case BIFFRECORDTYPE.LABEL: case BIFFRECORDTYPE.LABEL_OLD: case BIFFRECORDTYPE.RSTRING: return new XlsBiffLabelCell(bytes, offset); case BIFFRECORDTYPE.LABELSST: return new XlsBiffLabelSSTCell(bytes, offset); case BIFFRECORDTYPE.INTEGER: case BIFFRECORDTYPE.INTEGER_OLD: return new XlsBiffIntegerCell(bytes, offset); case BIFFRECORDTYPE.NUMBER: case BIFFRECORDTYPE.NUMBER_OLD: return new XlsBiffNumberCell(bytes, offset); case BIFFRECORDTYPE.RK: return new XlsBiffRKCell(bytes, offset); case BIFFRECORDTYPE.MULRK: return new XlsBiffMulRKCell(bytes, offset); case BIFFRECORDTYPE.FORMULA: case BIFFRECORDTYPE.FORMULA_OLD: return new XlsBiffFormulaCell(bytes, offset); case BIFFRECORDTYPE.STRING: return new XlsBiffFormulaString(bytes, offset); case BIFFRECORDTYPE.CONTINUE: return new XlsBiffContinue(bytes, offset); case BIFFRECORDTYPE.DIMENSIONS: return new XlsBiffDimensions(bytes, offset); case BIFFRECORDTYPE.BOUNDSHEET: return new XlsBiffBoundSheet(bytes, offset); case BIFFRECORDTYPE.WINDOW1: return new XlsBiffWindow1(bytes, offset); case BIFFRECORDTYPE.CODEPAGE: return new XlsBiffSimpleValueRecord(bytes, offset); case BIFFRECORDTYPE.FNGROUPCOUNT: return new XlsBiffSimpleValueRecord(bytes, offset); case BIFFRECORDTYPE.RECORD1904: return new XlsBiffSimpleValueRecord(bytes, offset); case BIFFRECORDTYPE.BOOKBOOL: return new XlsBiffSimpleValueRecord(bytes, offset); case BIFFRECORDTYPE.BACKUP: return new XlsBiffSimpleValueRecord(bytes, offset); case BIFFRECORDTYPE.HIDEOBJ: return new XlsBiffSimpleValueRecord(bytes, offset); case BIFFRECORDTYPE.USESELFS: return new XlsBiffSimpleValueRecord(bytes, offset); default: return new XlsBiffRecord(bytes, offset); } } public byte ReadByte(int offset) { return Buffer.GetByte(m_bytes, m_readoffset + offset); } public ushort ReadUInt16(int offset) { return BitConverter.ToUInt16(m_bytes, m_readoffset + offset); } public uint ReadUInt32(int offset) { return BitConverter.ToUInt32(m_bytes, m_readoffset + offset); } public ulong ReadUInt64(int offset) { return BitConverter.ToUInt64(m_bytes, m_readoffset + offset); } public short ReadInt16(int offset) { return BitConverter.ToInt16(m_bytes, m_readoffset + offset); } public int ReadInt32(int offset) { return BitConverter.ToInt32(m_bytes, m_readoffset + offset); } public long ReadInt64(int offset) { return BitConverter.ToInt64(m_bytes, m_readoffset + offset); } public byte[] ReadArray(int offset, int size) { byte[] tmp = new byte[size]; Buffer.BlockCopy(m_bytes, m_readoffset + offset, tmp, 0, size); return tmp; } public float ReadFloat(int offset) { return BitConverter.ToSingle(m_bytes, m_readoffset + offset); } public double ReadDouble(int offset) { return BitConverter.ToDouble(m_bytes, m_readoffset + offset); } } }
namespace Boxed.Mapping { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; /// <summary> /// <see cref="IMapper{TSource, TDestination}"/> extension methods. /// </summary> public static class MapperExtensions { #if NETSTANDARD2_1 /// <summary> /// Maps the <see cref="IAsyncEnumerable{TSource}"/> into <see cref="IAsyncEnumerable{TDestination}"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source asynchronous enumerable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An <see cref="IAsyncEnumerable{TDestination}"/> collection.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async IAsyncEnumerable<TDestination> MapEnumerableAsync<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, IAsyncEnumerable<TSource> source, [EnumeratorCancellation] CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } await foreach (var sourceItem in source.ConfigureAwait(false).WithCancellation(cancellationToken)) { var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); yield return destinationItem; } } #endif /// <summary> /// Maps the specified source object to a new object with a type of <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source object.</typeparam> /// <typeparam name="TDestination">The type of the destination object.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source object.</param> /// <returns>The mapped object of type <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper" /> or <paramref name="source" /> is /// <c>null</c>.</exception> public static TDestination Map<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = Factory<TDestination>.CreateInstance(); mapper.Map(source, destination); return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSourceCollection">The type of the source collection.</typeparam> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="sourceCollection">The source collection.</param> /// <param name="destinationCollection">The destination collection.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="sourceCollection"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSourceCollection, TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSourceCollection sourceCollection, TDestination[] destinationCollection) where TSourceCollection : IEnumerable<TSource> where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (sourceCollection is null) { throw new ArgumentNullException(nameof(sourceCollection)); } if (destinationCollection is null) { throw new ArgumentNullException(nameof(destinationCollection)); } var i = 0; foreach (var item in sourceCollection) { var destination = Factory<TDestination>.CreateInstance(); mapper.Map(item, destination); destinationCollection[i] = destination; ++i; } return destinationCollection; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, List<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Count]; for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination[i] = destinationItem; } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, Collection<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Count]; for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination[i] = destinationItem; } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource[] source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Length]; for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination[i] = destinationItem; } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, IEnumerable<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Count()]; var i = 0; foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination[i] = destinationItem; ++i; } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource" /> into a collection of type /// <typeparamref name="TDestinationCollection" /> containing objects of type <typeparamref name="TDestination" />. /// </summary> /// <typeparam name="TSourceCollection">The type of the source collection.</typeparam> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestinationCollection">The type of the destination collection.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="sourceCollection">The source collection.</param> /// <param name="destinationCollection">The destination collection.</param> /// <returns>A collection of type <typeparamref name="TDestinationCollection"/> containing objects of type /// <typeparamref name="TDestination" />. /// </returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper" /> or <paramref name="sourceCollection" /> is /// <c>null</c>.</exception> public static TDestinationCollection MapCollection<TSourceCollection, TSource, TDestinationCollection, TDestination>( this IMapper<TSource, TDestination> mapper, TSourceCollection sourceCollection, TDestinationCollection destinationCollection) where TSourceCollection : IEnumerable<TSource> where TDestinationCollection : ICollection<TDestination> where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (sourceCollection is null) { throw new ArgumentNullException(nameof(sourceCollection)); } foreach (var item in sourceCollection) { var destination = Factory<TDestination>.CreateInstance(); mapper.Map(item, destination); destinationCollection.Add(destination); } return destinationCollection; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, List<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, Collection<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource[] source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, IEnumerable<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Add(destinationItem); } return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, List<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Count); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, Collection<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Count); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource[] source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Length); for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, IEnumerable<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Count()); foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Add(destinationItem); } return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, List<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, Collection<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, TSource[] source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> mapper, IEnumerable<TSource> source) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); mapper.Map(sourceItem, destinationItem); destination.Add(destinationItem); } return destination; } } }
// ---------------------------------------------------------------------------------------------------------------------- // <summary>The Photon Chat Api enables clients to connect to a chat server and communicate with other clients.</summary> // <remarks>ChatClient is the main class of this api.</remarks> // <copyright company="Exit Games GmbH">Photon Chat Api - Copyright (C) 2014 Exit Games GmbH</copyright> // ---------------------------------------------------------------------------------------------------------------------- namespace ExitGames.Client.Photon.Chat { using System; using System.Collections.Generic; using ExitGames.Client.Photon; /// <summary> /// Provides basic operations of the Photon Chat server. This internal class is used by public ChatClient. /// </summary> internal class ChatPeer : PhotonPeer { /// <summary>Name Server Host Name for Photon Cloud. Without port and without any prefix.</summary> public const string NameServerHost = "ns.exitgames.com"; /// <summary>Name Server for HTTP connections to the Photon Cloud. Includes prefix and port.</summary> public const string NameServerHttp = "http://ns.exitgamescloud.com:80/photon/n"; /// <summary>Name Server port per protocol (the UDP port is different than TCP, etc).</summary> private static readonly Dictionary<ConnectionProtocol, int> ProtocolToNameServerPort = new Dictionary<ConnectionProtocol, int>() { { ConnectionProtocol.Udp, 5058 }, { ConnectionProtocol.Tcp, 4533 }, { ConnectionProtocol.WebSocket, 9093 }, { ConnectionProtocol.WebSocketSecure, 19093 } }; //, { ConnectionProtocol.RHttp, 6063 } }; /// <summary>Name Server Address for Photon Cloud (based on current protocol). You can use the default values and usually won't have to set this value.</summary> public string NameServerAddress { get { return this.GetNameServerAddress(); } } virtual internal bool IsProtocolSecure { get { return this.UsedProtocol == ConnectionProtocol.WebSocketSecure; } } public ChatPeer(IPhotonPeerListener listener, ConnectionProtocol protocol) : base(listener, protocol) { #if UNITY #pragma warning disable 0162 // the library variant defines if we should use PUN's SocketUdp variant (at all) if (PhotonPeer.NoSocket) { #if !UNITY_EDITOR && (UNITY_PS3 || UNITY_ANDROID) UnityEngine.Debug.Log("Using class SocketUdpNativeDynamic"); this.SocketImplementation = typeof(SocketUdpNativeDynamic); #elif !UNITY_EDITOR && UNITY_IPHONE UnityEngine.Debug.Log("Using class SocketUdpNativeStatic"); this.SocketImplementation = typeof(SocketUdpNativeStatic); #elif !UNITY_EDITOR && (UNITY_WINRT) // this automatically uses a separate assembly-file with Win8-style Socket usage (not possible in Editor) #else Type udpSocket = Type.GetType("ExitGames.Client.Photon.SocketUdp, Assembly-CSharp"); this.SocketImplementation = udpSocket; if (udpSocket == null) { UnityEngine.Debug.Log("ChatClient could not find a suitable C# socket class. The Photon3Unity3D.dll only supports native socket plugins."); } #endif if (this.SocketImplementation == null) { UnityEngine.Debug.Log("No socket implementation set for 'NoSocket' assembly. Please contact Exit Games."); } } #pragma warning restore 0162 if (protocol == ConnectionProtocol.WebSocket || protocol == ConnectionProtocol.WebSocketSecure) { UnityEngine.Debug.Log("Using SocketWebTcp"); this.SocketImplementation = Type.GetType("ExitGames.Client.Photon.SocketWebTcp, Assembly-CSharp");//typeof(SocketWebTcp); } #endif } /// <summary> /// Gets the NameServer Address (with prefix and port), based on the set protocol (this.UsedProtocol). /// </summary> /// <returns>NameServer Address (with prefix and port).</returns> private string GetNameServerAddress() { #if RHTTP if (this.UsedProtocol == ConnectionProtocol.RHttp) { return NameServerHttp; } #endif ConnectionProtocol currentProtocol = this.UsedProtocol; int protocolPort = 0; ProtocolToNameServerPort.TryGetValue(currentProtocol, out protocolPort); string protocolPrefix = string.Empty; if (currentProtocol == ConnectionProtocol.WebSocket) { protocolPrefix = "ws://"; } else if (currentProtocol == ConnectionProtocol.WebSocketSecure) { protocolPrefix = "wss://"; } return string.Format("{0}{1}:{2}", protocolPrefix, NameServerHost, protocolPort); } public bool Connect() { this.Listener.DebugReturn(DebugLevel.INFO, "Connecting to nameserver " + this.NameServerAddress); return this.Connect(this.NameServerAddress, "NameServer"); } public bool AuthenticateOnNameServer(string appId, string appVersion, string region, AuthenticationValues authValues) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpAuthenticate()"); } var opParameters = new Dictionary<byte, object>(); opParameters[ParameterCode.AppVersion] = appVersion; opParameters[ParameterCode.ApplicationId] = appId; opParameters[ParameterCode.Region] = region; if (authValues != null) { if (!string.IsNullOrEmpty(authValues.UserId)) { opParameters[ParameterCode.UserId] = authValues.UserId; } if (authValues != null && authValues.AuthType != CustomAuthenticationType.None) { opParameters[ParameterCode.ClientAuthenticationType] = (byte) authValues.AuthType; if (!string.IsNullOrEmpty(authValues.Token)) { opParameters[ParameterCode.Secret] = authValues.Token; } else { if (!string.IsNullOrEmpty(authValues.AuthGetParameters)) { opParameters[ParameterCode.ClientAuthenticationParams] = authValues.AuthGetParameters; } if (authValues.AuthPostData != null) { opParameters[ParameterCode.ClientAuthenticationData] = authValues.AuthPostData; } } } } return this.OpCustom((byte)ChatOperationCode.Authenticate, opParameters, true, (byte)0, this.IsEncryptionAvailable); } } /// <summary> /// Options for optional "Custom Authentication" services used with Photon. Used by OpAuthenticate after connecting to Photon. /// </summary> public enum CustomAuthenticationType : byte { /// <summary>Use a custom authentification service. Currently the only implemented option.</summary> Custom = 0, /// <summary>Authenticates users by their Steam Account. Set auth values accordingly!</summary> Steam = 1, /// <summary>Authenticates users by their Facebook Account. Set auth values accordingly!</summary> Facebook = 2, /// <summary>Disables custom authentification. Same as not providing any AuthenticationValues for connect (more precisely for: OpAuthenticate).</summary> None = byte.MaxValue } /// <summary> /// Container for user authentication in Photon. Set AuthValues before you connect - all else is handled. /// </summary> /// <remarks> /// On Photon, user authentication is optional but can be useful in many cases. /// If you want to FindFriends, a unique ID per user is very practical. /// /// There are basically three options for user authentification: None at all, the client sets some UserId /// or you can use some account web-service to authenticate a user (and set the UserId server-side). /// /// Custom Authentication lets you verify end-users by some kind of login or token. It sends those /// values to Photon which will verify them before granting access or disconnecting the client. /// /// The Photon Cloud Dashboard will let you enable this feature and set important server values for it. /// https://www.exitgames.com/dashboard /// </remarks> public class AuthenticationValues { /// <summary>The type of custom authentication provider that should be used. Currently only "Custom" or "None" (turns this off).</summary> public CustomAuthenticationType AuthType = CustomAuthenticationType.None; /// <summary>This string must contain any (http get) parameters expected by the used authentication service. By default, username and token.</summary> /// <remarks>Standard http get parameters are used here and passed on to the service that's defined in the server (Photon Cloud Dashboard).</remarks> public string AuthGetParameters; /// <summary>Data to be passed-on to the auth service via POST. Default: null (not sent). Either string or byte[] (see setters).</summary> public object AuthPostData { get; private set; } /// <summary>After initial authentication, Photon provides a token for this client / user, which is subsequently used as (cached) validation.</summary> public string Token; /// <summary>The UserId should be a unique identifier per user. This is for finding friends, etc..</summary> public string UserId { get; set; } /// <summary>Creates empty auth values without any info.</summary> public AuthenticationValues() { } /// <summary>Creates minimal info about the user. If this is authenticated or not, depends on the set AuthType.</summary> /// <param name="userId">Some UserId to set in Photon.</param> public AuthenticationValues(string userId) { this.UserId = userId; } /// <summary>Sets the data to be passed-on to the auth service via POST.</summary> /// <param name="byteData">Binary token / auth-data to pass on. Empty string will set AuthPostData to null.</param> public virtual void SetAuthPostData(string stringData) { this.AuthPostData = (string.IsNullOrEmpty(stringData)) ? null : stringData; } /// <summary>Sets the data to be passed-on to the auth service via POST.</summary> /// <param name="byteData">Binary token / auth-data to pass on.</param> public virtual void SetAuthPostData(byte[] byteData) { this.AuthPostData = byteData; } /// <summary>Adds a key-value pair to the get-parameters used for Custom Auth.</summary> /// <remarks>This method does uri-encoding for you.</remarks> /// <param name="key">Key for the value to set.</param> /// <param name="value">Some value relevant for Custom Authentication.</param> public virtual void AddAuthParameter(string key, string value) { string ampersand = string.IsNullOrEmpty(this.AuthGetParameters) ? "" : "&"; this.AuthGetParameters = string.Format("{0}{1}{2}={3}", this.AuthGetParameters, ampersand, System.Uri.EscapeDataString(key), System.Uri.EscapeDataString(value)); } public override string ToString() { return string.Format("AuthenticationValues UserId: {0}, GetParameters: {1} Token available: {2}", UserId, this.AuthGetParameters, Token != null); } } public class ParameterCode { public const byte ApplicationId = 224; /// <summary>(221) Internally used to establish encryption</summary> public const byte Secret = 221; public const byte AppVersion = 220; /// <summary>(217) This key's (byte) value defines the target custom authentication type/service the client connects with. Used in OpAuthenticate</summary> public const byte ClientAuthenticationType = 217; /// <summary>(216) This key's (string) value provides parameters sent to the custom authentication type/service the client connects with. Used in OpAuthenticate</summary> public const byte ClientAuthenticationParams = 216; /// <summary>(214) This key's (string or byte[]) value provides parameters sent to the custom authentication service setup in Photon Dashboard. Used in OpAuthenticate</summary> public const byte ClientAuthenticationData = 214; /// <summary>(210) Used for region values in OpAuth and OpGetRegions.</summary> public const byte Region = 210; /// <summary>(230) Address of a (game) server to use.</summary> public const byte Address = 230; /// <summary>(225) User's ID</summary> public const byte UserId = 225; } /// <summary> /// ErrorCode defines the default codes associated with Photon client/server communication. /// </summary> public class ErrorCode { /// <summary>(0) is always "OK", anything else an error or specific situation.</summary> public const int Ok = 0; // server - Photon low(er) level: <= 0 /// <summary> /// (-3) Operation can't be executed yet (e.g. OpJoin can't be called before being authenticated, RaiseEvent cant be used before getting into a room). /// </summary> /// <remarks> /// Before you call any operations on the Cloud servers, the automated client workflow must complete its authorization. /// In PUN, wait until State is: JoinedLobby (with AutoJoinLobby = true) or ConnectedToMaster (AutoJoinLobby = false) /// </remarks> public const int OperationNotAllowedInCurrentState = -3; /// <summary>(-2) The operation you called is not implemented on the server (application) you connect to. Make sure you run the fitting applications.</summary> public const int InvalidOperationCode = -2; /// <summary>(-1) Something went wrong in the server. Try to reproduce and contact Exit Games.</summary> public const int InternalServerError = -1; // server - PhotonNetwork: 0x7FFF and down // logic-level error codes start with short.max /// <summary>(32767) Authentication failed. Possible cause: AppId is unknown to Photon (in cloud service).</summary> public const int InvalidAuthentication = 0x7FFF; /// <summary>(32766) GameId (name) already in use (can't create another). Change name.</summary> public const int GameIdAlreadyExists = 0x7FFF - 1; /// <summary>(32765) Game is full. This rarely happens when some player joined the room before your join completed.</summary> public const int GameFull = 0x7FFF - 2; /// <summary>(32764) Game is closed and can't be joined. Join another game.</summary> public const int GameClosed = 0x7FFF - 3; /// <summary>(32762) Not in use currently.</summary> public const int ServerFull = 0x7FFF - 5; /// <summary>(32761) Not in use currently.</summary> public const int UserBlocked = 0x7FFF - 6; /// <summary>(32760) Random matchmaking only succeeds if a room exists thats neither closed nor full. Repeat in a few seconds or create a new room.</summary> public const int NoRandomMatchFound = 0x7FFF - 7; /// <summary>(32758) Join can fail if the room (name) is not existing (anymore). This can happen when players leave while you join.</summary> public const int GameDoesNotExist = 0x7FFF - 9; /// <summary>(32757) Authorization on the Photon Cloud failed becaus the concurrent users (CCU) limit of the app's subscription is reached.</summary> /// <remarks> /// Unless you have a plan with "CCU Burst", clients might fail the authentication step during connect. /// Affected client are unable to call operations. Please note that players who end a game and return /// to the master server will disconnect and re-connect, which means that they just played and are rejected /// in the next minute / re-connect. /// This is a temporary measure. Once the CCU is below the limit, players will be able to connect an play again. /// /// OpAuthorize is part of connection workflow but only on the Photon Cloud, this error can happen. /// Self-hosted Photon servers with a CCU limited license won't let a client connect at all. /// </remarks> public const int MaxCcuReached = 0x7FFF - 10; /// <summary>(32756) Authorization on the Photon Cloud failed because the app's subscription does not allow to use a particular region's server.</summary> /// <remarks> /// Some subscription plans for the Photon Cloud are region-bound. Servers of other regions can't be used then. /// Check your master server address and compare it with your Photon Cloud Dashboard's info. /// https://cloud.exitgames.com/dashboard /// /// OpAuthorize is part of connection workflow but only on the Photon Cloud, this error can happen. /// Self-hosted Photon servers with a CCU limited license won't let a client connect at all. /// </remarks> public const int InvalidRegion = 0x7FFF - 11; /// <summary> /// (32755) Custom Authentication of the user failed due to setup reasons (see Cloud Dashboard) or the provided user data (like username or token). Check error message for details. /// </summary> public const int CustomAuthenticationFailed = 0x7FFF - 12; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; using Newtonsoft.Json.Linq; namespace Microsoft.AzureStack.Management { /// <summary> /// Operations for extensions metadata. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> internal partial class ExtensionMetadataOperations : IServiceOperations<AzureStackClient>, IExtensionMetadataOperations { /// <summary> /// Initializes a new instance of the ExtensionMetadataOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ExtensionMetadataOperations(AzureStackClient client) { this._client = client; } private AzureStackClient _client; /// <summary> /// Gets a reference to the /// Microsoft.AzureStack.Management.AzureStackClient. /// </summary> public AzureStackClient Client { get { return this._client; } } /// <summary> /// Returns list of extensions the user has access to (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result containing list of extensions the user has access to. /// </returns> public async Task<ExtensionMetadataListResult> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/extensionsMetadata"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ExtensionMetadataListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExtensionMetadataListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ExtensionMetadata extensionMetadataInstance = new ExtensionMetadata(); result.ExtensionsMetadata.Add(extensionMetadataInstance); JToken namespaceValue = valueValue["namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); extensionMetadataInstance.Namespace = namespaceInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); extensionMetadataInstance.Location = locationInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); extensionMetadataInstance.Name = nameInstance; } JToken endpointUriValue = valueValue["endpointUri"]; if (endpointUriValue != null && endpointUriValue.Type != JTokenType.Null) { string endpointUriInstance = ((string)endpointUriValue); extensionMetadataInstance.EndpointUri = endpointUriInstance; } } } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; namespace Haack.Postal { /// <summary> /// Address Info. /// </summary> public struct AddressInfo { string _streetAddress; string _city; State _state; string _postalCode; string _country; /// <summary> /// Gets the street address. /// </summary> /// <value></value> public string StreetAddress { get { return _streetAddress; } } /// <summary> /// Gets the city. /// </summary> /// <value></value> public string City { get { return _city; } } /// <summary> /// Gets the state. /// </summary> /// <value></value> public State State { get { return _state; } } /// <summary> /// Gets the postal code. /// </summary> /// <value></value> public string PostalCode { get { return _postalCode; } } /// <summary> /// Gets the country. /// </summary> /// <value></value> public string Country { get { return _country; } } /// <summary> /// Constructor. /// </summary> /// <param name="streetAddress"></param> /// <param name="city"></param> /// <param name="state"></param> /// <param name="postalCode"></param> /// <param name="country"></param> public AddressInfo(string streetAddress, string city, string state, string postalCode, string country) { _streetAddress = streetAddress; _city = city; _state = AddressInfo.ParseState(state); _postalCode = postalCode; _country = country; } #region State Information /// <summary> /// Gets the state given the state code. /// </summary> /// <param name="stateCode">State code.</param> /// <returns></returns> public static string GetState(StateCode stateCode) { return Convert(stateCode).ToString().Replace("_", " "); } /// <summary> /// Returns the two letter state code for the given State enum value. /// </summary> /// <param name="state"></param> /// <returns></returns> public static string GetStateCode(State state) { return Convert(state).ToString(); } /// <summary> /// Converts a State to a StateCode. /// </summary> /// <param name="value">A State enum value.</param> /// <returns></returns> public static StateCode Convert(State value) { return (StateCode)value; } /// <summary> /// Converts a StateCode to a State. /// </summary> /// <param name="value">A StateCode enum value.</param> /// <returns></returns> public static State Convert(StateCode value) { return (State)value; } /// <summary> /// Returns the State enum value for the state. /// </summary> /// <param name="state">Name of the state.</param> /// <returns></returns> public static State ParseState(string state) { return (State)Enum.Parse(typeof(State), state.Replace(" ", ""), true); } /// <summary> /// Returns the StateCode enum value for the state. /// </summary> /// <param name="stateCode">Two letter state code</param> /// <returns></returns> public static StateCode ParseStateCode(string stateCode) { return (StateCode)Enum.Parse(typeof(StateCode), stateCode, true); } #endregion } /// <summary> /// Simple enum for all the states. /// </summary> #region enum State public enum State { /// <summary>AL</summary> Alabama, /// <summary>AK (Home Sweet Home)</summary> Alaska, /// <summary>AS</summary> American_Samoa, /// <summary>AZ</summary> Arizona, /// <summary>AR</summary> Arkansas, /// <summary>CA (Home of SkillJam Technologies).</summary> California, /// <summary>CO</summary> Colorado, /// <summary>CN</summary> Connecticut, /// <summary>DE</summary> Delaware, /// <summary>DC</summary> District_Of_Columbia, /// <summary>FM</summary> Federated_States_Of_Micronesia, /// <summary>FL</summary> Florida, /// <summary>GA</summary> Georgia, /// <summary>GU</summary> Guam, /// <summary>HI</summary> Hawaii, /// <summary>ID</summary> Idaho, /// <summary>IL</summary> Illinois, /// <summary>IN</summary> Indiana, /// <summary>IA</summary> Iowa, /// <summary>KS</summary> Kansas, /// <summary>KY</summary> Kentucky, /// <summary>LA</summary> Louisiana, /// <summary>ME</summary> Maine, /// <summary>MH</summary> Marshall_Islands, /// <summary>MD</summary> Maryland, /// <summary>MA</summary> Massachusetts, /// <summary>MI</summary> Michigan, /// <summary>MN</summary> Minnesota, /// <summary>MS</summary> Mississippi, /// <summary>MO</summary> Missouri, /// <summary>MT</summary> Montana, /// <summary>NE</summary> Nebraska, /// <summary>NV</summary> Nevada, /// <summary>NH</summary> New_Hampshire, /// <summary>NJ</summary> New_Jersey, /// <summary>NM</summary> New_Mexico, /// <summary>NY</summary> New_York, /// <summary>NC</summary> North_Carolina, /// <summary>ND</summary> North_Dakota, /// <summary>MP</summary> Northern_Mariana_Islands, /// <summary>OH</summary> Ohio, /// <summary>OK</summary> Oklahoma, /// <summary>OR</summary> Oregon, /// <summary>PW</summary> Palau, /// <summary>PA</summary> Pennsylvania, /// <summary>PR</summary> Puerto_Rico, /// <summary>RI</summary> Rhode_Island, /// <summary>SC</summary> South_Carolina, /// <summary>SD</summary> South_Dakota, /// <summary>TN</summary> Tennessee, /// <summary>TX</summary> Texas, /// <summary>UT</summary> Utah, /// <summary>VT</summary> Vermont, /// <summary>VI</summary> Virgin_Islands, /// <summary>VA</summary> Virginia, /// <summary>WA</summary> Washington, /// <summary>WV</summary> West_Virginia, /// <summary>WI</summary> Wisconsin, /// <summary>WY</summary> Wyoming } #endregion /// <summary> /// 2 letter state codes for the US states /// </summary> #region enum StateCode public enum StateCode { /// <summary>Alabama</summary> AL = State.Alabama, /// <summary>Alaska</summary> AK = State.Alaska, /// <summary>American Samoa</summary> AS = State.American_Samoa, /// <summary>Arizona</summary> AZ = State.Arizona, /// <summary>Arkansas</summary> AR = State.Arkansas, /// <summary>California</summary> CA = State.California, /// <summary>Colorado</summary> CO = State.Colorado, /// <summary>Connecticut</summary> CT = State.Connecticut, /// <summary>Delaware</summary> DE = State.Delaware, /// <summary>District of Columbia</summary> DC = State.District_Of_Columbia, /// <summary>Federated States of Micronesia</summary> FM = State.Federated_States_Of_Micronesia, /// <summary>Florida</summary> FL = State.Florida, /// <summary>Georgia</summary> GA = State.Georgia, /// <summary>Guam</summary> GU = State.Guam, /// <summary>Hawaii</summary> HI = State.Hawaii, /// <summary>Idaho</summary> ID = State.Idaho, /// <summary>Illinois</summary> IL = State.Illinois, /// <summary>Indiana</summary> IN = State.Indiana, /// <summary>Iowa</summary> IA = State.Iowa, /// <summary>Kansas</summary> KS = State.Kansas, /// <summary>Kentucky</summary> KY = State.Kentucky, /// <summary>Louisiana</summary> LA = State.Louisiana, /// <summary>Maine</summary> ME = State.Maine, /// <summary>Marshall Islands</summary> MH = State.Marshall_Islands, /// <summary>Maryland</summary> MD = State.Maryland, /// <summary>Massachusetts</summary> MA = State.Massachusetts, /// <summary>Michigan</summary> MI = State.Michigan, /// <summary>Minnesota</summary> MN = State.Minnesota, /// <summary>Mississippi</summary> MS = State.Mississippi, /// <summary>Missouri</summary> MO = State.Missouri, /// <summary>Montana</summary> MT = State.Montana, /// <summary>Nebraska</summary> NE = State.Nebraska, /// <summary>Nevada</summary> NV = State.Nevada, /// <summary>New Hampshire</summary> NH = State.New_Hampshire, /// <summary>New Jersey</summary> NJ = State.New_Jersey, /// <summary>New Mexico</summary> NM = State.New_Mexico, /// <summary>New York</summary> NY = State.New_York, /// <summary>North Carolina</summary> NC = State.North_Carolina, /// <summary>North Dakota</summary> ND = State.North_Dakota, /// <summary>Northern Mariana Islands</summary> MP = State.Northern_Mariana_Islands, /// <summary>Ohio</summary> OH = State.Ohio, /// <summary>Oklahoma</summary> OK = State.Oklahoma, /// <summary>Oregon</summary> OR = State.Oregon, /// <summary>Palau</summary> PW = State.Palau, /// <summary>Pennsylvania</summary> PA = State.Pennsylvania, /// <summary>Puerto Rico</summary> PR = State.Puerto_Rico, /// <summary>Rhode Island</summary> RI = State.Rhode_Island, /// <summary>South Carolina</summary> SC = State.South_Carolina, /// <summary>South Dakota</summary> SD = State.South_Dakota, /// <summary>Tennessee</summary> TN = State.Tennessee, /// <summary>Texas</summary> TX = State.Texas, /// <summary>Utah</summary> UT = State.Utah, /// <summary>Vermont</summary> VT = State.Vermont, /// <summary>Virgin Islands</summary> VI = State.Virgin_Islands, /// <summary>Virginia</summary> VA = State.Virginia, /// <summary>Washington</summary> WA = State.Washington, /// <summary>West Virginia</summary> WV = State.West_Virginia, /// <summary>Wisconsin</summary> WI = State.Wisconsin, /// <summary>Wyoming</summary> WY = State.Wyoming } #endregion }
using nHydrate.Generator.Common; using nHydrate.Generator.Common.Models; using nHydrate.Generator.Common.Util; using System; using System.Linq; using System.Text; namespace nHydrate.Generator.EFCodeFirstNetCore.Generators.Entity { public class EntityGeneratedTemplate : EFCodeFirstNetCoreBaseTemplate { private readonly Table _item; public EntityGeneratedTemplate(ModelRoot model, Table currentTable) : base(model) { _item = currentTable; } #region BaseClassTemplate overrides public override string FileName => $"{_item.PascalName}.Generated.cs"; public string ParentItemName => $"{_item.PascalName}.cs"; public override string FileContent { get => Generate(); } #endregion public override string Generate() { var sb = new StringBuilder(); GenerationHelper.AppendFileGeneatedMessageInCode(sb); sb.AppendLine("#pragma warning disable 612"); this.AppendUsingStatements(sb); sb.AppendLine($"namespace {this.GetLocalNamespace()}.Entity"); sb.AppendLine("{"); this.AppendEntityClass(sb); sb.AppendLine("}"); sb.AppendLine(); sb.AppendLine("#pragma warning restore 612"); sb.AppendLine(); return sb.ToString(); } private void AppendUsingStatements(StringBuilder sb) { sb.AppendLine("using System;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.ComponentModel;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using System.ComponentModel.DataAnnotations;"); sb.AppendLine(); } private void AppendEntityClass(StringBuilder sb) { var doubleDerivedClassName = _item.PascalName; if (_item.GeneratesDoubleDerived) { doubleDerivedClassName = $"{_item.PascalName}Base"; sb.AppendLine(" /// <summary>"); if (_item.Description.IsEmpty()) sb.AppendLine($" /// The '{_item.PascalName}' entity"); else StringHelper.LineBreakCode(sb, _item.Description, " /// "); sb.AppendLine(" /// </summary>"); sb.AppendLine($" [System.CodeDom.Compiler.GeneratedCode(\"nHydrate\", \"{_model.ModelToolVersion}\")]"); sb.Append($" public partial class {_item.PascalName} : {doubleDerivedClassName}, System.ICloneable"); //If we can add this item then implement the ICreatable interface if (!_item.AssociativeTable && !_item.Immutable) sb.Append($", {this.GetLocalNamespace()}.ICreatable"); sb.AppendLine(); sb.AppendLine(" {"); this.AppendClone(sb); sb.AppendLine(" }"); sb.AppendLine(); } var tenantInfo = _item.IsTenant ? " (Tenant Table)" : string.Empty; sb.AppendLine(" /// <summary>"); if (_item.GeneratesDoubleDerived) sb.AppendLine($" /// The base for the double derived '{_item.PascalName}' entity"); else sb.AppendLine($" /// The '{_item.PascalName}' entity{tenantInfo}"); if (!_item.Description.IsEmpty()) sb.AppendLine(" /// " + _item.Description); sb.AppendLine(" /// </summary>"); if (!_item.Description.IsEmpty()) sb.AppendLine($" [System.ComponentModel.Description(\"{_item.Description}\")]"); sb.AppendLine($" [System.CodeDom.Compiler.GeneratedCode(\"nHydrate\", \"{_model.ModelToolVersion}\")]"); sb.AppendLine($" [FieldNameConstants(typeof({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants))]"); //For type tables add special attribute if (_item.IsTypedTable()) { sb.AppendLine($" [StaticData(typeof({this.GetLocalNamespace()}.{_item.PascalName}Constants))]"); } if (_item.Immutable) // && _item.TypedTable == TypedTableConstants.None sb.AppendLine(" [System.ComponentModel.ImmutableObject(true)]"); if (!_item.PrimaryKeyColumns.Any()) sb.AppendLine(" [HasNoKey]"); var boInterface = this.GetLocalNamespace() + ".IBusinessObject"; if (_item.Immutable) boInterface = $"{this.GetLocalNamespace()}.IReadOnlyBusinessObject"; if (_item.IsTenant) { sb.AppendLine(" [TenantEntity]"); boInterface += ", ITenantEntity"; } sb.Append(" public " + (_item.GeneratesDoubleDerived ? "abstract " : "") + "partial class " + doubleDerivedClassName + " : " + boInterface); if (!_item.GeneratesDoubleDerived) sb.Append(", System.ICloneable"); if (_item.AllowCreateAudit || _item.AllowModifiedAudit || _item.AllowConcurrencyCheck) sb.Append($", {this.GetLocalNamespace()}.IAuditable"); //If we can add this item then implement the ICreatable interface if (!_item.AssociativeTable && !_item.Immutable && !_item.GeneratesDoubleDerived) sb.Append($", {this.GetLocalNamespace()}.ICreatable"); sb.AppendLine(); sb.AppendLine(" {"); this.AppendedFieldEnum(sb); this.AppendConstructors(sb); this.AppendProperties(sb); this.AppendGenerateEvents(sb); this.AppendRegionBusinessObject(sb); if (!_item.GeneratesDoubleDerived) this.AppendClone(sb); this.AppendRegionGetValue(sb); this.AppendRegionSetValue(sb); this.AppendNavigationProperties(sb); this.AppendIAuditable(sb); this.AppendIEquatable(sb); sb.AppendLine(" }"); } private void AppendedFieldEnum(StringBuilder sb) { var imageColumnList = _item.GetColumnsByType(System.Data.SqlDbType.Image).OrderBy(x => x.Name).ToList(); if (imageColumnList.Count != 0) { sb.AppendLine(" #region FieldImageConstants Enumeration"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// An enumeration of this object's image type fields"); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public enum FieldImageConstants"); sb.AppendLine(" {"); foreach (var column in imageColumnList) { sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Field mapping for the image parameter '{column.PascalName}' property" + (column.PascalName != column.DatabaseName ? " (Database column: " + column.DatabaseName + ")" : string.Empty)); sb.AppendLine(" /// </summary>"); sb.AppendLine($" [System.ComponentModel.Description(\"Field mapping for the image parameter '{column.PascalName}' property\")]"); sb.AppendLine($" {column.PascalName},"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); } sb.AppendLine(" public readonly struct MaxLengthValues"); sb.AppendLine(" {"); foreach (var column in _item.GetColumns().Where(x => x.DataType.IsTextType())) { var length = column.Length == 0 ? "int.MaxValue" : $"{column.Length}"; sb.AppendLine($" public const int {column.PascalName} = {length};"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #region FieldNameConstants Enumeration"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Enumeration to define each property that maps to a database field for the '{_item.PascalName}' table."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public enum FieldNameConstants"); sb.AppendLine(" {"); foreach (var column in _item.GetColumns()) { sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Field mapping for the '{column.PascalName}' property" + (column.PascalName != column.DatabaseName ? " (Database column: " + column.DatabaseName + ")" : string.Empty)); sb.AppendLine(" /// </summary>"); if (column.PrimaryKey) { sb.AppendLine(" [System.ComponentModel.DataAnnotations.Key]"); } if (column.PrimaryKey || _item.Immutable || column.IsReadOnly) { sb.AppendLine(" [System.ComponentModel.DataAnnotations.Editable(false)]"); } sb.AppendLine($" [System.ComponentModel.Description(\"Field mapping for the '{column.PascalName}' property\")]"); sb.AppendLine($" {column.PascalName},"); } if (_item.AllowCreateAudit) { sb.AppendLine($" /// <summary>"); sb.AppendLine($" /// Field mapping for the '{_model.Database.CreatedByPascalName}' property"); sb.AppendLine($" /// </summary>"); sb.AppendLine($" [System.ComponentModel.Description(\"Field mapping for the '{_model.Database.CreatedByPascalName}' property\")]"); sb.AppendLine($" {_model.Database.CreatedByPascalName},"); sb.AppendLine($" /// <summary>"); sb.AppendLine($" /// Field mapping for the '{_model.Database.CreatedDatePascalName}' property"); sb.AppendLine($" /// </summary>"); sb.AppendLine($" [System.ComponentModel.Description(\"Field mapping for the '{_model.Database.CreatedDatePascalName}' property\")]"); sb.AppendLine($" " + _model.Database.CreatedDatePascalName + ","); } if (_item.AllowModifiedAudit) { sb.AppendLine($" /// <summary>"); sb.AppendLine($" /// Field mapping for the '{_model.Database.ModifiedByPascalName}' property"); sb.AppendLine($" /// </summary>"); sb.AppendLine($" [System.ComponentModel.Description(\"Field mapping for the '{_model.Database.ModifiedByPascalName}' property\")]"); sb.AppendLine($" {_model.Database.ModifiedByPascalName},"); sb.AppendLine($" /// <summary>"); sb.AppendLine($" /// Field mapping for the '{_model.Database.ModifiedDatePascalName}' property"); sb.AppendLine($" /// </summary>"); sb.AppendLine($" [System.ComponentModel.Description(\"Field mapping for the '{_model.Database.ModifiedDatePascalName}' property\")]"); sb.AppendLine($" {_model.Database.ModifiedDatePascalName},"); } sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(); } private void AppendConstructors(StringBuilder sb) { var scope = "public"; if (_item.Immutable) // || _item.AssociativeTable scope = "protected internal"; //For now only create constructor for Immutable //Let user create default constructor if needed //if (!_item.Immutable && !_item.AssociativeTable) // return; var doubleDerivedClassName = _item.PascalName; if (_item.GeneratesDoubleDerived) doubleDerivedClassName = _item.PascalName + "Base"; sb.AppendLine(" #region Constructors"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Initializes a new instance of the {_item.PascalName} entity"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" {scope} {doubleDerivedClassName}()"); sb.AppendLine(" {"); sb.Append(this.SetInitialValues("this")); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); } private void AppendClone(StringBuilder sb) { sb.AppendLine(" #region Clone"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Creates a shallow copy of this object"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" object ICloneable.Clone() => {this.GetLocalNamespace()}.Entity.{_item.PascalName}.Clone(this);"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Creates a shallow copy of this object"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static {_item.PascalName} Clone({this.GetLocalNamespace()}.Entity.{_item.PascalName} item)"); sb.AppendLine(" {"); sb.AppendLine($" var newItem = new {_item.PascalName}();"); foreach (var column in _item.GetColumns().OrderBy(x => x.Name)) { sb.AppendLine($" newItem.{column.PascalName} = item.{column.PascalName};"); } if (_item.AllowCreateAudit) { sb.AppendLine($" newItem.{_model.Database.CreatedDatePascalName} = item.{_model.Database.CreatedDatePascalName};"); sb.AppendLine($" newItem.{_model.Database.CreatedByPascalName} = item.{_model.Database.CreatedByPascalName};"); } if (_item.AllowModifiedAudit) { sb.AppendLine($" newItem.{_model.Database.ModifiedDatePascalName} = item.{_model.Database.ModifiedDatePascalName};"); sb.AppendLine($" newItem.{_model.Database.ModifiedByPascalName} = item.{_model.Database.ModifiedByPascalName};"); } sb.AppendLine(" return newItem;"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); } private void AppendProperties(StringBuilder sb) { sb.AppendLine(" #region Properties"); sb.AppendLine(); foreach (var column in _item.GetColumns().OrderBy(x => x.Name)) { Table typeTable = null; if (_item.IsColumnRelatedToTypeTable(column, out var pascalRoleName) || (column.PrimaryKey && _item.IsTypedTable())) { typeTable = _item.GetRelatedTypeTableByColumn(column, out pascalRoleName); if (typeTable == null) typeTable = _item; if (typeTable != null) { var nullSuffix = string.Empty; if (column.AllowNull) nullSuffix = "?"; sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// This property is a wrapper for the typed enumeration for the '{column.PascalName}' field."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" [System.ComponentModel.DataAnnotations.Schema.NotMapped()]"); sb.AppendLine(" [System.Diagnostics.DebuggerNonUserCode()]"); if (column.Obsolete) sb.AppendLine(" [System.Obsolete()]"); sb.AppendLine($" public virtual {this.GetLocalNamespace()}.{typeTable.PascalName}Constants{nullSuffix} {pascalRoleName}{typeTable.PascalName}Value"); sb.AppendLine(" {"); sb.AppendLine(" get { return (" + this.GetLocalNamespace() + "." + typeTable.PascalName + "Constants" + nullSuffix + ")this." + column.PascalName + "; }"); sb.AppendLine(" set { this." + column.PascalName + " = (" + column.GetCodeType(true) + ")value; }"); sb.AppendLine(" }"); sb.AppendLine(); } } sb.AppendLine(" /// <summary>"); if (!column.Description.IsEmpty()) StringHelper.LineBreakCode(sb, column.Description, " /// "); else sb.AppendLine($" /// The property that maps back to the database '{column.ParentTable.DatabaseName}.{column.DatabaseName}' field."); //If this field has a related convenience property then explain it if (typeTable != null) { sb.AppendLine($" /// This property has an additional enumeration wrapper property {pascalRoleName}{typeTable.PascalName}Value. Use it as a strongly-typed property."); } else if (column.PrimaryKey && _item.IsTypedTable()) { sb.AppendLine($" /// This property has an additional enumeration wrapper property {pascalRoleName}{typeTable.PascalName}Value. Use it as a strongly-typed property."); } sb.AppendLine(" /// </summary>"); sb.AppendLine($" /// <remarks>{column.GetIntellisenseRemarks()}</remarks>"); sb.AppendLine($" [System.ComponentModel.DataAnnotations.Display(Name = \"{column.Name}\")]"); if (column.ComputedColumn || column.IsReadOnly) sb.AppendLine(" [System.ComponentModel.DataAnnotations.Editable(false)]"); if (!column.Description.IsEmpty()) sb.AppendLine($" [System.ComponentModel.Description(\"{StringHelper.ConvertTextToSingleLineCodeString(column.Description)}\")]"); if (column.DataType.IsTextType() && column.IsMaxLength()) sb.AppendLine(" [StringLengthUnbounded]"); else if (column.DataType.IsTextType() && !column.IsMaxLength()) sb.AppendLine($" [System.ComponentModel.DataAnnotations.StringLength(MaxLengthValues.{column.PascalName})]"); sb.AppendLine(" [System.Diagnostics.DebuggerNonUserCode()]"); if (column.Obsolete) sb.AppendLine(" [System.Obsolete()]"); //if (column.IdentityDatabase()) // sb.AppendLine(" [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]"); //if (column.IsTextType && column.DataType != System.Data.SqlDbType.Xml && column.Length > 0) //{ // sb.AppendLine(" [StringLength(" + column.Length + ")]"); //} //if (column.ComputedColumn) // sb.AppendLine(" [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Computed)]"); var typeTableAttr = string.Empty; var propertySetterScope = string.Empty; if (column.ComputedColumn) propertySetterScope = "protected internal "; else if (_item.Immutable && !_item.IsTypedTable()) propertySetterScope = "protected internal "; else if (_item.IsTypedTable() && StringHelper.Match(_item.GetTypeTableCodeDescription(), column.CamelName, true)) { propertySetterScope = "protected internal "; typeTableAttr = "[StaticDataNameField]"; } else if (column.IdentityDatabase()) propertySetterScope = "protected internal "; else if (column.IsReadOnly) propertySetterScope = "protected internal "; var codeType = column.GetCodeType(); //For type tables add attributes to the PK if (_item.IsTypedTable() && column.PrimaryKey) { sb.AppendLine(" [Key]"); sb.AppendLine(" [StaticDataIdField]"); } else if (!typeTableAttr.IsEmpty()) { sb.AppendLine(" [StaticDataNameField]"); } sb.AppendLine($" public virtual {codeType} {column.PascalName}"); sb.AppendLine(" {"); sb.AppendLine(" get { return _" + column.CamelName + "; }"); sb.AppendLine($" {propertySetterScope}set"); sb.AppendLine(" {"); #region Validation //Only perform null check for text types if (!column.AllowNull && column.DataType.IsTextType()) { sb.AppendLine(" if (value == null) throw new Exception(GlobalValues.ERROR_PROPERTY_SETNULL);"); } //Error Check for field size if (column.DataType.IsTextType()) { sb.Append($" if ((value != null) && (value.Length > GetMaxLength({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{column.PascalName})))"); sb.AppendLine($" throw new Exception(string.Format(GlobalValues.ERROR_DATA_TOO_BIG, value, \"{_item.PascalName}.{column.PascalName}\", GetMaxLength({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{column.PascalName})));"); } else if (column.DataType == System.Data.SqlDbType.DateTime) { //Error check date value sb.AppendLine(" if (" + (column.AllowNull ? "(value != null) && " : "") + $"(value < GlobalValues.MIN_DATETIME)) throw new Exception(\"The DateTime value '{column.PascalName}' (\" + value" + (column.AllowNull ? ".Value" : "") + ".ToString(\"yyyy-MM-dd HH:mm:ss\") + \") cannot be less than \" + GlobalValues.MIN_DATETIME.ToString());"); sb.AppendLine(" if (" + (column.AllowNull ? "(value != null) && " : "") + $"(value > GlobalValues.MAX_DATETIME)) throw new Exception(\"The DateTime value '{column.PascalName}' (\" + value" + (column.AllowNull ? ".Value" : "") + ".ToString(\"yyyy-MM-dd HH:mm:ss\") + \") cannot be greater than \" + GlobalValues.MAX_DATETIME.ToString());"); } else if (column.DataType.IsBinaryType()) { sb.Append($" if ((value != null) && (value.Length > GetMaxLength({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{column.PascalName})))"); sb.AppendLine($" throw new Exception(string.Format(GlobalValues.ERROR_DATA_TOO_BIG, value, \"{_item.PascalName}.{column.PascalName}\", GetMaxLength({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{column.PascalName})));"); } //If this column is related to a type table then add additional validation if (typeTable != null) { if (column.AllowNull) sb.AppendLine(" if (value != null) {"); sb.AppendLine(" //Error check the wrapped enumeration"); sb.AppendLine(" switch(value)"); sb.AppendLine(" {"); foreach (RowEntry rowEntry in typeTable.StaticData) { var idValue = rowEntry.GetCodeIdValue(typeTable); sb.AppendLine($" case {idValue}:"); } sb.AppendLine(" break;"); sb.AppendLine($" default: throw new Exception(string.Format(GlobalValues.ERROR_INVALID_ENUM, value.ToString(), \"{_item.PascalName}.{column.PascalName}\"));"); sb.AppendLine(" }"); if (column.AllowNull) sb.AppendLine(" }"); sb.AppendLine(); } //Do not process the setter if the value is NOT changing sb.AppendLine($" if (value == _{column.CamelName}) return;"); #endregion sb.AppendLine($" _{column.CamelName} = value;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); } if (_item.IsTenant) { sb.AppendLine(" [Required]"); sb.AppendLine(" [MaxLength(50)]"); sb.AppendLine($" protected virtual string {_model.TenantColumnName} {GetSetSuffix}"); sb.AppendLine(" string ITenantEntity.TenantId { get => this." + _model.TenantColumnName + "; }"); sb.AppendLine(); } //Audit Fields if (_item.AllowCreateAudit) GenerateAuditField(sb, _model.Database.CreatedByPascalName, "string", "The audit field for the 'Created By' parameter.", "public", "AuditCreatedBy"); if (_item.AllowCreateAudit) GenerateAuditField(sb, _model.Database.CreatedDatePascalName, "DateTime", "The audit field for the 'Created Date' parameter.", "public", "AuditCreatedDate(utc: " + (_model.UseUTCTime ? "true" : "false") + ")"); if (_item.AllowModifiedAudit) GenerateAuditField(sb, _model.Database.ModifiedByPascalName, "string", "The audit field for the 'Modified By' parameter.", "public", "AuditModifiedBy"); if (_item.AllowModifiedAudit) GenerateAuditField(sb, _model.Database.ModifiedDatePascalName, "DateTime", "The audit field for the 'Modified Date' parameter.", "public", "AuditModifiedDate(utc: " + (_model.UseUTCTime ? "true" : "false") + ")"); if (_item.AllowConcurrencyCheck) GenerateAuditField(sb, _model.Database.ConcurrencyCheckPascalName, "int", "The audit field for the 'Timestamp' parameter.", "protected internal", "AuditTimestamp", true); sb.AppendLine(" #endregion"); sb.AppendLine(); } private void AppendNavigationProperties(StringBuilder sb) { sb.AppendLine(" #region Navigation Properties"); sb.AppendLine(); #region Parent Relations { var relationList = _item.GetRelations().Where(x => x.IsValidEFRelation).OrderBy(x => x.ParentTable.Name).ThenBy(x => x.ChildTable.Name); foreach (var relation in relationList.OrderBy(x => x.ParentTable.Name).ThenBy(x => x.ChildTable.Name).ThenBy(x => x.RoleName)) { var parentTable = relation.ParentTable; var childTable = relation.ChildTable; //1-1 relations if (relation.IsOneToOne) { sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// The navigation definition for walking {_item.PascalName}->{childTable.PascalName}" + relation.PascalRoleName.IfExistsReturn($" (role: '{relation.PascalRoleName}') (Multiplicity 1:1)")); sb.AppendLine(" /// </summary>"); //sb.AppendLine(" [System.ComponentModel.DataAnnotations.Schema.NotMapped()]"); sb.AppendLine($" public virtual {childTable.PascalName} {relation.PascalRoleName}{childTable.PascalName} {GetSetSuffix}"); sb.AppendLine(); } //Process the associative tables else if (childTable.AssociativeTable) { var associativeRelations = childTable.GetRelationsWhereChild(); Relation targetRelation = null; Relation otherRelation = null; var relation1 = associativeRelations.First(); var relation2 = associativeRelations.Last(); if (_item == relation1.ParentTable) targetRelation = relation2; else targetRelation = relation1; if (targetRelation == relation2) otherRelation = relation1; else otherRelation = relation2; var targetTable = targetRelation.ParentTable; if (!targetTable.IsEnumOnly()) { sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// The navigation definition for walking {_item.PascalName}->{childTable.PascalName}" + otherRelation.PascalRoleName.IfExistsReturn($" (role: '{otherRelation.PascalRoleName}') (Multiplicity M:N)")); sb.AppendLine(" /// </summary>"); // This was "protected internal" however there are times that a navigation property is needed sb.AppendLine($" public virtual ICollection<{this.GetLocalNamespace()}.Entity.{childTable.PascalName}> {otherRelation.PascalRoleName}{childTable.PascalName}List" + " { get; set; }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Gets a readonly list of associated {targetRelation.ParentTable.PascalName} entities for this many-to-many relationship"); sb.AppendLine(" /// </summary>"); sb.AppendLine(" [System.ComponentModel.DataAnnotations.Schema.NotMapped()]"); sb.AppendLine($" public IList<{this.GetLocalNamespace()}.Entity.{targetRelation.ParentTable.PascalName}> Associated{targetRelation.ParentTable.PascalName}List"); sb.AppendLine(" {"); sb.AppendLine(" get { return this." + otherRelation.PascalRoleName + childTable.PascalName + "List?.Select(x => x." + targetRelation.PascalRoleName + targetRelation.ParentTable.PascalName + ").ToList(); }"); sb.AppendLine(" }"); sb.AppendLine(); } } //Process relations where Current Table is the parent else if (parentTable == _item && !childTable.IsEnumOnly() && !childTable.AssociativeTable) { sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// The navigation definition for walking {parentTable.PascalName}->{childTable.PascalName}" + relation.PascalRoleName.IfExistsReturn($" (role: '{relation.PascalRoleName}') (Multiplicity 1:N)")); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public virtual ICollection<{this.GetLocalNamespace()}.Entity.{childTable.PascalName}> {relation.PascalRoleName}{childTable.PascalName}List" + " { get; set; }"); sb.AppendLine(); } } } #endregion #region Child Relations { var relationList = _item.GetRelationsWhereChild().Where(x => x.IsValidEFRelation).AsEnumerable(); foreach (var relation in relationList.OrderBy(x => x.ParentTable.Name).ThenBy(x => x.ChildTable.Name).ThenBy(x => x.RoleName)) { var parentTable = relation.ParentTable; var childTable = relation.ChildTable; //Do not walk to associative if ((parentTable.IsEnumOnly()) || (childTable.IsEnumOnly())) { //Do Nothing } //Process relations where Current Table is the child else if (childTable == _item && !parentTable.IsInheritedFrom(_item)) { sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// The navigation definition for walking {parentTable.PascalName}->{childTable.PascalName}" + relation.PascalRoleName.IfExistsReturn($" (role: '{relation.PascalRoleName}') (Multiplicity 1:N)")); sb.AppendLine(" /// </summary>"); //sb.AppendLine(" [System.ComponentModel.DataAnnotations.Schema.NotMapped()]"); sb.AppendLine($" public virtual {parentTable.PascalName} {relation.PascalRoleName}{parentTable.PascalName} {GetSetSuffix}"); sb.AppendLine(); } } } #endregion sb.AppendLine(" #endregion"); sb.AppendLine(); } private void AppendGenerateEvents(StringBuilder sb) { sb.AppendLine(" #region Property Holders"); sb.AppendLine(); foreach (var column in _item.GetColumns().OrderBy(x => x.Name)) { sb.AppendLine(" /// <summary />"); sb.AppendLine($" protected {column.GetCodeType()} _{column.CamelName};"); } sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); } private void AppendRegionBusinessObject(StringBuilder sb) { sb.AppendLine(" #region GetMaxLength"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Gets the maximum size of the field value."); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static int GetMaxLength({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants field)"); sb.AppendLine(" {"); sb.AppendLine(" switch (field)"); sb.AppendLine(" {"); foreach (var column in _item.GetColumns().OrderBy(x => x.Name)) { sb.AppendLine($" case {this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{column.PascalName}:"); if (_item.GetColumns().Contains(column)) { //This is an actual column in this table switch (column.DataType) { case System.Data.SqlDbType.Text: sb.AppendLine(" return int.MaxValue;"); break; case System.Data.SqlDbType.NText: sb.AppendLine(" return int.MaxValue;"); break; case System.Data.SqlDbType.Image: case System.Data.SqlDbType.VarBinary: case System.Data.SqlDbType.Binary: sb.AppendLine(" return int.MaxValue;"); break; case System.Data.SqlDbType.Xml: sb.AppendLine(" return int.MaxValue;"); break; case System.Data.SqlDbType.Char: case System.Data.SqlDbType.NChar: case System.Data.SqlDbType.NVarChar: case System.Data.SqlDbType.VarChar: if ((column.Length == 0) && (column.DataType.SupportsMax())) sb.AppendLine(" return int.MaxValue;"); else sb.AppendLine($" return MaxLengthValues.{column.PascalName};"); break; default: sb.AppendLine($" return 0; //Type={column.DataType}"); break; } } } sb.AppendLine(" }"); sb.AppendLine(" return 0;"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine($" int {this.GetLocalNamespace()}.IReadOnlyBusinessObject.GetMaxLength(Enum field) => GetMaxLength(({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants)field);"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); sb.AppendLine(" #region GetFieldNameConstants"); sb.AppendLine(); sb.AppendLine($" System.Type {this.GetLocalNamespace()}.IReadOnlyBusinessObject.GetFieldNameConstants() => typeof({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants);"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); //GetValue sb.AppendLine(" #region Get/Set Value"); sb.AppendLine(); sb.AppendLine($" object {this.GetLocalNamespace()}.IReadOnlyBusinessObject.GetValue(System.Enum field)"); sb.AppendLine(" {"); sb.AppendLine($" return (({this.GetLocalNamespace()}.IReadOnlyBusinessObject)this).GetValue(field, null);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine($" object {this.GetLocalNamespace()}.IReadOnlyBusinessObject.GetValue(System.Enum field, object defaultValue)"); sb.AppendLine(" {"); sb.AppendLine($" if (field.GetType() != typeof({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants))"); sb.AppendLine($" throw new Exception(\"The field parameter must be of type '{this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants'.\");"); sb.AppendLine($" return this.GetValue(({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants)field, defaultValue);"); sb.AppendLine(" }"); sb.AppendLine(); if (!_item.Immutable) { sb.AppendLine($" void {this.GetLocalNamespace()}.IBusinessObject.SetValue(System.Enum field, object newValue)"); sb.AppendLine(" {"); sb.AppendLine($" if (field.GetType() != typeof({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants))"); sb.AppendLine($" throw new Exception(\"The field parameter must be of type '{this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants'.\");"); sb.AppendLine($" this.SetValue(({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants)field, newValue);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine($" void {this.GetLocalNamespace()}.IBusinessObject.SetValue(System.Enum field, object newValue, bool fixLength)"); sb.AppendLine(" {"); sb.AppendLine($" if (field.GetType() != typeof({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants))"); sb.AppendLine($" throw new Exception(\"The field parameter must be of type '{this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants'.\");"); sb.AppendLine($" this.SetValue(({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants)field, newValue, fixLength);"); sb.AppendLine(" }"); sb.AppendLine(); } sb.AppendLine(" #endregion"); sb.AppendLine(); //If this is not derived then add the Primary key stuff var pkList = string.Join(",", _item.PrimaryKeyColumns.OrderBy(x => x.Name).Select(x => "this." + x.PascalName).ToList()); sb.AppendLine(" #region PrimaryKey"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Generic primary key for this object"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" {this.GetLocalNamespace()}.IPrimaryKey {this.GetLocalNamespace()}.IReadOnlyBusinessObject.PrimaryKey"); sb.AppendLine(" {"); sb.AppendLine(" get { return new PrimaryKey(Util.HashPK(\"" + _item.PascalName + "\", " + pkList + ")); }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); } private string SetInitialValues(string propertyObjectPrefix) { //TODO - Audit Trail not implemented var setOriginalGuid = String.Format("\t\t\t" + propertyObjectPrefix + "._{0} = System.Guid.NewGuid();", _item.PrimaryKeyColumns.First().CamelName); var returnVal = new StringBuilder(); if (_item.PrimaryKeyColumns.Count == 1 && _item.PrimaryKeyColumns.First().DataType == System.Data.SqlDbType.UniqueIdentifier) { if (_item.PrimaryKeyColumns.First().DataType == System.Data.SqlDbType.UniqueIdentifier) returnVal.AppendLine(setOriginalGuid); } //DEFAULT PROPERTIES START foreach (var column in _item.GetColumns().Where(x => x.DataType != System.Data.SqlDbType.Timestamp).ToList()) { if (!column.Default.IsEmpty()) { var defaultValue = column.GetCodeDefault(); //Write the actual code if (!defaultValue.IsEmpty()) returnVal.AppendLine($" {propertyObjectPrefix}._{column.CamelName} = {defaultValue};"); } } //DEFAULT PROPERTIES END return returnVal.ToString(); } private void AppendRegionGetValue(StringBuilder sb) { sb.AppendLine(" #region GetValue"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Gets the value of one of this object's properties."); sb.AppendLine(" /// </summary>"); sb.AppendLine($" protected virtual object GetValue({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants field)"); sb.AppendLine(" {"); sb.AppendLine(" return GetValue(field, null);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Gets the value of one of this object's properties."); sb.AppendLine(" /// </summary>"); sb.AppendLine($" protected virtual object GetValue({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants field, object defaultValue)"); sb.AppendLine(" {"); var allColumns = _item.GetColumns().ToList(); foreach (var column in allColumns.OrderBy(x => x.Name)) { var relationParentTable = column.ParentTable; var childColumnList = relationParentTable.AllRelationships.FindByChildColumn(column); sb.AppendLine($" if (field == {this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{column.PascalName})"); if (column.AllowNull) sb.AppendLine($" return ((this.{column.PascalName} == null) ? defaultValue : this.{column.PascalName});"); else sb.AppendLine($" return this.{column.PascalName};"); } if (_item.AllowCreateAudit) { sb.AppendLine($" if (field == {this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{_model.Database.CreatedByPascalName})"); sb.AppendLine($" return ((this.{_model.Database.CreatedByPascalName} == null) ? defaultValue : this.{_model.Database.CreatedByPascalName});"); sb.AppendLine($" if (field == {this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{_model.Database.CreatedDatePascalName})"); sb.AppendLine($" return this.{_model.Database.CreatedDatePascalName};"); } if (_item.AllowModifiedAudit) { sb.AppendLine($" if (field == {this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{_model.Database.ModifiedByPascalName})"); sb.AppendLine($" return ((this.{_model.Database.ModifiedByPascalName} == null) ? defaultValue : this.{_model.Database.ModifiedByPascalName});"); sb.AppendLine($" if (field == {this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{_model.Database.ModifiedDatePascalName})"); sb.AppendLine($" return this.{_model.Database.ModifiedDatePascalName};"); } //Now do the primary keys foreach (var dbColumn in _item.PrimaryKeyColumns.OrderBy(x => x.Name)) { //TODO } sb.AppendLine(" throw new Exception(\"Field '\" + field.ToString() + \"' not found!\");"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); } private void AppendRegionSetValue(StringBuilder sb) { if (_item.Immutable) return; sb.AppendLine(" #region SetValue"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Assigns a value to a field on this object."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"field\">The field to set</param>"); sb.AppendLine(" /// <param name=\"newValue\">The new value to assign to the field</param>"); sb.AppendLine($" protected virtual void SetValue({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants field, object newValue)"); sb.AppendLine(" {"); sb.AppendLine(" SetValue(field, newValue, false);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Assigns a value to a field on this object."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"field\">The field to set</param>"); sb.AppendLine(" /// <param name=\"newValue\">The new value to assign to the field</param>"); sb.AppendLine(" /// <param name=\"fixLength\">Determines if the length should be truncated if too long. When false, an error will be raised if data is too large to be assigned to the field.</param>"); sb.AppendLine($" protected virtual void SetValue({this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants field, object newValue, bool fixLength)"); sb.AppendLine(" {"); var allColumns = _item.GetColumns().ToList(); var count = 0; foreach (var column in allColumns.OrderBy(x => x.Name)) { //If not the first one, add an 'ELSE' for speed if (count == 0) sb.Append(" "); else sb.Append(" else "); sb.AppendLine($"if (field == {this.GetLocalNamespace()}.Entity.{_item.PascalName}.FieldNameConstants.{column.PascalName})"); sb.AppendLine(" {"); if (column.PrimaryKey) { sb.AppendLine(" throw new Exception(\"Field '\" + field.ToString() + \"' is a primary key and cannot be set!\");"); } else if (column.ComputedColumn) { sb.AppendLine(" throw new Exception(\"Field '\" + field.ToString() + \"' is a computed parameter and cannot be set!\");"); } else if (column.IsReadOnly) { sb.AppendLine(" throw new Exception(\"Field '\" + field.ToString() + \"' is a read-only parameter and cannot be set!\");"); } else { if (column.DataType.IsTextType()) { sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperInternal((string)newValue, fixLength, GetMaxLength(field));"); } else if (column.DataType == System.Data.SqlDbType.Float) { if (column.AllowNull) sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperDoubleNullableInternal(newValue);"); else sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperDoubleNotNullableInternal(newValue, \"Field '{column.PascalName}' does not allow null values!\");"); } else if (column.DataType.IsDateType()) { if (column.AllowNull) sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperDateTimeNullableInternal(newValue);"); else sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperDateTimeNotNullableInternal(newValue, \"Field '{column.PascalName}' does not allow null values!\");"); } else if (column.DataType == System.Data.SqlDbType.Bit) { if (column.AllowNull) sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperBoolNullableInternal(newValue);"); else sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperBoolNotNullableInternal(newValue, \"Field '{column.PascalName}' does not allow null values!\");"); } else if (column.DataType == System.Data.SqlDbType.Int) { if (column.AllowNull) sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperIntNullableInternal(newValue);"); else sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperIntNotNullableInternal(newValue, \"Field '{column.PascalName}' does not allow null values!\");"); } else if (column.DataType == System.Data.SqlDbType.BigInt) { if (column.AllowNull) sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperLongNullableInternal(newValue);"); else sb.AppendLine($" this.{column.PascalName} = GlobalValues.SetValueHelperLongNotNullableInternal(newValue, \"Field '{column.PascalName}' does not allow null values!\");"); } else { //All other types sb.AppendLine(" if (newValue == null)"); sb.AppendLine(" {"); if (column.AllowNull) sb.AppendLine($" this.{column.PascalName} = null;"); else sb.AppendLine($" throw new Exception(\"Field '{column.PascalName}' does not allow null values!\");"); sb.AppendLine(" }"); sb.AppendLine(" else"); sb.AppendLine(" {"); var relationParentTable = column.ParentTable; var list = relationParentTable.AllRelationships.FindByChildColumn(column).ToList(); if (list.Count > 0) { var relation = list.First(); var pTable = relation.ParentTable; if (!pTable.IsEnumOnly()) { var cTable = relation.ChildTable; var s = pTable.PascalName; sb.AppendLine($" if (newValue is {this.GetLocalNamespace()}.Entity.{pTable.PascalName})"); sb.AppendLine(" {"); if (column.EnumType == string.Empty) { var columnRelationship = relation.ColumnRelationships.GetByParentField(column); var parentColumn = columnRelationship.ParentColumn; sb.AppendLine($" this.{column.PascalName} = (({this.GetLocalNamespace()}.Entity.{pTable.PascalName})newValue).{parentColumn.PascalName};"); //REMOVE PK FOR NOW //sb.AppendLine(" }"); //sb.AppendLine(" else if (newValue is " + this.GetLocalNamespace() + ".IPrimaryKey)"); //sb.AppendLine(" {"); //sb.AppendLine(" this." + column.PascalName + " = ((" + this.GetLocalNamespace() + ".Entity." + pTable.PascalName + "PrimaryKey)newValue)." + parentColumn.PascalName + ";"); } else //This is an Enumeration type sb.AppendLine($" throw new Exception(\"Field '{column.PascalName}' does not allow values of this type!\");"); sb.AppendLine(" } else"); } } if (column.AllowStringParse) { sb.AppendLine(" if (newValue is string)"); sb.AppendLine(" {"); if (column.EnumType == "") { sb.AppendLine($" this.{column.PascalName} = " + column.GetCodeType(false) + ".Parse((string)newValue);"); sb.AppendLine(" } else if (!(newValue is " + column.GetCodeType() + ")) {"); if (column.GetCodeType() == "int") sb.AppendLine($" this.{column.PascalName} = Convert.ToInt32(newValue);"); else sb.AppendLine($" this.{column.PascalName} = " + column.GetCodeType(false) + ".Parse(newValue.ToString());"); } else //This is an Enumeration type { sb.AppendLine($" this.{column.PascalName} = (" + column.EnumType + ")Enum.Parse(typeof(" + column.EnumType + "), newValue.ToString());"); } sb.AppendLine(" }"); sb.AppendLine($" else if (newValue is {this.GetLocalNamespace()}.IBusinessObject)"); sb.AppendLine(" {"); sb.AppendLine(" throw new Exception(\"An invalid object of type 'IBusinessObject' was passed in. Perhaps a relationship was not enforced correctly.\");"); sb.AppendLine(" }"); sb.AppendLine(" else"); } if (column.GetCodeType() == "string") sb.AppendLine($" this.{column.PascalName} = newValue.ToString();"); else sb.AppendLine($" this.{column.PascalName} = ({column.GetCodeType()})newValue;"); sb.AppendLine(" }"); //sb.AppendLine(" return;"); } //All non-string types } sb.AppendLine(" }"); count++; } sb.AppendLine(" else"); sb.AppendLine(" throw new Exception(\"Field '\" + field.ToString() + \"' not found!\");"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); } private void AppendIEquatable(StringBuilder sb) { sb.AppendLine(" #region Equals"); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Compares two objects of '{_item.PascalName}' type and determines if all properties match"); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <returns>True if all properties match, false otherwise</returns>"); sb.AppendLine(" public override bool Equals(object obj)"); sb.AppendLine(" {"); sb.AppendLine($" var other = obj as {this.GetLocalNamespace()}.Entity.{_item.PascalName};"); sb.AppendLine(" if (other == null) return false;"); sb.AppendLine(" return ("); var allColumns = _item.GetColumns().OrderBy(x => x.Name).ToList(); var index = 0; foreach (var column in allColumns) { sb.Append($" other.{column.PascalName} == this.{column.PascalName}"); if (index < allColumns.Count - 1) sb.Append(" &&"); sb.AppendLine(); index++; } sb.AppendLine(" );"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Serves as a hash function for this type."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public override int GetHashCode() => base.GetHashCode();"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); } private void AppendIAuditable(StringBuilder sb) { if (!_item.AllowCreateAudit && !_item.AllowModifiedAudit && !_item.AllowConcurrencyCheck) return; sb.AppendLine(" #region Auditing"); sb.AppendLine($" string {this.GetLocalNamespace()}.IAuditable.CreatedBy"); sb.AppendLine(" {"); if (_item.AllowCreateAudit) { sb.AppendLine(" get { return this." + _model.Database.CreatedByPascalName + "; }"); sb.AppendLine(" set { this." + _model.Database.CreatedByPascalName + " = value; }"); } else { sb.AppendLine(" get { return null; }"); sb.AppendLine(" set { }"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine($" System.DateTime? {this.GetLocalNamespace()}.IAuditable.CreatedDate"); sb.AppendLine(" {"); if (_item.AllowCreateAudit) { sb.AppendLine(" get { return this." + _model.Database.CreatedDatePascalName + "; }"); sb.AppendLine(" set { if (value == null) throw new Exception(\"Invalid Date\"); this." + _model.Database.CreatedDatePascalName + " = (DateTime)value; }"); } else { sb.AppendLine(" get { return null; }"); sb.AppendLine(" set { }"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine($" string {this.GetLocalNamespace()}.IAuditable.ModifiedBy"); sb.AppendLine(" {"); if (_item.AllowModifiedAudit) { sb.AppendLine(" get { return this." + _model.Database.ModifiedByPascalName + "; }"); sb.AppendLine(" set { this." + _model.Database.ModifiedByPascalName + " = value; }"); } else { sb.AppendLine(" get { return null; }"); sb.AppendLine(" set { }"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine($" System.DateTime? {this.GetLocalNamespace()}.IAuditable.ModifiedDate"); sb.AppendLine(" {"); if (_item.AllowModifiedAudit) { sb.AppendLine(" get { return this." + _model.Database.ModifiedDatePascalName + "; }"); sb.AppendLine(" set { if (value == null) throw new Exception(\"Invalid Date\"); this." + _model.Database.ModifiedDatePascalName + " = (DateTime)value; }"); } else { sb.AppendLine(" get { return null; }"); sb.AppendLine(" set { }"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine($" int {this.GetLocalNamespace()}.IAuditable.Concurrency"); sb.AppendLine(" {"); if (_item.AllowConcurrencyCheck) { sb.AppendLine(" get { return this." + _model.Database.ConcurrencyCheckPascalName + "; }"); sb.AppendLine(" set { this." + _model.Database.ConcurrencyCheckPascalName + " = value; }"); } else { sb.AppendLine(" get { return 0; }"); sb.AppendLine(" set { }"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); } private void GenerateAuditField(StringBuilder sb, string columnName, string codeType, string description, string propertyScope, string attributeType, bool isConcurrency = false) { if (!description.IsEmpty()) { sb.AppendLine(" /// <summary>"); StringHelper.LineBreakCode(sb, description, " /// "); sb.AppendLine(" /// </summary>"); } sb.AppendLine(" [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]"); sb.AppendLine(" [System.Diagnostics.DebuggerNonUserCode()]"); if (!attributeType.IsEmpty()) sb.AppendLine($" [{attributeType}]"); var virtualText = " virtual "; if (isConcurrency) { sb.AppendLine(" [System.ComponentModel.DataAnnotations.ConcurrencyCheck()]"); virtualText = " "; //The customer attribute does not work with proxy object } sb.AppendLine($" {propertyScope}{virtualText}{codeType} {columnName}"); sb.AppendLine(" {"); sb.AppendLine(" get { return _" + StringHelper.DatabaseNameToCamelCase(columnName) + "; }"); if (propertyScope == "public") { //Cannot have a property scope and setter scope cannot be explicitly set to same, compile error if (propertyScope == "protected internal") sb.AppendLine(" set"); else sb.AppendLine(" protected internal set"); } else { sb.AppendLine(" set"); } sb.AppendLine(" {"); sb.AppendLine(" _" + StringHelper.DatabaseNameToCamelCase(columnName) + " = value;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary />"); sb.AppendLine(" protected " + codeType + " _" + StringHelper.DatabaseNameToCamelCase(columnName) + ";"); sb.AppendLine(); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.Mail.Net.TCP { #region usings using System; using System.Diagnostics; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; using IO; using Log; #endregion /// <summary> /// This class implements generic TCP client. /// </summary> public class TCP_Client : TCP_Session { #region Delegates /// <summary> /// Internal helper method for asynchronous Connect method. /// </summary> /// <param name="localEP">Local IP end point to use for connect.</param> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> private delegate void BeginConnectEPDelegate(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl); /// <summary> /// Internal helper method for asynchronous Connect method. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> private delegate void BeginConnectHostDelegate(string host, int port, bool ssl); /// <summary> /// Internal helper method for asynchronous Disconnect method. /// </summary> private delegate void DisconnectDelegate(); #endregion #region Members private static readonly Regex IpRegexp = new Regex(@"^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); private DateTime m_ConnectTime; private string m_ID = ""; private bool m_IsConnected; private bool m_IsDisposed; private bool m_IsSecure; private RemoteCertificateValidationCallback m_pCertificateCallback; private IPEndPoint m_pLocalEP; private Logger m_pLogger; private IPEndPoint m_pRemoteEP; private SmartStream m_pTcpStream; private Socket socket; #endregion #region Properties /// <summary> /// Gets the time when session was connected. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override DateTime ConnectTime { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_ConnectTime; } } /// <summary> /// Gets session ID. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override string ID { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_ID; } } /// <summary> /// Gets if TCP client is connected. /// </summary> public override bool IsConnected { get { if (Socket != null) { return Socket.Connected; } return m_IsConnected; } } /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets if this session TCP connection is secure connection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override bool IsSecureConnection { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_IsSecure; } } /// <summary> /// Gets the last time when data was sent or received. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override DateTime LastActivity { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_pTcpStream.LastActivity; } } /// <summary> /// Gets session local IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override IPEndPoint LocalEndPoint { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_pLocalEP; } } /// <summary> /// Gets or sets TCP client logger. Value null means no logging. /// </summary> public Logger Logger { get { return m_pLogger; } set { m_pLogger = value; } } /// <summary> /// Gets session remote IP end point. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override IPEndPoint RemoteEndPoint { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_pRemoteEP; } } /// <summary> /// Gets TCP stream which must be used to send/receive data through this session. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override SmartStream TcpStream { get { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } return m_pTcpStream; } } /// <summary> /// Gets or stes remote callback which is called when remote server certificate needs to be validated. /// Value null means not sepcified. /// </summary> public RemoteCertificateValidationCallback ValidateCertificateCallback { get { return m_pCertificateCallback; } set { m_pCertificateCallback = value; } } public Socket Socket { get { return socket; } set { socket = value; } } #endregion #region Methods /// <summary> /// Cleans up any resources being used. This method is thread-safe. /// </summary> public override void Dispose() { lock (this) { Debug.Print("TCP client disposed"); if (m_IsDisposed) { return; } try { if (IsConnected) { Disconnect(); } } catch {} m_IsDisposed = true; } } /// <summary> /// Starts connection to the specified host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="callback">Callback to call when the connect operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous connection.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginConnect(string host, int port, AsyncCallback callback, object state) { return BeginConnect(host, port, false, callback, state); } /// <summary> /// Starts connection to the specified host. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <param name="callback">Callback to call when the connect operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous connection.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginConnect(string host, int port, bool ssl, AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (IsConnected) { throw new InvalidOperationException("TCP client is already connected."); } if (string.IsNullOrEmpty(host)) { throw new ArgumentException("Argument 'host' value may not be null or empty."); } if (port < 1) { throw new ArgumentException("Argument 'port' value must be >= 1."); } BeginConnectHostDelegate asyncMethod = Connect; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(host, port, ssl, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Starts connection to the specified remote end point. /// </summary> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <param name="callback">Callback to call when the connect operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous connection.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginConnect(IPEndPoint remoteEP, bool ssl, AsyncCallback callback, object state) { return BeginConnect(null, remoteEP, ssl, callback, state); } /// <summary> /// Starts connection to the specified remote end point. /// </summary> /// <param name="localEP">Local IP end point to use for connect.</param> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <param name="callback">Callback to call when the connect operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous connection.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public IAsyncResult BeginConnect(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl, AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (IsConnected) { throw new InvalidOperationException("TCP client is already connected."); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } BeginConnectEPDelegate asyncMethod = Connect; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(localEP, remoteEP, ssl, asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous connection request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when argument <b>asyncResult</b> was not returned by a call to the <b>BeginConnect</b> method.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>EndConnect</b> was previously called for the asynchronous connection.</exception> public void EndConnect(IAsyncResult asyncResult) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginConnect method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "EndConnect was previously called for the asynchronous operation."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is BeginConnectHostDelegate) { ((BeginConnectHostDelegate) castedAsyncResult.AsyncDelegate).EndInvoke( castedAsyncResult.AsyncResult); } else if (castedAsyncResult.AsyncDelegate is BeginConnectEPDelegate) { ((BeginConnectEPDelegate) castedAsyncResult.AsyncDelegate).EndInvoke( castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginConnect method."); } } /// <summary> /// Connects to the specified host. If the hostname resolves to more than one IP address, /// all IP addresses will be tried for connection, until one of them connects. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(string host, int port) { Connect(host, port, false); } /// <summary> /// Connects to the specified host. If the hostname resolves to more than one IP address, /// all IP addresses will be tried for connection, until one of them connects. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(string host, int port, bool ssl) { Connect(host, port, ssl, 30000); } /// <summary> /// Connects to the specified host. If the hostname resolves to more than one IP address, /// all IP addresses will be tried for connection, until one of them connects. /// </summary> /// <param name="host">Host name or IP address.</param> /// <param name="port">Port to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(string host, int port, bool ssl, int timeout) { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (IsConnected) { throw new InvalidOperationException("TCP client is already connected."); } if (string.IsNullOrEmpty(host)) { throw new ArgumentException("Argument 'host' value may not be null or empty."); } if (port < 1) { throw new ArgumentException("Argument 'port' value must be >= 1."); } //Check ip IPAddress[] ips = Dns.GetHostAddresses(host); for (int i = 0; i < ips.Length; i++) { try { Connect(null, new IPEndPoint(ips[i], port), ssl, timeout); break; } catch (Exception x) { if (IsConnected) { throw x; } // Connect failed for specified IP address, if there are some more IPs left, try next, otherwise forward exception. else if (i == (ips.Length - 1)) { throw x; } } } } /// <summary> /// Connects to the specified remote end point. /// </summary> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(IPEndPoint remoteEP, bool ssl) { Connect(null, remoteEP, ssl); } /// <summary> /// Connects to the specified remote end point. /// </summary> /// <param name="localEP">Local IP end point to use for connet.</param> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl) { Connect(localEP, remoteEP, ssl, 30000); } /// <summary> /// Connects to the specified remote end point. /// </summary> /// <param name="localEP">Local IP end point to use for connet.</param> /// <param name="remoteEP">Remote IP end point where to connect.</param> /// <param name="ssl">Specifies if connects to SSL end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is already connected.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void Connect(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl, int timeout) { Debug.Print("TCP client connect"); if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (IsConnected) { throw new InvalidOperationException("TCP client is already connected."); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (Socket != null && Socket.Connected) { Socket.Disconnect(false); Socket.Shutdown(SocketShutdown.Both); } Socket = null; if (remoteEP.AddressFamily == AddressFamily.InterNetwork) { Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } else if (remoteEP.AddressFamily == AddressFamily.InterNetworkV6) { Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); } else { throw new ArgumentException("Remote end point has invalid AddressFamily."); } try { Socket.SendTimeout = timeout; Socket.ReceiveTimeout = timeout; if (localEP != null) { Socket.Bind(localEP); } LogAddText("Connecting to " + remoteEP + "."); Socket.Connect(remoteEP); m_IsConnected = true; m_ID = Guid.NewGuid().ToString(); m_ConnectTime = DateTime.Now; m_pLocalEP = (IPEndPoint) Socket.LocalEndPoint; m_pRemoteEP = (IPEndPoint) Socket.RemoteEndPoint; m_pTcpStream = new SmartStream(new NetworkStream(Socket, true), true); LogAddText("Connected, localEP='" + m_pLocalEP + "'; remoteEP='" + remoteEP + "'."); if (ssl) { SwitchToSecure(); } } catch (Exception x) { LogAddException("Exception: " + x.Message, x); // Switching to secure failed. if (IsConnected) { Disconnect(); } // Bind or connect failed. else { Socket.Close(); } OnError(x); throw x; } OnConnected(); } /// <summary> /// Disconnects connection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public override void Disconnect() { Debug.Print("TCP client disconect"); if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } try { m_pLocalEP = null; m_pRemoteEP = null; m_pTcpStream.Dispose(); LogAddText("Socket disconnecting"); m_IsSecure = false; } catch (Exception) { } } private void DisconnectCallback(IAsyncResult ar) { try { Socket.EndDisconnect(ar); Socket.Close(); m_IsConnected = false; LogAddText("Disconnected."); } catch (Exception) { } } /// <summary> /// Starts disconnecting connection. /// </summary> /// <param name="callback">Callback to call when the asynchronous operation is complete.</param> /// <param name="state">User data.</param> /// <returns>An IAsyncResult that references the asynchronous disconnect.</returns> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception> public IAsyncResult BeginDisconnect(AsyncCallback callback, object state) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } DisconnectDelegate asyncMethod = Disconnect; AsyncResultState asyncState = new AsyncResultState(this, asyncMethod, callback, state); asyncState.SetAsyncResult(asyncMethod.BeginInvoke(asyncState.CompletedCallback, null)); return asyncState; } /// <summary> /// Ends a pending asynchronous disconnect request. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>asyncResult</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when argument <b>asyncResult</b> was not returned by a call to the <b>BeginDisconnect</b> method.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>EndDisconnect</b> was previously called for the asynchronous connection.</exception> public void EndDisconnect(IAsyncResult asyncResult) { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } AsyncResultState castedAsyncResult = asyncResult as AsyncResultState; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginDisconnect method."); } if (castedAsyncResult.IsEndCalled) { throw new InvalidOperationException( "EndDisconnect was previously called for the asynchronous connection."); } castedAsyncResult.IsEndCalled = true; if (castedAsyncResult.AsyncDelegate is DisconnectDelegate) { ((DisconnectDelegate) castedAsyncResult.AsyncDelegate).EndInvoke(castedAsyncResult.AsyncResult); } else { throw new ArgumentException( "Argument asyncResult was not returned by a call to the BeginDisconnect method."); } } #endregion #region Virtual methods /// <summary> /// This method is called after TCP client has sucessfully connected. /// </summary> protected virtual void OnConnected() {} #endregion #region Utility methods private bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // User will handle it. if (m_pCertificateCallback != null) { return m_pCertificateCallback(sender, certificate, chain, sslPolicyErrors); } else { if (sslPolicyErrors == SslPolicyErrors.None || sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch) { return true; } // Do not allow this client to communicate with unauthenticated servers. return false; } } #endregion /// <summary> /// Switches session to secure connection. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected or is already secure.</exception> protected void SwitchToSecure() { if (m_IsDisposed) { throw new ObjectDisposedException("TCP_Client"); } if (!IsConnected) { throw new InvalidOperationException("TCP client is not connected."); } if (m_IsSecure) { throw new InvalidOperationException("TCP client is already secure."); } LogAddText("Switching to SSL."); // FIX ME: if ssl switching fails, it closes source stream or otherwise if ssl successful, source stream leaks. SslStream sslStream = new SslStream(m_pTcpStream.SourceStream, true, RemoteCertificateValidationCallback); sslStream.AuthenticateAsClient(""); // Close old stream, but leave source stream open. m_pTcpStream.IsOwner = false; m_pTcpStream.Dispose(); m_IsSecure = true; m_pTcpStream = new SmartStream(sslStream, true); } // Do we need it ? /// <summary> /// This must be called when unexpected error happens. When inheriting <b>TCP_Client</b> class, be sure that you call <b>OnError</b> /// method for each unexpected error. /// </summary> /// <param name="x">Exception happened.</param> protected void OnError(Exception x) { try { if (m_pLogger != null) { //m_pLogger.AddException(x); } } catch {} } /// <summary> /// Reads and logs specified line from connected host. /// </summary> /// <returns>Returns readed line.</returns> protected string ReadLine() { SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength], SizeExceededAction. JunkAndThrowException); TcpStream.ReadLine(args, false); if (args.Error != null) { throw args.Error; } string line = args.LineUtf8; if (args.BytesInBuffer > 0) { LogAddRead(args.BytesInBuffer, line); } else { LogAddText("Remote host closed connection."); } return line; } /// <summary> /// Sends and logs specified line to connected host. /// </summary> /// <param name="line">Line to send.</param> protected void WriteLine(string line) { if (line == null) { throw new ArgumentNullException("line"); } int countWritten = TcpStream.WriteLine(line); LogAddWrite(countWritten, line); } /// <summary> /// Logs read operation. /// </summary> /// <param name="size">Number of bytes readed.</param> /// <param name="text">Log text.</param> protected void LogAddRead(long size, string text) { try { if (m_pLogger != null) { m_pLogger.AddRead(ID, AuthenticatedUserIdentity, size, text, LocalEndPoint, RemoteEndPoint); } } catch { // We skip all logging errors, normally there shouldn't be any. } } /// <summary> /// Logs write operation. /// </summary> /// <param name="size">Number of bytes written.</param> /// <param name="text">Log text.</param> protected void LogAddWrite(long size, string text) { try { if (m_pLogger != null) { m_pLogger.AddWrite(ID, AuthenticatedUserIdentity, size, text, LocalEndPoint, RemoteEndPoint); } } catch { // We skip all logging errors, normally there shouldn't be any. } } /// <summary> /// Logs free text entry. /// </summary> /// <param name="text">Log text.</param> protected void LogAddText(string text) { try { if (m_pLogger != null) { m_pLogger.AddText(IsConnected ? ID : "", IsConnected ? AuthenticatedUserIdentity : null, text, IsConnected ? LocalEndPoint : null, IsConnected ? RemoteEndPoint : null); } } catch { // We skip all logging errors, normally there shouldn't be any. } } /// <summary> /// Logs exception. /// </summary> /// <param name="text">Log text.</param> /// <param name="x">Exception happened.</param> protected void LogAddException(string text, Exception x) { try { if (m_pLogger != null) { m_pLogger.AddException(IsConnected ? ID : "", IsConnected ? AuthenticatedUserIdentity : null, text, IsConnected ? LocalEndPoint : null, IsConnected ? RemoteEndPoint : null, x); } } catch { // We skip all logging errors, normally there shouldn't be any. } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using SIL.IO; using SIL.Reporting; namespace SIL.Migration { ///<summary> /// Migrates a set of files (of one type) in a folder matching an optional SearchPattern up to the given version using a set of strategies to migrate each /// version of the file. ///</summary> public class FolderMigrator : MigratorBase { private class FileVersionInfo { public readonly int Version; public readonly string FileName; public FileVersionInfo(string fileName, int version) { FileName = fileName; Version = version; } } ///<summary> /// A handler delegate for notification of issues encountered during migration. ///</summary> ///<param name="problems"></param> public delegate void FolderMigratorProblemHandler(IEnumerable<FolderMigratorProblem> problems); private readonly FolderMigratorProblemHandler _problemHandler; ///<summary> /// FolderMigrationProblem contains information about exceptions thrown during execution /// of a migration strategy. ///</summary> public class FolderMigratorProblem { ///<summary> /// The exceptions that was thrown by the migration stragegy. ///</summary> public Exception Exception { get; set; } ///<summary> /// The file being migrated when the problem occurred. ///</summary> public string FilePath { get; set; } } private readonly List<FileVersionInfo> _versionCache = new List<FileVersionInfo>(); private string _versionCachePath; ///<summary> /// Constructor ///</summary> ///<param name="versionToMigrateTo">Target version to migrate to</param> ///<param name="sourcePath">FolderMigratorProblemHandler callback to pass exceptions thrown during migration</param> public FolderMigrator(int versionToMigrateTo, string sourcePath) : base(versionToMigrateTo) { SourcePath = sourcePath; _problemHandler = OnFolderMigrationProblem; } ///<summary> /// Constructor with FolderMigratorProblemHandler which is passed a collection of exceptions thrown during migration. ///</summary> ///<param name="versionToMigrateTo">Target version to migrate to</param> ///<param name="sourcePath">Folder path containing files to migrate</param> ///<param name="problemHandler">Folder path containing files to migrate</param> public FolderMigrator(int versionToMigrateTo, string sourcePath, FolderMigratorProblemHandler problemHandler) : this(versionToMigrateTo, sourcePath) { _problemHandler = problemHandler; } ///<summary> /// Default FolderMigrationProblemHandler, does nothing. ///</summary> protected virtual void OnFolderMigrationProblem(IEnumerable<FolderMigratorProblem> problems) { } ///<summary> /// Perform the migration ///</summary> ///<exception cref="InvalidOperationException"></exception> public virtual void Migrate() { var problems = new List<FolderMigratorProblem>(); // Clean up root backup path if (Directory.Exists(MigrationPath)) { if (!DirectoryUtilities.DeleteDirectoryRobust(MigrationPath)) { //for user, ah well //for programmer, tell us Debug.Fail("(Debug mode only) Couldn't delete the migration folder"); } } //check if there is anything to migrate. If not, don't do anything if(!Directory.Exists(SourcePath)) return; Logger.WriteMinorEvent("Migrator examining "+SourcePath); if (GetLowestVersionInFolder(SourcePath) == ToVersion) return; // Backup current folder to backup path under backup root CopyDirectory(SourcePath, BackupPath, MigrationPath); string currentPath = BackupPath; int lowestVersionInFolder; int lowestVersoinInFolder1 = -1; while ((lowestVersionInFolder = GetLowestVersionInFolder(currentPath)) != ToVersion) { Logger.WriteEvent("Migrating "+currentPath+" from "+lowestVersionInFolder);//enhance: to what version? //This guards against an empty Folder if(lowestVersionInFolder == int.MaxValue) { break; } if (lowestVersionInFolder == lowestVersoinInFolder1) { var fileNotMigrated = _versionCache.First(info => info.Version == lowestVersionInFolder).FileName; throw new ApplicationException( String.Format("The migration strategy for {0} failed to migrate the file '{1} from version {2}", SearchPattern,fileNotMigrated, lowestVersoinInFolder1) ); } int currentVersion = lowestVersionInFolder; // Get all files in folder with this version var fileNamesToMigrate = GetFilesOfVersion(currentVersion, currentPath); // Find a strategy to migrate this version IMigrationStrategy strategy = _migrationStrategies.Find(s => s.FromVersion == currentVersion); if (strategy == null) { throw new InvalidOperationException( String.Format("No migration strategy could be found for version {0}", currentVersion) ); } string destinationPath = Path.Combine( MigrationPath, String.Format("{0}_{1}", strategy.FromVersion, strategy.ToVersion) ); Directory.CreateDirectory(destinationPath); // Migrate all the files of the current version foreach (var filePath in Directory.GetFiles(currentPath, SearchPattern)) { string fileName = Path.GetFileName(filePath); if (fileName == null) continue; string sourceFilePath = Path.Combine(currentPath, fileName); string targetFilePath = Path.Combine(destinationPath, fileName); if (fileNamesToMigrate.Contains(sourceFilePath)) { strategy.Migrate(sourceFilePath, targetFilePath); } else { File.Copy(sourceFilePath, targetFilePath); } } try { strategy.PostMigrate(currentPath, destinationPath); } catch (Exception e) { problems.Add(new FolderMigratorProblem { Exception = e, FilePath = currentPath }); } // Setup for the next iteration currentPath = destinationPath; lowestVersoinInFolder1 = lowestVersionInFolder; } // Delete all the files in SourcePath matching SearchPattern foreach (var filePath in Directory.GetFiles(SourcePath, SearchPattern)) { File.Delete(filePath); } // Copy the migration results into SourcePath CopyDirectory(currentPath, SourcePath, ""); if (!DirectoryUtilities.DeleteDirectoryRobust(MigrationPath)) { //for user, ah well //for programmer, tell us Debug.Fail("(Debug mode only) Couldn't delete the migration folder"); } // Call the problem handler if we encountered problems during migration. if (problems.Count > 0) { _problemHandler(problems); } } internal IEnumerable<string> GetFilesOfVersion(int currentVersion, string path) { UpdateVersionInfoCache(path); return _versionCache.Where(i => i.Version == currentVersion).Select(i => i.FileName); } internal int GetLowestVersionInFolder(string path) { UpdateVersionInfoCache(path); return _versionCache.Aggregate(int.MaxValue, (current, i) => Math.Min(i.Version, current)); } private void UpdateVersionInfoCache(string path) { if (path == _versionCachePath) { return; } _versionCache.Clear(); foreach (var fileName in Directory.GetFiles(path, SearchPattern)) { int fileVersion = GetFileVersion(fileName); _versionCache.Add(new FileVersionInfo(fileName, fileVersion)); } _versionCachePath = path; } ///<summary> /// The pattern used to match files to migrate. ///</summary> public string SearchPattern { get; set; } /// <summary> /// Gets the source path. /// </summary> protected string SourcePath { get; private set; } private string MigrationPath { get { return Path.Combine(SourcePath, "Migration"); } } private string BackupPath { get { return Path.Combine(MigrationPath, "Backup"); } } private static void CopyDirectory(string sourcePath, string targetPath, string excludePath) { CopyDirectory(new DirectoryInfo(sourcePath), new DirectoryInfo(targetPath), string.IsNullOrEmpty(excludePath) ? null : new DirectoryInfo(excludePath)); } // Gleaned from http://xneuron.wordpress.com/2007/04/12/copy-directory-and-its-content-to-another-directory-in-c/ public static void CopyDirectory(DirectoryInfo source, DirectoryInfo target, DirectoryInfo excludePath) { // Check if the target directory exists, if not, create it. if (Directory.Exists(target.FullName) == false) { Directory.CreateDirectory(target.FullName); } // Copy each file into its new directory. foreach (FileInfo fileInfo in source.GetFiles()) { fileInfo.CopyTo(Path.Combine(target.ToString(), fileInfo.Name), true); } // Copy each subdirectory using recursion. foreach (DirectoryInfo directoryInfo in source.GetDirectories()) { if (excludePath != null && directoryInfo.FullName == excludePath.FullName) { continue; } DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(directoryInfo.Name); CopyDirectory(directoryInfo, nextTargetSubDir, excludePath); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT license. using Microsoft.AppCenter.Unity; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Xml.Linq; using System; #if UNITY_2018_1_OR_NEWER using UnityEditor.Build.Reporting; #endif using UnityEditor.Build; using UnityEditor; using UnityEngine; // Warning: Don't use #if #endif for conditional compilation here as Unity // doesn't always set the flags early enough. #if UNITY_2018_1_OR_NEWER public class AppCenterPostBuild : IPostprocessBuildWithReport #else public class AppCenterPostBuild : IPostprocessBuild #endif { public int callbackOrder { get { return 0; } } private const string AppManifestFileName = "Package.appxmanifest"; private const string CapabilitiesElement = "Capabilities"; private const string CapabilityElement = "Capability"; private const string CapabilityNameAttribute = "Name"; private const string CapabilityNameAttributeValue = "internetClient"; private const string AppNetD3d = "App.cs"; private const string AppNetXaml = "App.xaml.cs"; private const string AppIl2cppXaml = "App.xaml.cpp"; private const string AppIl2cppD3d = "App.cpp"; #if UNITY_2018_1_OR_NEWER public void OnPostprocessBuild(BuildReport report) { OnPostprocessBuild(report.summary.platform, report.summary.outputPath); } #endif public void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { if (target == BuildTarget.WSAPlayer) { AddInternetClientCapability(pathToBuiltProject); AddHelperCodeToUWPProject(pathToBuiltProject); if (PlayerSettings.GetScriptingBackend(BuildTargetGroup.WSA) != ScriptingImplementation.IL2CPP) { // If UWP with .NET scripting backend, need to add NuGet packages. var projectJson = pathToBuiltProject + "/" + PlayerSettings.productName + "/project.json"; AddDependenciesToProjectJson(projectJson); var nuget = EditorApplication.applicationContentsPath + "/PlaybackEngines/MetroSupport/Tools/nuget.exe"; ExecuteCommand(nuget, "restore \"" + projectJson + "\" -NonInteractive"); } else { // Fix System.Diagnostics.Debug IL2CPP implementation. FixIl2CppLogging(pathToBuiltProject); } } if (target == BuildTarget.iOS && PBXProjectWrapper.PBXProjectIsAvailable && PlistDocumentWrapper.PlistDocumentIsAvailable) { var pbxProject = new PBXProjectWrapper(pathToBuiltProject); // Update project. OnPostprocessProject(pbxProject); pbxProject.WriteToFile(); // Update Info.plist. var settings = AppCenterSettingsContext.SettingsInstance; var infoPath = pathToBuiltProject + "/Info.plist"; var info = new PlistDocumentWrapper(infoPath); OnPostprocessInfo(info, settings); info.WriteToFile(); // Update capabilities (if possible). if (ProjectCapabilityManagerWrapper.ProjectCapabilityManagerIsAvailable) { var capabilityManager = new ProjectCapabilityManagerWrapper(pbxProject.ProjectPath, PBXProjectWrapper.GetUnityTargetName()); OnPostprocessCapabilities(capabilityManager, settings); capabilityManager.WriteToFile(); } } } #region UWP Methods public static void AddHelperCodeToUWPProject(string pathToBuiltProject) { var settings = AppCenterSettingsContext.SettingsInstance; if (!settings.UsePush || AppCenter.Push == null) { return; } // .NET, D3D if (EditorUserBuildSettings.wsaUWPBuildType == WSAUWPBuildType.D3D && PlayerSettings.GetScriptingBackend(BuildTargetGroup.WSA) == ScriptingImplementation.WinRTDotNET) { var appFilePath = GetAppFilePath(pathToBuiltProject, AppNetD3d); var regexPattern = "private void ApplicationView_Activated \\( CoreApplicationView [a-zA-Z0-9_]*, IActivatedEventArgs args \\) {".Replace(" ", "[\\s]*"); InjectCodeToFile(appFilePath, AppNetD3d, regexPattern, "d3ddotnet.txt"); } // .NET, XAML else if (EditorUserBuildSettings.wsaUWPBuildType == WSAUWPBuildType.XAML && PlayerSettings.GetScriptingBackend(BuildTargetGroup.WSA) == ScriptingImplementation.WinRTDotNET) { var appFilePath = GetAppFilePath(pathToBuiltProject, AppNetXaml); var regexPattern = "InitializeUnity\\(args.Arguments\\);"; InjectCodeToFile(appFilePath, AppNetXaml, regexPattern, "xamldotnet.txt", false); } // IL2CPP, XAML else if (EditorUserBuildSettings.wsaUWPBuildType == WSAUWPBuildType.XAML && PlayerSettings.GetScriptingBackend(BuildTargetGroup.WSA) == ScriptingImplementation.IL2CPP) { var appFilePath = GetAppFilePath(pathToBuiltProject, AppIl2cppXaml); var regexPattern = "InitializeUnity\\(e->Arguments\\);"; InjectCodeToFile(appFilePath, AppIl2cppXaml, regexPattern, "xamlil2cpp.txt", false); } // IL2CPP, D3D else if (EditorUserBuildSettings.wsaUWPBuildType == WSAUWPBuildType.D3D && PlayerSettings.GetScriptingBackend(BuildTargetGroup.WSA) == ScriptingImplementation.IL2CPP) { var appFilePath = GetAppFilePath(pathToBuiltProject, AppIl2cppD3d); var regexPattern = "void App::OnActivated\\(CoreApplicationView\\s*\\^ [a-zA-Z0-9_]+, IActivatedEventArgs\\s*\\^ [a-zA-Z0-9_]+\\) {".Replace(" ", "[\\s]*"); InjectCodeToFile(appFilePath, AppIl2cppD3d, regexPattern, "d3dil2cpp.txt"); } } public static void InjectCodeToFile(string appFilePath, string appFileName, string searchRegex, string codeToInsertFileName, bool includeSearchText = true) { if (string.IsNullOrEmpty(appFilePath)) { LogInjectFailed(appFileName); return; } var appAdditionsFolder = AppCenterSettingsContext.AppCenterPath + "/AppCenter/Plugins/WSA/Push/AppAdditions"; var commentText = "App Center Push code:"; var codeToInsert = Environment.NewLine + " // " + commentText + Environment.NewLine + File.ReadAllText(Path.Combine(appAdditionsFolder, codeToInsertFileName)); var fileText = File.ReadAllText(appFilePath); if (fileText.Contains(commentText)) { if (fileText.Contains(codeToInsert)) { Debug.LogFormat("App Center Push: Code file `{0}` already contains the injection code. Will not re-inject", appFilePath); } else { Debug.LogWarningFormat("App Center Push: Code file `{0}` already contains the injection code but it does not match the latest code injection. Please rebuild the project into an empty folder", appFilePath); } return; } var regex = new Regex(searchRegex); var matches = regex.Match(fileText); if (matches.Success) { var codeToReplace = matches.ToString(); if (includeSearchText) { codeToInsert = codeToReplace + codeToInsert; } fileText = fileText.Replace(codeToReplace, codeToInsert); File.WriteAllText(appFilePath, fileText); } else { LogInjectFailed(appFilePath); } } public static void FixIl2CppLogging(string pathToBuiltProject) { var sourceDebuggerPath = "Assets\\AppCenter\\Plugins\\WSA\\IL2CPP\\Debugger.cpp.txt"; var destDebuggerPath = Path.Combine(pathToBuiltProject, "Il2CppOutputProject\\IL2CPP\\libil2cpp\\icalls\\mscorlib\\System.Diagnostics\\Debugger.cpp"); File.Copy(sourceDebuggerPath, destDebuggerPath, true); } public static string GetAppFilePath(string pathToBuiltProject, string filename) { var candidate = Path.Combine(pathToBuiltProject, Application.productName); candidate = Path.Combine(candidate, filename); return File.Exists(candidate) ? candidate : null; } public static void ProcessUwpIl2CppDependencies() { var binaries = AssetDatabase.FindAssets("*", new[] { AppCenterSettingsContext.AppCenterPath + "/AppCenter/Plugins/WSA/IL2CPP" }); foreach (var guid in binaries) { var assetPath = AssetDatabase.GUIDToAssetPath(guid); var importer = AssetImporter.GetAtPath(assetPath) as PluginImporter; if (importer != null) { importer.SetPlatformData(BuildTarget.WSAPlayer, "SDK", "UWP"); importer.SetPlatformData(BuildTarget.WSAPlayer, "ScriptingBackend", "Il2Cpp"); importer.SaveAndReimport(); } } } private static void AddDependenciesToProjectJson(string projectJsonPath) { if (!File.Exists(projectJsonPath)) { Debug.LogWarning(projectJsonPath + " not found!"); return; } var jsonString = File.ReadAllText(projectJsonPath); jsonString = AddDependencyToProjectJson(jsonString, "Microsoft.NETCore.UniversalWindowsPlatform", "5.2.2"); jsonString = AddDependencyToProjectJson(jsonString, "Newtonsoft.Json", "10.0.3"); jsonString = AddDependencyToProjectJson(jsonString, "sqlite-net-pcl", "1.3.1"); jsonString = AddDependencyToProjectJson(jsonString, "System.Collections.NonGeneric", "4.0.1"); File.WriteAllText(projectJsonPath, jsonString); } private static string AddDependencyToProjectJson(string projectJson, string packageId, string packageVersion) { const string quote = @"\" + "\""; var dependencyString = "\"" + packageId + "\": \"" + packageVersion + "\""; var pattern = quote + packageId + quote + @":[\s]+" + quote + "[^" + quote + "]*" + quote; var regex = new Regex(pattern); var match = regex.Match(projectJson); if (match.Success) { return projectJson.Replace(match.Value, dependencyString); } pattern = quote + "dependencies" + quote + @":[\s]+{"; regex = new Regex(pattern); match = regex.Match(projectJson); var idx = projectJson.IndexOf(match.Value, StringComparison.Ordinal) + match.Value.Length; return projectJson.Insert(idx, "\n" + dependencyString + ","); } private static void ExecuteCommand(string command, string arguments, int timeout = 600) { try { var buildProcess = new System.Diagnostics.Process { StartInfo = { FileName = command, Arguments = arguments } }; buildProcess.Start(); buildProcess.WaitForExit(timeout * 1000); } catch (Exception exception) { Debug.LogException(exception); } } private static void AddInternetClientCapability(string pathToBuiltProject) { /* Package.appxmanifest file example: <Package> <Capabilities> <Capability Name="internetClient" /> </Capabilities> </Package> */ var appManifests = Directory.GetFiles(pathToBuiltProject, AppManifestFileName, SearchOption.AllDirectories); if (appManifests.Length == 0) { Debug.LogWarning("Failed to add the `InternetClient` capability, file `" + AppManifestFileName + "` is not found"); return; } else if (appManifests.Length > 1) { Debug.LogWarning("Failed to add the `InternetClient` capability, multiple `" + AppManifestFileName + "` files found"); return; } var appManifestFilePath = appManifests[0]; var xmlFile = XDocument.Load(appManifestFilePath); var defaultNamespace = xmlFile.Root.GetDefaultNamespace().NamespaceName; var capabilitiesElements = xmlFile.Root.Elements().Where(element => element.Name.LocalName == CapabilitiesElement).ToList(); if (capabilitiesElements.Count > 1) { Debug.LogWarning("Failed to add the `InternetClient` capability, multiple `Capabilities` elements found inside `" + appManifestFilePath + "` file"); return; } else if (capabilitiesElements.Count == 0) { xmlFile.Root.Add(new XElement(XName.Get(CapabilitiesElement, defaultNamespace), GetInternetClientCapabilityElement(defaultNamespace))); } else // capabilitiesElements.Count == 1 { var capabilitiesElement = capabilitiesElements[0]; foreach (var element in capabilitiesElement.Elements()) { if (element.Name.LocalName == CapabilityElement && GetAttributeValue(element, CapabilityNameAttribute) == CapabilityNameAttributeValue) { return; } } capabilitiesElement.Add(GetInternetClientCapabilityElement(defaultNamespace)); } xmlFile.Save(appManifestFilePath); } private static XElement GetInternetClientCapabilityElement(string defaultNamespace) { return new XElement(XName.Get(CapabilityElement, defaultNamespace), new XAttribute(CapabilityNameAttribute, CapabilityNameAttributeValue)); } internal static string GetAttributeValue(XElement element, string attributeName) { var attribute = element.Attribute(attributeName); return attribute == null ? null : attribute.Value; } private static void LogInjectFailed(string fileName) { Debug.LogError("Unable to automatically modify file '" + fileName + "'. For App Center Push to work properly, " + "please follow troubleshooting instructions at https://docs.microsoft.com/en-us/appcenter/sdk/troubleshooting/unity"); } #endregion #region iOS Methods private static void OnPostprocessProject(PBXProjectWrapper project) { // Need to add "-lsqlite3" linker flag to "Other linker flags" due to // SQLite dependency. project.AddBuildProperty("OTHER_LDFLAGS", "-lsqlite3"); project.AddBuildProperty("CLANG_ENABLE_MODULES", "YES"); } private static void OnPostprocessInfo(PlistDocumentWrapper info, AppCenterSettings settings) { if (settings.UseDistribute && AppCenter.Distribute != null) { // Add App Center URL sceme. var root = info.GetRoot(); var urlTypes = root.GetType().GetMethod("CreateArray").Invoke(root, new object[] { "CFBundleURLTypes" }); var urlType = urlTypes.GetType().GetMethod("AddDict").Invoke(urlTypes, null); var setStringMethod = urlType.GetType().GetMethod("SetString"); setStringMethod.Invoke(urlType, new object[] { "CFBundleTypeRole", "None" }); setStringMethod.Invoke(urlType, new object[] { "CFBundleURLName", ApplicationIdHelper.GetApplicationId() }); var urlSchemes = urlType.GetType().GetMethod("CreateArray").Invoke(urlType, new[] { "CFBundleURLSchemes" }); urlSchemes.GetType().GetMethod("AddString").Invoke(urlSchemes, new[] { "appcenter-" + settings.iOSAppSecret }); } } private static void OnPostprocessCapabilities(ProjectCapabilityManagerWrapper capabilityManager, AppCenterSettings settings) { if (settings.UsePush && AppCenter.Push != null) { capabilityManager.AddPushNotifications(); capabilityManager.AddRemoteNotificationsToBackgroundModes(); } } #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. // /*============================================================================= ** ** ** ** Purpose: Class to represent all synchronization objects in the runtime (that allow multiple wait) ** ** =============================================================================*/ namespace System.Threading { using System.Threading; using System.Runtime.Remoting; using System; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; using Win32Native = Microsoft.Win32.Win32Native; [System.Runtime.InteropServices.ComVisible(true)] #if FEATURE_REMOTING public abstract class WaitHandle : MarshalByRefObject, IDisposable { #else // FEATURE_REMOTING public abstract class WaitHandle : IDisposable { #endif // FEATURE_REMOTING public const int WaitTimeout = 0x102; private const int MAX_WAITHANDLES = 64; #pragma warning disable 414 // Field is not used from managed. private IntPtr waitHandle; // !!! DO NOT MOVE THIS FIELD. (See defn of WAITHANDLEREF in object.h - has hardcoded access to this field.) #pragma warning restore 414 [System.Security.SecurityCritical] // auto-generated internal volatile SafeWaitHandle safeWaitHandle; internal bool hasThreadAffinity; [System.Security.SecuritySafeCritical] // auto-generated private static IntPtr GetInvalidHandle() { return Win32Native.INVALID_HANDLE_VALUE; } protected static readonly IntPtr InvalidHandle = GetInvalidHandle(); private const int WAIT_OBJECT_0 = 0; private const int WAIT_ABANDONED = 0x80; private const int WAIT_FAILED = 0x7FFFFFFF; private const int ERROR_TOO_MANY_POSTS = 0x12A; internal enum OpenExistingResult { Success, NameNotFound, PathNotFound, NameInvalid } protected WaitHandle() { Init(); } [System.Security.SecuritySafeCritical] // auto-generated private void Init() { safeWaitHandle = null; waitHandle = InvalidHandle; hasThreadAffinity = false; } [Obsolete("Use the SafeWaitHandle property instead.")] public virtual IntPtr Handle { [System.Security.SecuritySafeCritical] // auto-generated get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle();} [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif set { if (value == InvalidHandle) { // This line leaks a handle. However, it's currently // not perfectly clear what the right behavior is here // anyways. This preserves Everett behavior. We should // ideally do these things: // *) Expose a settable SafeHandle property on WaitHandle. // *) Expose a settable OwnsHandle property on SafeHandle. if (safeWaitHandle != null) { safeWaitHandle.SetHandleAsInvalid(); safeWaitHandle = null; } } else { safeWaitHandle = new SafeWaitHandle(value, true); } waitHandle = value; } } public SafeWaitHandle SafeWaitHandle { [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] get { if (safeWaitHandle == null) { safeWaitHandle = new SafeWaitHandle(InvalidHandle, false); } return safeWaitHandle; } [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { // Set safeWaitHandle and waitHandle in a CER so we won't take // a thread abort between the statements and leave the wait // handle in an invalid state. Note this routine is not thread // safe however. RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (value == null) { safeWaitHandle = null; waitHandle = InvalidHandle; } else { safeWaitHandle = value; waitHandle = safeWaitHandle.DangerousGetHandle(); } } } } // Assembly-private version that doesn't do a security check. Reduces the // number of link-time security checks when reading & writing to a file, // and helps avoid a link time check while initializing security (If you // call a Serialization method that requires security before security // has started up, the link time check will start up security, run // serialization code for some security attribute stuff, call into // FileStream, which will then call Sethandle, which requires a link time // security check.). While security has fixed that problem, we still // don't need to do a linktime check here. [System.Security.SecurityCritical] // auto-generated internal void SetHandleInternal(SafeWaitHandle handle) { safeWaitHandle = handle; waitHandle = handle.DangerousGetHandle(); } public virtual bool WaitOne (int millisecondsTimeout, bool exitContext) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); return WaitOne((long)millisecondsTimeout,exitContext); } public virtual bool WaitOne (TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return WaitOne(tm,exitContext); } public virtual bool WaitOne () { //Infinite Timeout return WaitOne(-1,false); } public virtual bool WaitOne(int millisecondsTimeout) { return WaitOne(millisecondsTimeout, false); } public virtual bool WaitOne(TimeSpan timeout) { return WaitOne(timeout, false); } [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] private bool WaitOne(long timeout, bool exitContext) { return InternalWaitOne(safeWaitHandle, timeout, hasThreadAffinity, exitContext); } [System.Security.SecurityCritical] // auto-generated internal static bool InternalWaitOne(SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext) { if (waitableSafeHandle == null) { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic")); } Contract.EndContractBlock(); int ret = WaitOneNative(waitableSafeHandle, (uint)millisecondsTimeout, hasThreadAffinity, exitContext); if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); if (ret == WAIT_ABANDONED) { ThrowAbandonedMutexException(); } return (ret != WaitTimeout); } [System.Security.SecurityCritical] internal bool WaitOneWithoutFAS() { // version of waitone without fast application switch (FAS) support // This is required to support the Wait which FAS needs (otherwise recursive dependency comes in) if (safeWaitHandle == null) { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic")); } Contract.EndContractBlock(); long timeout = -1; int ret = WaitOneNative(safeWaitHandle, (uint)timeout, hasThreadAffinity, false); if (ret == WAIT_ABANDONED) { ThrowAbandonedMutexException(); } return (ret != WaitTimeout); } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext); /*======================================================================== ** Waits for signal from all the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when all the object have been pulsed ** or timeout milliseonds have elapsed. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll); [System.Security.SecuritySafeCritical] // auto-generated public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles == null) { throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_Waithandles")); } if(waitHandles.Length == 0) { // // Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct. // Somehow, in 2.0, this became ArgumentNullException. This was not fixed until Silverlight 2, // which went back to ArgumentException. // // Now we're in a bit of a bind. Backward-compatibility requires us to keep throwing ArgumentException // in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking // user code. // #if FEATURE_CORECLR throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); #else throw new ArgumentNullException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); #endif } if (waitHandles.Length > MAX_WAITHANDLES) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles")); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i ++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_ArrayElement")); #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(waitHandle)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); #endif internalWaitHandles[i] = waitHandle; } #if _DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, true /* waitall*/ ); if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret)) { //In the case of WaitAll the OS will only provide the // information that mutex was abandoned. // It won't tell us which one. So we can't set the Index or provide access to the Mutex ThrowAbandonedMutexException(); } GC.KeepAlive(internalWaitHandles); return (ret != WaitTimeout); } public static bool WaitAll( WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return WaitAll(waitHandles,(int)tm, exitContext); } /*======================================================================== ** Shorthand for WaitAll with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ public static bool WaitAll(WaitHandle[] waitHandles) { return WaitAll(waitHandles, Timeout.Infinite, true); } public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitAll(waitHandles, millisecondsTimeout, true); } public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitAll(waitHandles, timeout, true); } /*======================================================================== ** Waits for notification from any of the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when either one of the object have been ** signalled or timeout milliseonds have elapsed. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles==null) { throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_Waithandles")); } if(waitHandles.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); } if (MAX_WAITHANDLES < waitHandles.Length) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles")); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i ++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_ArrayElement")); #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(waitHandle)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy")); #endif internalWaitHandles[i] = waitHandle; } #if _DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, false /* waitany*/ ); if(AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret)) { int mutexIndex = ret -WAIT_ABANDONED; if(0 <= mutexIndex && mutexIndex < internalWaitHandles.Length) { ThrowAbandonedMutexException(mutexIndex,internalWaitHandles[mutexIndex]); } else { ThrowAbandonedMutexException(); } } GC.KeepAlive(internalWaitHandles); return ret; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny( WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return WaitAny(waitHandles,(int)tm, exitContext); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitAny(waitHandles, timeout, true); } /*======================================================================== ** Shorthand for WaitAny with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles) { return WaitAny(waitHandles, Timeout.Infinite, true); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitAny(waitHandles, millisecondsTimeout, true); } /*================================================= == == SignalAndWait == ==================================================*/ [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout, bool hasThreadAffinity, bool exitContext); public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn) { return SignalAndWait(toSignal,toWaitOn,-1,false); } public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long) Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException("timeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } return SignalAndWait(toSignal,toWaitOn,(int)tm,exitContext); } [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext) { if(null == toSignal) { throw new ArgumentNullException("toSignal"); } if(null == toWaitOn) { throw new ArgumentNullException("toWaitOn"); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException("millisecondsTimeout", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); //NOTE: This API is not supporting Pause/Resume as it's not exposed in CoreCLR (not in WP or SL) int ret = SignalAndWaitOne(toSignal.safeWaitHandle,toWaitOn.safeWaitHandle,millisecondsTimeout, toWaitOn.hasThreadAffinity,exitContext); #if !FEATURE_CORECLR if(WAIT_FAILED != ret && toSignal.hasThreadAffinity) { Thread.EndCriticalRegion(); Thread.EndThreadAffinity(); } #endif if(WAIT_ABANDONED == ret) { ThrowAbandonedMutexException(); } if(ERROR_TOO_MANY_POSTS == ret) { throw new InvalidOperationException(Environment.GetResourceString("Threading.WaitHandleTooManyPosts")); } //Object was signaled if(WAIT_OBJECT_0 == ret) { return true; } //Timeout return false; } private static void ThrowAbandonedMutexException() { throw new AbandonedMutexException(); } private static void ThrowAbandonedMutexException(int location, WaitHandle handle) { throw new AbandonedMutexException(location, handle); } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] // auto-generated protected virtual void Dispose(bool explicitDisposing) { if (safeWaitHandle != null) { safeWaitHandle.Close(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }