context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using Plugins.CountlySDK.Enums; using Plugins.CountlySDK.Helpers; using Plugins.CountlySDK.Models; namespace Plugins.CountlySDK.Services { public class UserDetailsCountlyService : AbstractBaseService { internal Dictionary<string, object> CustomDataProperties { get; private set; } private readonly CountlyUtils _countlyUtils; internal readonly RequestCountlyHelper _requestCountlyHelper; internal UserDetailsCountlyService(CountlyConfiguration configuration, CountlyLogHelper logHelper, RequestCountlyHelper requestCountlyHelper, CountlyUtils countlyUtils, ConsentCountlyService consentService) : base(configuration, logHelper, consentService) { Log.Debug("[UserDetailsCountlyService] Initializing."); _countlyUtils = countlyUtils; _requestCountlyHelper = requestCountlyHelper; CustomDataProperties = new Dictionary<string, object>(); } /// <summary> /// Add user custom detail to request queue. /// </summary> /// <returns></returns> private void AddCustomDetailToRequestQueue(IDictionary<string, object> segments) { IDictionary<string, object> customDetail = FixSegmentKeysAndValues(segments); Dictionary<string, object> requestParams = new Dictionary<string, object> { { "user_details", JsonConvert.SerializeObject( new Dictionary<string, object> { { "custom", customDetail } }) } }; _requestCountlyHelper.AddToRequestQueue(requestParams); _ = _requestCountlyHelper.ProcessQueue(); } /// <summary> /// Sets information about user. /// </summary> /// <param name="userDetailsModel">User Model with the specified params</param> /// <returns></returns> public async Task SetUserDetailsAsync(CountlyUserDetailsModel userDetailsModel) { lock (LockObj) { Log.Info("[UserDetailsCountlyService] SetUserDetailsAsync " + (userDetailsModel != null)); if (!_consentService.CheckConsentInternal(Consents.Users)) { return; } if (userDetailsModel == null) { Log.Warning("[UserDetailsCountlyService] SetUserDetailsAsync : The parameter 'userDetailsModel' can't be null."); return; } if (!_countlyUtils.IsPictureValid(userDetailsModel.PictureUrl)) { throw new Exception("Accepted picture formats are .png, .gif and .jpeg"); } userDetailsModel.Name = TrimValue("Name", userDetailsModel.Name); userDetailsModel.Phone = TrimValue("Phone", userDetailsModel.Phone); userDetailsModel.Email = TrimValue("Email", userDetailsModel.Email); userDetailsModel.Gender = TrimValue("Gender", userDetailsModel.Gender); userDetailsModel.Username = TrimValue("Username", userDetailsModel.Username); userDetailsModel.BirthYear = TrimValue("BirthYear", userDetailsModel.BirthYear); userDetailsModel.Organization = TrimValue("Organization", userDetailsModel.Organization); if (userDetailsModel.PictureUrl.Length > 4096) { Log.Warning("[" + GetType().Name + "] TrimValue : Max allowed length of 'PictureUrl' is " + _configuration.MaxValueSize); userDetailsModel.PictureUrl = userDetailsModel.PictureUrl.Substring(0, 4096); } userDetailsModel.Custom = FixSegmentKeysAndValues(userDetailsModel.Custom); Dictionary<string, object> requestParams = new Dictionary<string, object> { { "user_details", JsonConvert.SerializeObject(userDetailsModel, Formatting.Indented, new JsonSerializerSettings{ NullValueHandling = NullValueHandling.Ignore }) }, }; _requestCountlyHelper.AddToRequestQueue(requestParams); _ = _requestCountlyHelper.ProcessQueue(); } } /// <summary> /// Sets information about user with custom properties. /// In custom properties you can provide any string key values to be stored with user. /// </summary> /// <param name="userDetailsModel">User Detail Model with the custom properties</param> /// <returns></returns> [Obsolete("SetCustomUserDetailsAsync is deprecated, please use SetCustomUserDetails method instead.")] public async Task SetCustomUserDetailsAsync(CountlyUserDetailsModel userDetailsModel) { lock (LockObj) { Log.Info("[UserDetailsCountlyService] SetCustomUserDetailsAsync " + (userDetailsModel != null)); if (!_consentService.CheckConsentInternal(Consents.Users)) { return; } if (userDetailsModel == null) { Log.Warning("[UserDetailsCountlyService] SetCustomUserDetailsAsync : The parameter 'userDetailsModel' can't be null."); return; } if (userDetailsModel.Custom == null || userDetailsModel.Custom.Count == 0) { Log.Warning("[UserDetailsCountlyService] SetCustomUserDetailsAsync : The custom property 'userDetailsModel.Custom' can't be null or empty."); return; } AddCustomDetailToRequestQueue(userDetailsModel.Custom); } } /// <summary> /// Sets information about user with custom properties. /// In custom properties you can provide any string key values to be stored with user. /// </summary> /// <param name="customDetail">User custom detail</param> /// <returns></returns> public void SetCustomUserDetails(Dictionary<string, object> customDetail) { Log.Info("[UserDetailsCountlyService] SetCustomUserDetails " + (customDetail != null)); if (!_consentService.CheckConsentInternal(Consents.Users)) { return; } if (customDetail == null || customDetail.Count == 0) { Log.Warning("[UserDetailsCountlyService] SetCustomUserDetails : Provided custom detail 'customDetail' can't be null or empty."); return; } AddCustomDetailToRequestQueue(customDetail); } /// <summary> /// Send provided values to server. /// </summary> /// <returns></returns> public async Task SaveAsync() { lock (LockObj) { if (!CustomDataProperties.Any()) { return; } Log.Info("[UserDetailsCountlyService] SaveAsync"); CountlyUserDetailsModel model = new CountlyUserDetailsModel(CustomDataProperties); CustomDataProperties = new Dictionary<string, object> { }; AddCustomDetailToRequestQueue(CustomDataProperties); } } /// <summary> /// Sets custom provide key/value as custom property. /// </summary> /// <param name="key">string with key for the property</param> /// <param name="value">string with value for the property</param> public void Set(string key, string value) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] Set : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] Set : key = " + key + ", value = " + value); AddToCustomData(key, TrimValue(key, value)); } } /// <summary> /// Set value only if property does not exist yet. /// </summary> /// <param name="key">string with property name to set</param> /// <param name="value">string value to set</param> public void SetOnce(string key, string value) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] SetOnce : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] SetOnce : key = " + key + ", value = " + value); AddToCustomData(key, new Dictionary<string, object> { { "$setOnce", TrimValue(key, value) } }); } } /// <summary> /// Increment custom property value by 1. /// </summary> /// <param name="key">string with property name to increment</param> public void Increment(string key) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] Increment : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] Increment : key = " + key); AddToCustomData(key, new Dictionary<string, object> { { "$inc", 1 } }); } } /// <summary> /// Increment custom property value by provided value. /// </summary> /// <param name="key">string with property name to increment</param> /// <param name="value">double value by which to increment</param> public void IncrementBy(string key, double value) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] IncrementBy : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] IncrementBy : key = " + key + ", value = " + value); AddToCustomData(key, new Dictionary<string, object> { { "$inc", value } }); } } /// <summary> /// Multiply custom property value by provided value. /// </summary> /// <param name="key">string with property name to multiply</param> /// <param name="value">double value by which to multiply</param> public void Multiply(string key, double value) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] Multiply : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] Multiply : key = " + key + ", value = " + value); AddToCustomData(key, new Dictionary<string, object> { { "$mul", value } }); } } /// <summary> /// Save maximal value between existing and provided. /// </summary> /// <param name="key">String with property name to check for max</param> /// <param name="value">double value to check for max</param> public void Max(string key, double value) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] Max : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] Max : key = " + key + ", value = " + value); AddToCustomData(key, new Dictionary<string, object> { { "$max", value } }); } } /// <summary> /// Save minimal value between existing and provided. /// </summary> /// <param name="key">string with property name to check for min</param> /// <param name="value">double value to check for min</param> public void Min(string key, double value) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] Min : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] Min : key = " + key + ", value = " + value); AddToCustomData(key, new Dictionary<string, object> { { "$min", value } }); } } /// <summary> /// Create array property, if property does not exist and add value to array /// You can only use it on array properties or properties that do not exist yet. /// </summary> /// <param name="key">string with property name for array property</param> /// <param name="value">array with values to add</param> public void Push(string key, string[] value) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] Push : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] Push : key = " + key + ", value = " + value); AddToCustomData(key, new Dictionary<string, object> { { "$push", TrimValues(value) } }); } } /// <summary> /// Create array property, if property does not exist and add value to array, only if value is not yet in the array /// You can only use it on array properties or properties that do not exist yet. /// </summary> /// <param name="key">string with property name for array property</param> /// <param name="value">array with values to add</param> public void PushUnique(string key, string[] value) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] PushUnique : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] PushUnique : key = " + key + ", value = " + value); AddToCustomData(key, new Dictionary<string, object> { { "$addToSet", TrimValues(value) } }); } } /// <summary> /// Create array property, if property does not exist and remove value from array. /// </summary> /// <param name="key">String with property name for array property</param> /// <param name="value">array with values to remove from array</param> public void Pull(string key, string[] value) { if (string.IsNullOrEmpty(key)) { Log.Warning("[UserDetailsCountlyService] Pull : key '" + key + "'isn't valid."); return; } lock (LockObj) { Log.Info("[UserDetailsCountlyService] Pull : key = " + key + ", value = " + value); value = TrimValues(value); AddToCustomData(key, new Dictionary<string, object> { { "$pull", value } }); } } /// <summary> /// Create a property /// </summary> /// <param name="key">property name</param> /// <param name="value">property value</param> private void AddToCustomData(string key, object value) { Log.Debug("[UserDetailsCountlyService] AddToCustomData: " + key + ", " + value); if (!_consentService.CheckConsentInternal(Consents.Users)) { return; } key = TrimKey(key); if (CustomDataProperties.ContainsKey(key)) { string item = CustomDataProperties.Select(x => x.Key).FirstOrDefault(x => x.Equals(key, StringComparison.OrdinalIgnoreCase)); if (item != null) { CustomDataProperties.Remove(item); } } CustomDataProperties.Add(key, value); } #region override Methods #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Xml; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class XNodeReaderFunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { public partial class TCReadSubtree : BridgeHelpers { //[Variation("ReadSubtree only works on Element Node")] public void ReadSubtreeOnlyWorksOnElementNode() { XmlReader DataReader = GetReader(); while (DataReader.Read()) { if (DataReader.NodeType != XmlNodeType.Element) { string nodeType = DataReader.NodeType.ToString(); bool flag = true; try { DataReader.ReadSubtree(); } catch (InvalidOperationException) { flag = false; } if (flag) { TestLog.WriteLine("ReadSubtree doesn't throw InvalidOp Exception on NodeType : " + nodeType); throw new TestException(TestResult.Failed, ""); } // now try next read try { DataReader.Read(); } catch (XmlException) { TestLog.WriteLine("Cannot Read after an invalid operation exception"); throw new TestException(TestResult.Failed, ""); } } else { if (DataReader.HasAttributes) { bool flag = true; DataReader.MoveToFirstAttribute(); try { DataReader.ReadSubtree(); } catch (InvalidOperationException) { flag = false; } if (flag) { TestLog.WriteLine("ReadSubtree doesn't throw InvalidOp Exception on Attribute Node Type"); throw new TestException(TestResult.Failed, ""); } //now try next read. try { DataReader.Read(); } catch (XmlException) { TestLog.WriteLine("Cannot Read after an invalid operation exception"); throw new TestException(TestResult.Failed, ""); } } } }//end while } private string _xml = "<root><elem1><elempi/><?pi target?><elem2 xmlns='xyz'><elem/><!--Comment--><x:elem3 xmlns:x='pqr'><elem4 attr4='4'/></x:elem3></elem2></elem1><elem5/><elem6/></root>"; //[Variation("ReadSubtree Test on Root", Priority = 0, Params = new object[] { "root", "", "ELEMENT", "", "", "NONE" })] //[Variation("ReadSubtree Test depth=1", Priority = 0, Params = new object[] { "elem1", "", "ELEMENT", "elem5", "", "ELEMENT" })] //[Variation("ReadSubtree Test depth=2", Priority = 0, Params = new object[] { "elem2", "", "ELEMENT", "elem1", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test depth=3", Priority = 0, Params = new object[] { "x:elem3", "", "ELEMENT", "elem2", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test depth=4", Priority = 0, Params = new object[] { "elem4", "", "ELEMENT", "x:elem3", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test empty element", Priority = 0, Params = new object[] { "elem5", "", "ELEMENT", "elem6", "", "ELEMENT" })] //[Variation("ReadSubtree Test empty element before root", Priority = 0, Params = new object[] { "elem6", "", "ELEMENT", "root", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test PI after element", Priority = 0, Params = new object[] { "elempi", "", "ELEMENT", "pi", "target", "PROCESSINGINSTRUCTION" })] //[Variation("ReadSubtree Test Comment after element", Priority = 0, Params = new object[] { "elem", "", "ELEMENT", "", "Comment", "COMMENT" })] public void v2() { int count = 0; string name = Variation.Params[count++].ToString(); string value = Variation.Params[count++].ToString(); string type = Variation.Params[count++].ToString(); string oname = Variation.Params[count++].ToString(); string ovalue = Variation.Params[count++].ToString(); string otype = Variation.Params[count++].ToString(); XmlReader DataReader = GetReader(new StringReader(_xml)); PositionOnElement(DataReader, name); XmlReader r = DataReader.ReadSubtree(); TestLog.Compare(r.ReadState, ReadState.Initial, "Reader state is not Initial"); TestLog.Compare(r.Name, String.Empty, "Name is not empty"); TestLog.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty"); TestLog.Compare(r.Depth, 0, "Depth is not zero"); r.Read(); TestLog.Compare(r.ReadState, ReadState.Interactive, "Reader state is not Interactive"); TestLog.Compare(r.Name, name, "Subreader name doesn't match"); TestLog.Compare(r.Value, value, "Subreader value doesn't match"); TestLog.Compare(r.NodeType.ToString().ToUpperInvariant(), type, "Subreader nodetype doesn't match"); TestLog.Compare(r.Depth, 0, "Subreader Depth is not zero"); while (r.Read()) ; r.Dispose(); TestLog.Compare(r.ReadState, ReadState.Closed, "Reader state is not Initial"); TestLog.Compare(r.Name, String.Empty, "Name is not empty"); TestLog.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty"); DataReader.Read(); TestLog.Compare(DataReader.Name, oname, "Main name doesn't match"); TestLog.Compare(DataReader.Value, ovalue, "Main value doesn't match"); TestLog.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), otype, "Main nodetype doesn't match"); DataReader.Dispose(); } //[Variation("Read with entities", Priority = 1)] public void v3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "PLAY"); XmlReader r = DataReader.ReadSubtree(); while (r.Read()) { if (r.NodeType == XmlNodeType.EntityReference) { if (r.CanResolveEntity) r.ResolveEntity(); } } r.Dispose(); DataReader.Dispose(); } //[Variation("Inner XML on Subtree reader", Priority = 1)] public void v4() { string xmlStr = "<elem1><elem2/></elem1>"; XmlReader DataReader = GetReaderStr(xmlStr); PositionOnElement(DataReader, "elem1"); XmlReader r = DataReader.ReadSubtree(); r.Read(); TestLog.Compare(r.ReadInnerXml(), "<elem2 />", "Inner Xml Fails"); TestLog.Compare(r.Read(), false, "Read returns false"); r.Dispose(); DataReader.Dispose(); } //[Variation("Outer XML on Subtree reader", Priority = 1)] public void v5() { string xmlStr = "<elem1><elem2/></elem1>"; XmlReader DataReader = GetReaderStr(xmlStr); PositionOnElement(DataReader, "elem1"); XmlReader r = DataReader.ReadSubtree(); r.Read(); TestLog.Compare(r.ReadOuterXml(), "<elem1><elem2 /></elem1>", "Outer Xml Fails"); TestLog.Compare(r.Read(), false, "Read returns true"); r.Dispose(); DataReader.Dispose(); } //[Variation("ReadString on Subtree reader", Priority = 1)] public void v6() { string xmlStr = "<elem1><elem2/></elem1>"; XmlReader DataReader = GetReaderStr(xmlStr); PositionOnElement(DataReader, "elem1"); XmlReader r = DataReader.ReadSubtree(); r.Read(); TestLog.Compare(r.Read(), true, "Read returns false"); r.Dispose(); DataReader.Dispose(); } //[Variation("Close on inner reader with CloseInput should not close the outer reader", Priority = 1, Params = new object[] { "true" })] //[Variation("Close on inner reader with CloseInput should not close the outer reader", Priority = 1, Params = new object[] { "false" })] public void v7() { XmlReader DataReader = GetReader(); bool ci = Boolean.Parse(Variation.Params[0].ToString()); XmlReaderSettings settings = new XmlReaderSettings(); settings.CloseInput = ci; PositionOnElement(DataReader, "elem2"); XmlReader r = DataReader.ReadSubtree(); r.Dispose(); TestLog.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState not interactive"); DataReader.Dispose(); } private XmlReader NestRead(XmlReader r) { r.Read(); r.Read(); if (!(r.Name == "elem0" && r.NodeType == XmlNodeType.Element)) { NestRead(r.ReadSubtree()); } r.Dispose(); return r; } //[Variation("Nested Subtree reader calls", Priority = 2)] public void v8() { string xmlStr = "<elem1><elem2><elem3><elem4><elem5><elem6><elem7><elem8><elem9><elem0></elem0></elem9></elem8></elem7></elem6></elem5></elem4></elem3></elem2></elem1>"; XmlReader r = GetReader(new StringReader(xmlStr)); NestRead(r); TestLog.Compare(r.ReadState, ReadState.Closed, "Reader Read State is not closed"); } //[Variation("ReadSubtree for element depth more than 4K chars", Priority = 2)] public void v100() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); do { mnw.OpenElement(); mnw.CloseElement(); } while (mnw.GetNodes().Length < 4096); mnw.Finish(); XmlReader DataReader = GetReader(new StringReader(mnw.GetNodes())); PositionOnElement(DataReader, "ELEMENT_2"); XmlReader r = DataReader.ReadSubtree(); while (r.Read()) ; r.Dispose(); DataReader.Read(); TestLog.Compare(DataReader.Name, "ELEMENT_1", "Main name doesn't match"); TestLog.Compare(DataReader.Value, "", "Main value doesn't match"); TestLog.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), "ENDELEMENT", "Main nodetype doesn't match"); DataReader.Dispose(); } //[Variation("Multiple Namespaces on Subtree reader", Priority = 1)] public void MultipleNamespacesOnSubtreeReader() { string xmlStr = "<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a=''></e></root>"; XmlReader DataReader = GetReader(new StringReader(xmlStr)); PositionOnElement(DataReader, "e"); XmlReader r = DataReader.ReadSubtree(); while (r.Read()) ; r.Dispose(); DataReader.Dispose(); } //[Variation("Subtree Reader caches the NodeType and reports node type of Attribute on subsequent reads.", Priority = 1)] public void SubtreeReaderCachesNodeTypeAndReportsNodeTypeOfAttributeOnSubsequentReads() { string xmlStr = "<root xmlns='foo'><b blah='blah'/><b/></root>"; XmlReader DataReader = GetReader(new StringReader(xmlStr)); PositionOnElement(DataReader, "root"); XmlReader xxr = DataReader.ReadSubtree(); //Now on root. xxr.Read(); TestLog.Compare(xxr.Name, "root", "Root Elem"); TestLog.Compare(xxr.MoveToNextAttribute(), true, "MTNA 1"); TestLog.Compare(xxr.NodeType, XmlNodeType.Attribute, "XMLNS NT"); TestLog.Compare(xxr.Name, "xmlns", "XMLNS Attr"); TestLog.Compare(xxr.Value, "foo", "XMLNS Value"); TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 2"); //Now on b. xxr.Read(); TestLog.Compare(xxr.Name, "b", "b Elem"); TestLog.Compare(xxr.MoveToNextAttribute(), true, "MTNA 3"); TestLog.Compare(xxr.NodeType, XmlNodeType.Attribute, "blah NT"); TestLog.Compare(xxr.Name, "blah", "blah Attr"); TestLog.Compare(xxr.Value, "blah", "blah Value"); TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 4"); // Now on /b. xxr.Read(); TestLog.Compare(xxr.Name, "b", "b EndElem"); TestLog.Compare(xxr.NodeType, XmlNodeType.Element, "b Elem NT"); TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 5"); xxr.Read(); TestLog.Compare(xxr.Name, "root", "root EndElem"); TestLog.Compare(xxr.NodeType, XmlNodeType.EndElement, "root EndElem NT"); TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 6"); xxr.Dispose(); DataReader.Dispose(); } } } } }
/* * 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.Text; namespace OpenSim.Region.UserStatistics { public static class HTMLUtil { public static void TR_O(ref StringBuilder o, string pclass) { o.Append("<tr"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(">\n\t"); } public static void TR_C(ref StringBuilder o) { o.Append("</tr>\n"); } public static void TD_O(ref StringBuilder o, string pclass) { TD_O(ref o, pclass, 0, 0); } public static void TD_O(ref StringBuilder o, string pclass, int rowspan, int colspan) { o.Append("<td"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } if (rowspan > 1) { o.Append(" rowspan=\""); o.Append(rowspan); o.Append("\""); } if (colspan > 1) { o.Append(" colspan=\""); o.Append(colspan); o.Append("\""); } o.Append(">"); } public static void TD_C(ref StringBuilder o) { o.Append("</td>"); } public static void TABLE_O(ref StringBuilder o, string pclass) { o.Append("<table"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(">\n\t"); } public static void TABLE_C(ref StringBuilder o) { o.Append("</table>\n"); } public static void BLOCKQUOTE_O(ref StringBuilder o, string pclass) { o.Append("<blockquote"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void BLOCKQUOTE_C(ref StringBuilder o) { o.Append("</blockquote>\n"); } public static void BR(ref StringBuilder o) { o.Append("<br />\n"); } public static void HR(ref StringBuilder o, string pclass) { o.Append("<hr"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void UL_O(ref StringBuilder o, string pclass) { o.Append("<ul"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void UL_C(ref StringBuilder o) { o.Append("</ul>\n"); } public static void OL_O(ref StringBuilder o, string pclass) { o.Append("<ol"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void OL_C(ref StringBuilder o) { o.Append("</ol>\n"); } public static void LI_O(ref StringBuilder o, string pclass) { o.Append("<li"); if (pclass.Length > 0) { GenericClass(ref o, pclass); } o.Append(" />\n"); } public static void LI_C(ref StringBuilder o) { o.Append("</li>\n"); } public static void GenericClass(ref StringBuilder o, string pclass) { o.Append(" class=\""); o.Append(pclass); o.Append("\""); } public static void InsertProtoTypeAJAX(ref StringBuilder o) { o.Append("<script type=\"text/javascript\" src=\"prototype.js\"></script>\n"); o.Append("<script type=\"text/javascript\" src=\"updater.js\"></script>\n"); } public static void InsertPeriodicUpdaters(ref StringBuilder o, string[] divID, int[] seconds, string[] reportfrag) { o.Append("<script type=\"text/javascript\">\n"); o.Append( @" // <![CDATA[ document.observe('dom:loaded', function() { /* first arg : div to update second arg : interval to poll in seconds third arg : file to get data */ "); for (int i = 0; i < divID.Length; i++) { o.Append("new updater('"); o.Append(divID[i]); o.Append("', "); o.Append(seconds[i]); o.Append(", '"); o.Append(reportfrag[i]); o.Append("');\n"); } o.Append(@" }); // ]]> </script>"); } public static void HtmlHeaders_O(ref StringBuilder o) { o.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); o.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"nl\">"); o.Append("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />"); } public static void HtmlHeaders_C(ref StringBuilder o) { o.Append("</HEAD>"); o.Append("<BODY>"); } public static void AddReportLinks(ref StringBuilder o, Dictionary<string, IStatsController> reports, string pClass) { int repcount = 0; foreach (string str in reports.Keys) { if (reports[str].ReportName.Length > 0) { if (repcount > 0) { o.Append("|&nbsp;&nbsp;"); } A(ref o, reports[str].ReportName, str, pClass); o.Append("&nbsp;&nbsp;"); repcount++; } } } public static void A(ref StringBuilder o, string linktext, string linkhref, string pClass) { o.Append("<A"); if (pClass.Length > 0) { GenericClass(ref o, pClass); } o.Append(" href=\""); o.Append(linkhref); o.Append("\">"); o.Append(linktext); o.Append("</A>"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class MARSSessionPoolingTest { private const string COMMAND_STATUS = "select count(*) as ConnectionCount from sys.dm_exec_connections where session_id=@@spid and net_transport='Session'; select count(*) as ActiveRequestCount from sys.dm_exec_requests where session_id=@@spid and status='running' or session_id=@@spid and status='suspended'"; private const string COMMAND_SPID = "select @@spid"; private const int CONCURRENT_COMMANDS = 5; private const string _COMMAND_RPC = "sp_who"; private const string _COMMAND_SQL = "select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; " + "select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; " + "select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; " + "select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; " + "select * from sys.databases; print 'THIS IS THE END!'"; private static readonly string _testConnString = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { PacketSize = 512, MaxPoolSize = 1, MultipleActiveResultSets = true }).ConnectionString; [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void MarsExecuteScalar_AllFlavors() { TestMARSSessionPooling("Case: Text, ExecuteScalar", _testConnString, CommandType.Text, ExecuteType.ExecuteScalar, ReaderTestType.ReaderClose, GCType.Wait); TestMARSSessionPooling("Case: RPC, ExecuteScalar", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteScalar, ReaderTestType.ReaderClose, GCType.Wait); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void MarsExecuteNonQuery_AllFlavors() { TestMARSSessionPooling("Case: Text, ExecuteNonQuery", _testConnString, CommandType.Text, ExecuteType.ExecuteNonQuery, ReaderTestType.ReaderClose, GCType.Wait); TestMARSSessionPooling("Case: RPC, ExecuteNonQuery", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteNonQuery, ReaderTestType.ReaderClose, GCType.Wait); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void MarsExecuteReader_Text_NoGC() { TestMARSSessionPooling("Case: Text, ExecuteReader, ReaderClose", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ReaderClose, GCType.Wait); TestMARSSessionPooling("Case: Text, ExecuteReader, ReaderDispose", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ReaderDispose, GCType.Wait); TestMARSSessionPooling("Case: Text, ExecuteReader, ConnectionClose", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ConnectionClose, GCType.Wait); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void MarsExecuteReader_RPC_NoGC() { TestMARSSessionPooling("Case: RPC, ExecuteReader, ReaderClose", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderClose, GCType.Wait); TestMARSSessionPooling("Case: RPC, ExecuteReader, ReaderDispose", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderDispose, GCType.Wait); TestMARSSessionPooling("Case: RPC, ExecuteReader, ConnectionClose", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ConnectionClose, GCType.Wait); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void MarsExecuteReader_Text_WithGC() { TestMARSSessionPooling("Case: Text, ExecuteReader, GC-Wait", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ReaderGC, GCType.Wait); TestMARSSessionPooling("Case: Text, ExecuteReader, GC-NoWait", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ReaderGC, GCType.NoWait); } [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))] public static void MarsExecuteReader_StoredProcedure_WithGC() { TestMARSSessionPooling("Case: RPC, ExecuteReader, GC-Wait", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderGC, GCType.Wait); TestMARSSessionPooling("Case: RPC, ExecuteReader, GC-NoWait", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderGC, GCType.NoWait); TestMARSSessionPooling("Case: Text, ExecuteReader, NoCloses", _testConnString + " ", CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.NoCloses, GCType.Wait); TestMARSSessionPooling("Case: RPC, ExecuteReader, NoCloses", _testConnString + " ", CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.NoCloses, GCType.Wait); } private enum ExecuteType { ExecuteScalar, ExecuteNonQuery, ExecuteReader, } private enum ReaderTestType { ReaderClose, ReaderDispose, ReaderGC, ConnectionClose, NoCloses, } private enum GCType { Wait, NoWait, } [MethodImpl(MethodImplOptions.NoInlining)] private static void TestMARSSessionPooling(string caseName, string connectionString, CommandType commandType, ExecuteType executeType, ReaderTestType readerTestType, GCType gcType) { SqlCommand[] cmd = new SqlCommand[CONCURRENT_COMMANDS]; SqlDataReader[] gch = new SqlDataReader[CONCURRENT_COMMANDS]; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); for (int i = 0; i < CONCURRENT_COMMANDS; i++) { // Prepare all commands cmd[i] = con.CreateCommand(); switch (commandType) { case CommandType.Text: cmd[i].CommandText = _COMMAND_SQL; cmd[i].CommandTimeout = 120; break; case CommandType.StoredProcedure: cmd[i].CommandText = _COMMAND_RPC; cmd[i].CommandTimeout = 120; cmd[i].CommandType = CommandType.StoredProcedure; break; } } for (int i = 0; i < CONCURRENT_COMMANDS; i++) { switch (executeType) { case ExecuteType.ExecuteScalar: cmd[i].ExecuteScalar(); break; case ExecuteType.ExecuteNonQuery: cmd[i].ExecuteNonQuery(); break; case ExecuteType.ExecuteReader: if (readerTestType != ReaderTestType.ReaderGC) gch[i] = cmd[i].ExecuteReader(); switch (readerTestType) { case ReaderTestType.ReaderClose: { gch[i].Dispose(); break; } case ReaderTestType.ReaderDispose: gch[i].Dispose(); break; case ReaderTestType.ReaderGC: gch[i] = null; WeakReference weak = OpenReaderThenNullify(cmd[i]); GC.Collect(); if (gcType == GCType.Wait) { GC.WaitForPendingFinalizers(); Assert.False(weak.IsAlive, "Error - target still alive!"); } break; case ReaderTestType.ConnectionClose: GC.SuppressFinalize(gch[i]); con.Close(); con.Open(); break; case ReaderTestType.NoCloses: GC.SuppressFinalize(gch[i]); break; } break; } if (readerTestType != ReaderTestType.NoCloses) { con.Close(); con.Open(); // Close and open, to re-assure collection! } SqlCommand verificationCmd = con.CreateCommand(); verificationCmd.CommandText = COMMAND_STATUS; using (SqlDataReader rdr = verificationCmd.ExecuteReader()) { rdr.Read(); int connections = (int)rdr.GetValue(0); rdr.NextResult(); rdr.Read(); int requests = (int)rdr.GetValue(0); switch (executeType) { case ExecuteType.ExecuteScalar: case ExecuteType.ExecuteNonQuery: // 1 for connection, 1 for command Assert.True(connections == 2, "Failure - incorrect number of connections for ExecuteScalar! #connections: " + connections); // only 1 executing Assert.True(requests == 1, "Failure - incorrect number of requests for ExecuteScalar! #requests: " + requests); break; case ExecuteType.ExecuteReader: switch (readerTestType) { case ReaderTestType.ReaderClose: case ReaderTestType.ReaderDispose: case ReaderTestType.ConnectionClose: // 1 for connection, 1 for command Assert.True(connections == 2, "Failure - Incorrect number of connections for ReaderClose / ReaderDispose / ConnectionClose! #connections: " + connections); // only 1 executing Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderClose/ReaderDispose/ConnectionClose! #requests: " + requests); break; case ReaderTestType.ReaderGC: switch (gcType) { case GCType.Wait: // 1 for connection, 1 for open reader Assert.True(connections == 2, "Failure - incorrect number of connections for ReaderGCWait! #connections: " + connections); // only 1 executing Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderGCWait! #requests: " + requests); break; case GCType.NoWait: // 1 for connection, 1 for open reader Assert.True(connections == 2, "Failure - incorrect number of connections for ReaderGCNoWait! #connections: " + connections); // only 1 executing Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderGCNoWait! #requests: " + requests); break; } break; case ReaderTestType.NoCloses: // 1 for connection, 1 for current command, 1 for 0 based array offset, plus i for open readers Assert.True(connections == (3 + i), "Failure - incorrect number of connections for NoCloses: " + connections); // 1 for current command, 1 for 0 based array offset, plus i open readers Assert.True(requests == (2 + i), "Failure - incorrect number of requests for NoCloses: " + requests); break; } break; } } } } } private static WeakReference OpenReaderThenNullify(SqlCommand command) { SqlDataReader reader = command.ExecuteReader(); WeakReference weak = new WeakReference(reader); reader = null; return weak; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using SR = System.Reflection; using System.Runtime.CompilerServices; using Zenject.ReflectionBaking.Mono.Cecil.Cil; using NUnit.Framework; namespace Zenject.ReflectionBaking.Mono.Cecil.Tests { [TestFixture] public class ImportCecilTests : BaseTestFixture { [Test] public void ImportStringByRef () { var get_string = Compile<Func<string, string>> ((module, body) => { var type = module.Types [1]; var method_by_ref = new MethodDefinition { Name = "ModifyString", IsPrivate = true, IsStatic = true, }; type.Methods.Add (method_by_ref); method_by_ref.MethodReturnType.ReturnType = module.Import (typeof (void).ToDefinition ()); method_by_ref.Parameters.Add (new ParameterDefinition (module.Import (typeof (string).ToDefinition ()))); method_by_ref.Parameters.Add (new ParameterDefinition (module.Import (new ByReferenceType (typeof (string).ToDefinition ())))); var m_il = method_by_ref.Body.GetILProcessor (); m_il.Emit (OpCodes.Ldarg_1); m_il.Emit (OpCodes.Ldarg_0); m_il.Emit (OpCodes.Stind_Ref); m_il.Emit (OpCodes.Ret); var v_0 = new VariableDefinition (module.Import (typeof (string).ToDefinition ())); body.Variables.Add (v_0); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Stloc, v_0); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldloca, v_0); il.Emit (OpCodes.Call, method_by_ref); il.Emit (OpCodes.Ldloc_0); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("foo", get_string ("foo")); } [Test] public void ImportStringArray () { var identity = Compile<Func<string [,], string [,]>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ret); }); var array = new string [2, 2]; Assert.AreEqual (array, identity (array)); } [Test] public void ImportFieldStringEmpty () { var get_empty = Compile<Func<string>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldsfld, module.Import (typeof (string).GetField ("Empty").ToDefinition ())); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("", get_empty ()); } [Test] public void ImportStringConcat () { var concat = Compile<Func<string, string, string>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Call, module.Import (typeof (string).GetMethod ("Concat", new [] { typeof (string), typeof (string) }).ToDefinition ())); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("FooBar", concat ("Foo", "Bar")); } public class Generic<T> { public T Field; public T Method (T t) { return t; } public TS GenericMethod<TS> (T t, TS s) { return s; } public Generic<TS> ComplexGenericMethod<TS> (T t, TS s) { return new Generic<TS> { Field = s }; } } [Test] public void ImportGenericField () { var get_field = Compile<Func<Generic<string>, string>> ((module, body) => { var generic_def = module.Import (typeof (Generic<>)).Resolve (); var field_def = generic_def.Fields.Where (f => f.Name == "Field").First (); var field_string = field_def.MakeGeneric (module.Import (typeof (string))); var field_ref = module.Import (field_string); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldfld, field_ref); il.Emit (OpCodes.Ret); }); var generic = new Generic<string> { Field = "foo", }; Assert.AreEqual ("foo", get_field (generic)); } [Test] public void ImportGenericMethod () { var generic_identity = Compile<Func<Generic<int>, int, int>> ((module, body) => { var generic_def = module.Import (typeof (Generic<>)).Resolve (); var method_def = generic_def.Methods.Where (m => m.Name == "Method").First (); var method_int = method_def.MakeGeneric (module.Import (typeof (int))); var method_ref = module.Import (method_int); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Callvirt, method_ref); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, generic_identity (new Generic<int> (), 42)); } [Test] public void ImportGenericMethodSpec () { var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => { var generic_def = module.Import (typeof (Generic<>)).Resolve (); var method_def = generic_def.Methods.Where (m => m.Name == "GenericMethod").First (); var method_string = method_def.MakeGeneric (module.Import (typeof (string))); var method_instance = method_string.MakeGenericMethod (module.Import (typeof (int))); var method_ref = module.Import (method_instance); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Callvirt, method_ref); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42)); } [Test] public void ImportComplexGenericMethodSpec () { var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => { var generic_def = module.Import (typeof (Generic<>)).Resolve (); var method_def = generic_def.Methods.Where (m => m.Name == "ComplexGenericMethod").First (); var method_string = method_def.MakeGeneric (module.Import (typeof (string))); var method_instance = method_string.MakeGenericMethod (module.Import (typeof (int))); var method_ref = module.Import (method_instance); var field_def = generic_def.Fields.Where (f => f.Name == "Field").First (); var field_int = field_def.MakeGeneric (module.Import (typeof (int))); var field_ref = module.Import (field_int); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Callvirt, method_ref); il.Emit (OpCodes.Ldfld, field_ref); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42)); } [Test] public void ImportMethodOnOpenGeneric () { var generic = typeof (Generic<>).ToDefinition (); var module = ModuleDefinition.CreateModule ("foo", ModuleKind.Dll); var method = module.Import (generic.GetMethod ("Method")); Assert.AreEqual ("T Zenject.ReflectionBaking.Mono.Cecil.Tests.ImportCecilTests/Generic`1::Method(T)", method.FullName); } public class ContextGeneric1Method2<G1> { public G1 GenericMethod<R1, S1> (R1 r, S1 s) { return default (G1); } } public class ContextGeneric2Method1<G2, H2> { public R2 GenericMethod<R2> (G2 g, H2 h) { return default (R2); } } public class NestedGenericsA<A> { public class NestedGenericsB<B> { public class NestedGenericsC<C> { public A GenericMethod (B b, C c) { return default (A); } } } } [Test] public void ContextGenericTest () { var module = ModuleDefinition.ReadModule (typeof (ContextGeneric1Method2<>).Module.FullyQualifiedName); // by mixing open generics with 2 & 1 parameters, we make sure the right context is used (because otherwise, an exception will be thrown) var type = typeof (ContextGeneric1Method2<>).MakeGenericType (typeof (ContextGeneric2Method1<,>)); var meth = type.GetMethod ("GenericMethod"); var imported_type = module.Import (type); var method = module.Import (meth, imported_type); Assert.AreEqual ("G1 Zenject.ReflectionBaking.Mono.Cecil.Tests.ImportCecilTests/ContextGeneric1Method2`1<Mono.Cecil.Tests.ImportCecilTests/ContextGeneric2Method1`2<G2,H2>>::GenericMethod<R1,S1>(R1,S1)", method.FullName); // and the other way around type = typeof (ContextGeneric2Method1<,>).MakeGenericType (typeof (ContextGeneric1Method2<>), typeof (IList<>)); meth = type.GetMethod ("GenericMethod"); imported_type = module.Import (type); method = module.Import (meth, imported_type); Assert.AreEqual ("R2 Zenject.ReflectionBaking.Mono.Cecil.Tests.ImportCecilTests/ContextGeneric2Method1`2<Mono.Cecil.Tests.ImportCecilTests/ContextGeneric1Method2`1<G1>,System.Collections.Generic.IList`1<T>>::GenericMethod<R2>(G2,H2)", method.FullName); // not sure about this one type = typeof (NestedGenericsA<string>.NestedGenericsB<int>.NestedGenericsC<float>); meth = type.GetMethod ("GenericMethod"); imported_type = module.Import (type); method = module.Import (meth, imported_type); Assert.AreEqual ("A Zenject.ReflectionBaking.Mono.Cecil.Tests.ImportCecilTests/NestedGenericsA`1/NestedGenericsB`1/NestedGenericsC`1<System.String,System.Int32,System.Single>::GenericMethod(B,C)", method.FullName); // We need both the method & type ! type = typeof (Generic<>).MakeGenericType (typeof (string)); meth = type.GetMethod ("ComplexGenericMethod"); imported_type = module.Import (type); method = module.Import (meth, imported_type); Assert.AreEqual ("Zenject.ReflectionBaking.Mono.Cecil.Tests.ImportCecilTests/Generic`1<TS> Mono.Cecil.Tests.ImportCecilTests/Generic`1<System.String>::ComplexGenericMethod<TS>(T,TS)", method.FullName); } delegate void Emitter (ModuleDefinition module, MethodBody body); [MethodImpl (MethodImplOptions.NoInlining)] static TDelegate Compile<TDelegate> (Emitter emitter) where TDelegate : class { var name = GetTestCaseName (); var module = CreateTestModule<TDelegate> (name, emitter); var assembly = LoadTestModule (module); return CreateRunDelegate<TDelegate> (GetTestCase (name, assembly)); } static TDelegate CreateRunDelegate<TDelegate> (Type type) where TDelegate : class { return (TDelegate) (object) Delegate.CreateDelegate (typeof (TDelegate), type.GetMethod ("Run")); } static Type GetTestCase (string name, SR.Assembly assembly) { return assembly.GetType (name); } static SR.Assembly LoadTestModule (ModuleDefinition module) { using (var stream = new MemoryStream ()) { module.Write (stream); File.WriteAllBytes (Path.Combine (Path.Combine (Path.GetTempPath (), "cecil"), module.Name + ".dll"), stream.ToArray ()); return SR.Assembly.Load (stream.ToArray ()); } } static ModuleDefinition CreateTestModule<TDelegate> (string name, Emitter emitter) { var module = CreateModule (name); var type = new TypeDefinition ( "", name, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract, module.Import (typeof (object))); module.Types.Add (type); var method = CreateMethod (type, typeof (TDelegate).GetMethod ("Invoke")); emitter (module, method.Body); return module; } static MethodDefinition CreateMethod (TypeDefinition type, SR.MethodInfo pattern) { var module = type.Module; var method = new MethodDefinition { Name = "Run", IsPublic = true, IsStatic = true, }; type.Methods.Add (method); method.MethodReturnType.ReturnType = module.Import (pattern.ReturnType); foreach (var parameter_pattern in pattern.GetParameters ()) method.Parameters.Add (new ParameterDefinition (module.Import (parameter_pattern.ParameterType))); return method; } static ModuleDefinition CreateModule (string name) { return ModuleDefinition.CreateModule (name, ModuleKind.Dll); } [MethodImpl (MethodImplOptions.NoInlining)] static string GetTestCaseName () { var stack_trace = new StackTrace (); var stack_frame = stack_trace.GetFrame (2); return "ImportCecil_" + stack_frame.GetMethod ().Name; } } }
// 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.Text { using System; using System.Runtime; using System.Diagnostics.Contracts; [Serializable] public sealed class EncoderReplacementFallback : EncoderFallback { // Our variables private String strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public EncoderReplacementFallback() : this("?") { } public EncoderReplacementFallback(String replacement) { // Must not be null if (replacement == null) throw new ArgumentNullException("replacement"); Contract.EndContractBlock(); // Make sure it doesn't have bad surrogate pairs bool bFoundHigh=false; for (int i = 0; i < replacement.Length; i++) { // Found a surrogate? if (Char.IsSurrogate(replacement,i)) { // High or Low? if (Char.IsHighSurrogate(replacement, i)) { // if already had a high one, stop if (bFoundHigh) break; // break & throw at the bFoundHIgh below bFoundHigh = true; } else { // Low, did we have a high? if (!bFoundHigh) { // Didn't have one, make if fail when we stop bFoundHigh = true; break; } // Clear flag bFoundHigh = false; } } // If last was high we're in trouble (not surrogate so not low surrogate, so break) else if (bFoundHigh) break; } if (bFoundHigh) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", "replacement")); strDefault = replacement; } public String DefaultString { get { return strDefault; } } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderReplacementFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return strDefault.Length; } } public override bool Equals(Object value) { EncoderReplacementFallback that = value as EncoderReplacementFallback; if (that != null) { return (this.strDefault == that.strDefault); } return (false); } public override int GetHashCode() { return strDefault.GetHashCode(); } } public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer { // Store our default string private String strDefault; int fallbackCount = -1; int fallbackIndex = -1; // Construction public EncoderReplacementFallbackBuffer(EncoderReplacementFallback fallback) { // 2X in case we're a surrogate pair this.strDefault = fallback.DefaultString + fallback.DefaultString; } // Fallback Methods public override bool Fallback(char charUnknown, int index) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if (fallbackCount >= 1) { // If we're recursive we may still have something in our buffer that makes this a surrogate if (char.IsHighSurrogate(charUnknown) && fallbackCount >= 0 && char.IsLowSurrogate(strDefault[fallbackIndex+1])) ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknown, strDefault[fallbackIndex+1])); // Nope, just one character ThrowLastCharRecursive(unchecked((int)charUnknown)); } // Go ahead and get our fallback // Divide by 2 because we aren't a surrogate pair fallbackCount = strDefault.Length/2; fallbackIndex = -1; return fallbackCount != 0; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair if (!Char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException("charUnknownHigh", Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); if (!Char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException("CharUnknownLow", Environment.GetResourceString("ArgumentOutOfRange_Range", 0xDC00, 0xDFFF)); Contract.EndContractBlock(); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if (fallbackCount >= 1) ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknownHigh, charUnknownLow)); // Go ahead and get our fallback fallbackCount = strDefault.Length; fallbackIndex = -1; return fallbackCount != 0; } public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. fallbackCount--; fallbackIndex++; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (fallbackCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (fallbackCount == int.MaxValue) { fallbackCount = -1; return '\0'; } // Now make sure its in the expected range Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range"); return strDefault[fallbackIndex]; } public override bool MovePrevious() { // Back up one, only if we just processed the last character (or earlier) if (fallbackCount >= -1 && fallbackIndex >= 0) { fallbackIndex--; fallbackCount++; return true; } // Return false 'cause we couldn't do it. return false; } // How many characters left to output? public override int Remaining { get { // Our count is 0 for 1 character left. return (fallbackCount < 0) ? 0 : fallbackCount; } } // Clear the buffer [System.Security.SecuritySafeCritical] // auto-generated public override unsafe void Reset() { fallbackCount = -1; fallbackIndex = 0; charStart = null; bFallingBack = false; } } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Threading; using System.Net.Sockets; using System.Threading.Tasks; using Cassandra.Tasks; namespace Cassandra { internal class ControlConnection : IDisposable { private const string SelectPeers = "SELECT peer, data_center, rack, tokens, rpc_address FROM system.peers"; private const string SelectLocal = "SELECT * FROM system.local WHERE key='local'"; private const CassandraEventType CassandraEventTypes = CassandraEventType.TopologyChange | CassandraEventType.StatusChange | CassandraEventType.SchemaChange; private static readonly IPAddress BindAllAddress = new IPAddress(new byte[4]); private volatile Host _host; private volatile Connection _connection; // ReSharper disable once InconsistentNaming private static readonly Logger _logger = new Logger(typeof (ControlConnection)); private readonly Configuration _config; private readonly IReconnectionPolicy _reconnectionPolicy; private IReconnectionSchedule _reconnectionSchedule; private readonly Timer _reconnectionTimer; private int _isShutdown; private int _refreshCounter; private Task<bool> _reconnectTask; /// <summary> /// Gets the recommended binary protocol version to be used for this cluster. /// </summary> internal byte ProtocolVersion { get; private set; } private Metadata Metadata { get; set; } internal Host Host { get { return _host; } set { _host = value; } } /// <summary> /// The address of the endpoint used by the ControlConnection /// </summary> internal IPEndPoint BindAddress { get { if (_connection == null) { return null; } return _connection.Address; } } internal ControlConnection(byte initialProtocolVersion, Configuration config, Metadata metadata) { Metadata = metadata; _reconnectionPolicy = config.Policies.ReconnectionPolicy; _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); _reconnectionTimer = new Timer(_ => Reconnect(), null, Timeout.Infinite, Timeout.Infinite); _config = config; ProtocolVersion = initialProtocolVersion; } public void Dispose() { Shutdown(); } /// <summary> /// Tries to create a connection to any of the contact points and retrieve cluster metadata for the first time. Not thread-safe. /// </summary> /// <exception cref="NoHostAvailableException" /> /// <exception cref="DriverInternalError" /> internal void Init() { _logger.Info("Trying to connect the ControlConnection"); TaskHelper.WaitToComplete(Connect(true), _config.SocketOptions.ConnectTimeoutMillis); try { SubscribeEventHandlers(); RefreshNodeList(); Metadata.RefreshKeyspaces(false); } catch (SocketException ex) { //There was a problem using the connection obtained //It is not usual but can happen _logger.Error("An error occurred when trying to retrieve the cluster metadata, retrying.", ex); //Retry one more time and throw if there is problem TaskHelper.WaitToComplete(Reconnect(), _config.SocketOptions.ConnectTimeoutMillis); } } /// <summary> /// Tries to create the a connection to the cluster /// </summary> /// <exception cref="NoHostAvailableException" /> /// <exception cref="DriverInternalError" /> private Task<bool> Connect(bool firstTime) { IEnumerable<Host> hosts = Metadata.Hosts; if (!firstTime) { _logger.Info("Trying to reconnect the ControlConnection"); //Use the load balancing policy to determine which host to use hosts = _config.Policies.LoadBalancingPolicy.NewQueryPlan(null, null); } return IterateAndConnect(hosts.GetEnumerator(), new Dictionary<IPEndPoint, Exception>()); } private Task<bool> IterateAndConnect(IEnumerator<Host> hostsEnumerator, Dictionary<IPEndPoint, Exception> triedHosts) { var available = hostsEnumerator.MoveNext(); if (!available) { throw new NoHostAvailableException(triedHosts); } var host = hostsEnumerator.Current; var c = new Connection(ProtocolVersion, host.Address, _config); return ((Task) c .Open()) .ContinueWith(t => { if (t.Status == TaskStatus.RanToCompletion) { _connection = c; _host = host; _logger.Info("Connection established to {0}", c.Address); return TaskHelper.ToTask(true); } if (t.IsFaulted && t.Exception != null) { var ex = t.Exception.InnerException; if (ex is UnsupportedProtocolVersionException) { //Use the protocol version used to parse the response message var nextVersion = c.ProtocolVersion; if (nextVersion >= ProtocolVersion) { //Processor could reorder instructions in such way that the connection protocol version is not up to date. nextVersion = (byte)(ProtocolVersion - 1); } _logger.Info(String.Format("Unsupported protocol version {0}, trying with version {1}", ProtocolVersion, nextVersion)); ProtocolVersion = nextVersion; c.Dispose(); if (ProtocolVersion < 1) { throw new DriverInternalError("Invalid protocol version"); } //Retry using the new protocol version return Connect(true); } //There was a socket exception or an authentication exception triedHosts.Add(host.Address, ex); c.Dispose(); return IterateAndConnect(hostsEnumerator, triedHosts); } throw new TaskCanceledException("The ControlConnection could not be connected."); }, TaskContinuationOptions.ExecuteSynchronously) .Unwrap(); } internal Task<bool> Reconnect() { //If there is another thread reconnecting, use the same task var tcs = new TaskCompletionSource<bool>(); var currentTask = Interlocked.CompareExchange(ref _reconnectTask, tcs.Task, null); if (currentTask != null) { return currentTask; } Unsubscribe(); Connect(false).ContinueWith(t => { if (t.Exception != null) { Interlocked.Exchange(ref _reconnectTask, null); tcs.TrySetException(t.Exception.InnerException); var delay = _reconnectionSchedule.NextDelayMs(); _reconnectionTimer.Change(delay, Timeout.Infinite); _logger.Error("ControlConnection was not able to reconnect: " + t.Exception.InnerException); return; } try { RefreshNodeList(); Metadata.RefreshKeyspaces(false); _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); tcs.TrySetResult(true); Interlocked.Exchange(ref _reconnectTask, null); _logger.Info("ControlConnection reconnected to host {0}", _host.Address); } catch (Exception ex) { Interlocked.Exchange(ref _reconnectTask, null); _logger.Error("There was an error when trying to refresh the ControlConnection", ex); _reconnectionTimer.Change(_reconnectionSchedule.NextDelayMs(), Timeout.Infinite); tcs.TrySetException(ex); } }); return tcs.Task; } internal void Refresh() { if (Interlocked.Increment(ref _refreshCounter) != 1) { //Only one refresh at a time Interlocked.Decrement(ref _refreshCounter); return; } var reconnect = false; try { RefreshNodeList(); Metadata.RefreshKeyspaces(false); _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); } catch (SocketException ex) { _logger.Error("There was a SocketException when trying to refresh the ControlConnection", ex); reconnect = true; } catch (Exception ex) { _logger.Error("There was an error when trying to refresh the ControlConnection", ex); } finally { Interlocked.Decrement(ref _refreshCounter); } if (reconnect) { Reconnect(); } } public void Shutdown() { if (Interlocked.Increment(ref _isShutdown) != 1) { //Only shutdown once return; } var c = _connection; if (c != null) { c.Dispose(); } _reconnectionTimer.Change(Timeout.Infinite, Timeout.Infinite); _reconnectionTimer.Dispose(); } /// <summary> /// Gets the next connection and setup the event listener for the host and connection. /// Not thread-safe. /// </summary> private void SubscribeEventHandlers() { _host.Down += OnHostDown; _connection.CassandraEventResponse += OnConnectionCassandraEvent; //Register to events on the connection var registerTask = _connection.Send(new RegisterForEventRequest(ProtocolVersion, CassandraEventTypes)); TaskHelper.WaitToComplete(registerTask, 10000); if (!(registerTask.Result is ReadyResponse)) { throw new DriverInternalError("Expected ReadyResponse, obtained " + registerTask.Result.GetType().Name); } } private void Unsubscribe() { var c = _connection; var h = _host; if (c != null) { c.CassandraEventResponse -= OnConnectionCassandraEvent; } if (h != null) { h.Down -= OnHostDown; } } private void OnHostDown(Host h, long reconnectionDelay) { h.Down -= OnHostDown; _logger.Warning("Host {0} used by the ControlConnection DOWN", h.Address); Task.Factory.StartNew(() => Reconnect(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } private void OnConnectionCassandraEvent(object sender, CassandraEventArgs e) { //This event is invoked from a worker thread (not a IO thread) if (e is TopologyChangeEventArgs) { var tce = (TopologyChangeEventArgs)e; if (tce.What == TopologyChangeEventArgs.Reason.NewNode || tce.What == TopologyChangeEventArgs.Reason.RemovedNode) { Refresh(); return; } } if (e is StatusChangeEventArgs) { var sce = (StatusChangeEventArgs)e; //The address in the Cassandra event message needs to be translated var address = TranslateAddress(sce.Address); _logger.Info("Received Node status change event: host {0} is {1}", address, sce.What.ToString().ToUpper()); if (sce.What == StatusChangeEventArgs.Reason.Up) { Metadata.BringUpHost(address, this); return; } if (sce.What == StatusChangeEventArgs.Reason.Down) { Metadata.SetDownHost(address, this); return; } } if (e is SchemaChangeEventArgs) { var ssc = (SchemaChangeEventArgs)e; if (!String.IsNullOrEmpty(ssc.Table)) { Metadata.RefreshTable(ssc.Keyspace, ssc.Table); return; } if (ssc.FunctionName != null) { Metadata.ClearFunction(ssc.Keyspace, ssc.FunctionName, ssc.Signature); return; } if (ssc.AggregateName != null) { Metadata.ClearAggregate(ssc.Keyspace, ssc.AggregateName, ssc.Signature); return; } if (ssc.Type != null) { return; } if (ssc.What == SchemaChangeEventArgs.Reason.Dropped) { Metadata.RemoveKeyspace(ssc.Keyspace); return; } Metadata.RefreshSingleKeyspace(ssc.What == SchemaChangeEventArgs.Reason.Created, ssc.Keyspace); } } private IPEndPoint TranslateAddress(IPEndPoint value) { return _config.AddressTranslator.Translate(value); } private void RefreshNodeList() { _logger.Info("Refreshing node list"); var localRow = Query(SelectLocal).FirstOrDefault(); var rsPeers = Query(SelectPeers); if (localRow == null) { _logger.Error("Local host metadata could not be retrieved"); return; } Metadata.Partitioner = localRow.GetValue<string>("partitioner"); UpdateLocalInfo(localRow); UpdatePeersInfo(rsPeers); _logger.Info("Node list retrieved successfully"); } internal void UpdateLocalInfo(Row row) { var localhost = _host; // Update cluster name, DC and rack for the one node we are connected to var clusterName = row.GetValue<string>("cluster_name"); if (clusterName != null) { Metadata.ClusterName = clusterName; } localhost.SetLocationInfo(row.GetValue<string>("data_center"), row.GetValue<string>("rack")); localhost.Tokens = row.GetValue<IEnumerable<string>>("tokens") ?? new string[0]; } internal void UpdatePeersInfo(IEnumerable<Row> rs) { var foundPeers = new HashSet<IPEndPoint>(); foreach (var row in rs) { var address = GetAddressForPeerHost(row, _config.AddressTranslator, _config.ProtocolOptions.Port); if (address == null) { _logger.Error("No address found for host, ignoring it."); continue; } foundPeers.Add(address); var host = Metadata.GetHost(address); if (host == null) { host = Metadata.AddHost(address); } host.SetLocationInfo(row.GetValue<string>("data_center"), row.GetValue<string>("rack")); host.Tokens = row.GetValue<IEnumerable<string>>("tokens") ?? new string[0]; } // Removes all those that seems to have been removed (since we lost the control connection or not valid contact point) foreach (var address in Metadata.AllReplicas()) { if (!address.Equals(_host.Address) && !foundPeers.Contains(address)) { Metadata.RemoveHost(address); } } } /// <summary> /// Uses system.peers values to build the Address translator /// </summary> internal static IPEndPoint GetAddressForPeerHost(Row row, IAddressTranslator translator, int port) { var address = row.GetValue<IPAddress>("rpc_address"); if (address == null) { return null; } if (BindAllAddress.Equals(address) && !row.IsNull("peer")) { address = row.GetValue<IPAddress>("peer"); _logger.Warning(String.Format("Found host with 0.0.0.0 as rpc_address, using listen_address ({0}) to contact it instead. If this is incorrect you should avoid the use of 0.0.0.0 server side.", address)); } return translator.Translate(new IPEndPoint(address, port)); } /// <summary> /// Uses the active connection to execute a query /// </summary> public RowSet Query(string cqlQuery, bool retry = false) { var request = new QueryRequest(ProtocolVersion, cqlQuery, false, QueryProtocolOptions.Default); var task = _connection.Send(request); try { TaskHelper.WaitToComplete(task, 10000); } catch (SocketException ex) { const string message = "There was an error while executing on the host {0} the query '{1}'"; _logger.Error(string.Format(message, cqlQuery, _connection.Address), ex); if (retry) { //Try to connect to another host TaskHelper.WaitToComplete(Reconnect(), _config.SocketOptions.ConnectTimeoutMillis); //Try to execute again without retry return Query(cqlQuery, false); } throw; } return GetRowSet(task.Result); } /// <summary> /// Validates that the result contains a RowSet and returns it. /// </summary> /// <exception cref="NullReferenceException" /> /// <exception cref="DriverInternalError" /> public static RowSet GetRowSet(AbstractResponse response) { if (response == null) { throw new NullReferenceException("Response can not be null"); } if (!(response is ResultResponse)) { throw new DriverInternalError("Expected rows, obtained " + response.GetType().FullName); } var result = (ResultResponse) response; if (!(result.Output is OutputRows)) { throw new DriverInternalError("Expected rows output, obtained " + result.Output.GetType().FullName); } return ((OutputRows) result.Output).RowSet; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Data; using System.Text; using System.Windows.Forms; using System.Reflection; namespace CloudBox.Controller { public class ColorTable : LabelRotate { public event EventHandler SelectedIndexChanged; public Color SelectedItem { get { if (m_selindex < 0 || m_selindex >= m_colors.Count) return Color.White; return m_colors[m_selindex]; } set { if (m_selindex < m_colors.Count && value == m_colors[m_selindex]) return; int index = m_colors.IndexOf(value); if (index < 0) return; SetIndex(index); } } public bool ColorExist(Color c) { int index = m_colors.IndexOf(c); return index >= 0; } int m_cols = 0; int m_rows = 0; public int Cols { get { return m_cols; } set { m_cols = value; m_rows = m_colors.Count / m_cols; if ((m_colors.Count % m_cols) != 0) m_rows++; } } Size m_fieldSize = new Size(12, 12); public Size FieldSize { get { return m_fieldSize; } set { m_fieldSize = value; } } int CompareColorByValue(Color c1, Color c2) { int color1 = c1.R << 16 | c1.G << 8 | c1.B; int color2 = c2.R << 16 | c2.G << 8 | c2.B; if (color1 > color2) return -1; if (color1 < color2) return 1; return 0; } int CompareColorByHue(Color c1, Color c2) { float h1 = c1.GetHue(); float h2 = c2.GetHue(); if (h1 < h2) return -1; if (h1 > h2) return 1; return 0; } int CompareColorByBrightness(Color c1, Color c2) { // bug, using float causes the sort to go into infinite loop in release, // but only when run as standalone. If started from Visual Studio it works correct in release. // other work around is to move float h1 and h2 out of the method double h1 = c1.GetBrightness(); double h2 = c2.GetBrightness(); if (h1 < h2) return -1; if (h1 > h2) return 1; return 0; } public void SortColorByValue() { m_colors.Sort(CompareColorByValue); Invalidate(); } public void SortColorByHue() { m_colors.Sort(CompareColorByHue); Invalidate(); } public void SortColorByBrightness() { m_colors.Sort(CompareColorByBrightness); Invalidate(); } List<Color> m_colors = new List<Color>(); public ColorTable(Color[] colors) { this.DoubleBuffered = true; if (colors != null) m_colors = new List<Color>(colors); Cols = 16; m_initialColorCount = m_colors.Count; Padding = new Padding(8,8,0,0); } public ColorTable() { this.DoubleBuffered = true; PropertyInfo[] propinfos = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static); foreach (PropertyInfo info in propinfos) { if (info.PropertyType == typeof(Color)) { Color c = (Color)info.GetValue(typeof(Color), null); if (c.A == 0) // transparent continue; m_colors.Add(c); } } m_colors.Sort(CompareColorByBrightness); m_initialColorCount = m_colors.Count; Cols = 16; } public void RemoveCustomColor() { if (m_colors.Count > m_initialColorCount) m_colors.RemoveAt(m_colors.Count-1); } public void SetCustomColor(Color col) { RemoveCustomColor(); if (m_colors.Contains(col) == false) { int rows = m_rows; m_colors.Add(col); Cols = Cols; if (m_rows != rows) Invalidate(); else Invalidate(GetRectangle(m_colors.Count-1)); } } public Color[] Colors { get { return m_colors.ToArray(); } set { m_colors = new List<Color>(value); Cols = 16; m_initialColorCount = m_colors.Count; } } int m_spacing = 3; int m_selindex = 0; int m_initialColorCount = 0; Rectangle GetSelectedItemRect() { Rectangle rect = GetRectangle(m_selindex); rect.Inflate(m_fieldSize.Width / 2, m_fieldSize.Height / 2); return rect; } Rectangle GetRectangle(int index) { int row = 0; int col = 0; GetRowCol(index, ref row, ref col); return GetRectangle(row, col); } void GetRowCol(int index, ref int row, ref int col) { row = index / m_cols; col = index - (row * m_cols); } Rectangle GetRectangle(int row, int col) { int x = Padding.Left + (col * (m_fieldSize.Width + m_spacing)); int y = Padding.Top + (row * (m_fieldSize.Height + m_spacing)); return new Rectangle(x,y,m_fieldSize.Width, m_fieldSize.Height); } int GetIndexFromMousePos(int x, int y) { int col = (x-Padding.Left) / (m_fieldSize.Width + m_spacing); int row = (y-Padding.Top) / (m_fieldSize.Height + m_spacing); return GetIndex(row, col); } int GetIndex(int row, int col) { if (col < 0 || col >= m_cols) return -1; if (row < 0 || row >= m_rows) return -1; return row * m_cols + col; } void SetIndex(int index) { if (index == m_selindex) return; Invalidate(GetSelectedItemRect()); m_selindex = index; if (SelectedIndexChanged != null) SelectedIndexChanged(this, null); Invalidate(GetSelectedItemRect()); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); Focus(); if (GetSelectedItemRect().Contains(new Point(e.X, e.Y))) return; int index = GetIndexFromMousePos(e.X, e.Y); if (index != -1) SetIndex(index); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); int index = 0; int totalwidth = m_cols * (m_fieldSize.Width + m_spacing); int totalheight = m_rows * (m_fieldSize.Height + m_spacing); int offset = (m_spacing / 2 + 1); Rectangle r = new Rectangle(0, 0, totalwidth, totalheight); r.X += Padding.Left - offset; r.Y += Padding.Top - offset; e.Graphics.DrawRectangle(Pens.CadetBlue, r); r.X++; r.Y++; r.Width--; r.Height--; e.Graphics.FillRectangle(Brushes.White, r); for (int col = 1; col < m_cols; col++) { int x = Padding.Left - offset + (col * (m_fieldSize.Width + m_spacing)); e.Graphics.DrawLine(Pens.CadetBlue, x, r.Y, x, r.Bottom - 1); } for (int row = 1; row < m_rows; row++) { int y = Padding.Top - offset + (row * (m_fieldSize.Height + m_spacing)); e.Graphics.DrawLine(Pens.CadetBlue, r.X, y, r.Right - 1, y); } for (int row = 0; row < m_rows; row++) { for (int col = 0; col < m_cols; col++) { if (index >= m_colors.Count) break; Rectangle rect = GetRectangle(row, col); using (SolidBrush brush = new SolidBrush(m_colors[index++])) { e.Graphics.FillRectangle(brush, rect); } } } if (m_selindex >= 0) { Rectangle rect = GetSelectedItemRect(); e.Graphics.FillRectangle(Brushes.White, rect); rect.Inflate(-3, -3); using (SolidBrush brush = new SolidBrush(SelectedItem)) { e.Graphics.FillRectangle(brush, rect); } if (Focused) { rect.Inflate(2, 2); ControlPaint.DrawFocusRectangle(e.Graphics, rect); } else { rect.X -= 2; rect.Y -= 2; rect.Width += 3; rect.Height += 3; e.Graphics.DrawRectangle(Pens.CadetBlue, rect); } } } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); Invalidate(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); Invalidate(); } protected override bool ProcessDialogKey(Keys keyData) { bool processed = false; int row = 0; int col = 0; GetRowCol(m_selindex, ref row, ref col); switch (keyData) { case Keys.Down: row++; processed = true; break; case Keys.Up: row--; processed = true; break; case Keys.Left: col--; if (col < 0) { col = m_cols-1; row--; } processed = true; break; case Keys.Right: col++; if (col >= m_cols) { col = 0; row++; } processed = true; break; } if (processed) { int index = GetIndex(row, col); if (index != -1) SetIndex(index); return false; } return base.ProcessDialogKey(keyData); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace Microsoft.PackageManagement.SwidTag { using System; using System.Linq; using System.Xml.Linq; using Utility; public static class Iso19770_2 { private static int _counter = 0; public static XAttribute SwidtagNamespace { get { return new XAttribute(XNamespace.Xmlns + "swid", Namespace.Iso19770_2); } } /// <summary> /// Gets the attribute value for a given element. /// </summary> /// <param name="element">the element that possesses the attribute</param> /// <param name="attribute">the attribute to find</param> /// <returns>the string value of the element. Returns null if the element or attribute does not exist.</returns> public static string GetAttribute(this XElement element, XName attribute) { if (element == null || attribute == null || string.IsNullOrWhiteSpace(attribute.ToString())) { return null; } var a = element.Attribute(attribute); return a == null ? null : a.Value; } /// <summary> /// Adds a new attribute to the element /// Does not permit modification of an existing attribute. /// Does not add empty or null attributes or values. /// </summary> /// <param name="element">The element to add the attribute to</param> /// <param name="attribute">The attribute to add</param> /// <param name="value">the value of the attribute to add</param> /// <returns>The element passed in. (Permits fluent usage)</returns> public static XElement AddAttribute(this XElement element, XName attribute, string value) { if (element == null) { return null; } // we quietly ignore attempts to add empty data or attributes. if (string.IsNullOrWhiteSpace(value) || attribute == null || string.IsNullOrWhiteSpace(attribute.ToString())) { return element; } // Swidtag attributes can be added but not changed -- if it already exists, that's not permitted. var current = element.GetAttribute(attribute); if (!string.IsNullOrWhiteSpace(current)) { if (value != current) { throw new Exception("Attempt to change Attribute '{0}' present in element '{1}'".format(attribute.LocalName, element.Name.LocalName)); } // if the value was set to that already, don't worry about it. return element; } if (element.Name.Namespace == attribute.Namespace || string.IsNullOrWhiteSpace(attribute.NamespaceName) || attribute.Namespace == Namespace.XmNs || attribute.Namespace == Namespace.Xml) { element.SetAttributeValue(attribute.LocalName, value); } else { element.EnsureNamespaceAtTop(attribute.Namespace); element.SetAttributeValue(attribute, value); } return element; } public static void EnsureNamespaceAtTop(this XElement element, XNamespace ns) { if (string.IsNullOrEmpty(ns.NamespaceName)) { return; } while (true) { if (element.Parent != null) { element = element.Parent; continue; } if (element.Attributes().Any(each => each.Value == ns.NamespaceName)) { return; } element.SetAttributeValue(Namespace.XmNs + ("pp" + (++_counter)), ns.NamespaceName); break; } } public static class Attributes { public static readonly XName Name = "name"; public static readonly XName Patch = "patch"; public static readonly XName Media = "media"; public static readonly XName Supplemental = "supplemental"; public static readonly XName TagVersion = "tagVersion"; public static readonly XName TagId = "tagId"; public static readonly XName Version = "version"; public static readonly XName VersionScheme = "versionScheme"; public static readonly XName Corpus = "corpus"; public static readonly XName Summary = "summary"; public static readonly XName Description = "description"; public static readonly XName ActivationStatus = "activationStatus"; public static readonly XName ChannelType = "channelType"; public static readonly XName ColloquialVersion = "colloquialVersion"; public static readonly XName Edition = "edition"; public static readonly XName EntitlementDataRequired = "entitlementDataRequired"; public static readonly XName EntitlementKey = "entitlementKey"; public static readonly XName Generator = "generator"; public static readonly XName PersistentId = "persistentId"; public static readonly XName Product = "product"; public static readonly XName ProductFamily = "productFamily"; public static readonly XName Revision = "revision"; public static readonly XName UnspscCode = "unspscCode"; public static readonly XName UnspscVersion = "unspscVersion"; public static readonly XName RegId = "regId"; public static readonly XName Role = "role"; public static readonly XName Thumbprint = "thumbprint"; public static readonly XName HRef = "href"; public static readonly XName Relationship = "rel"; public static readonly XName MediaType = "type"; public static readonly XName Ownership = "ownership"; public static readonly XName Use = "use"; public static readonly XName Artifact = "artifact"; public static readonly XName Type = "type"; public static readonly XName Key = "key"; public static readonly XName Root = "root"; public static readonly XName Location = "location"; public static readonly XName Size = "size"; public static readonly XName Pid = "pid"; public static readonly XName Date = "date"; public static readonly XName DeviceId = "deviceId"; public static readonly XName XmlLang = Namespace.Xml + "lang"; } public static class Discovery { public static readonly XName NamespaceDeclaration = Namespace.XmNs + "discovery"; public static readonly XName Name = Namespace.Discovery + "name"; // Feed Link Extended attributes: public static readonly XName MinimumName = Namespace.Discovery + "min-name"; public static readonly XName MaximumName = Namespace.Discovery + "max-name"; public static readonly XName MinimumVersion = Namespace.Discovery + "min-version"; public static readonly XName MaximumVersion = Namespace.Discovery + "max-version"; public static readonly XName Keyword = Namespace.Discovery + "keyword"; // Package Link Extended Attributes public static readonly XName Version = Namespace.Discovery + "version"; public static readonly XName Latest = Namespace.Discovery + "latest"; public static readonly XName TargetFilename = Namespace.Discovery + "targetFilename"; public static readonly XName Type = Namespace.Discovery + "type"; } public static class Installation { // Package Link Installer Attributes public static readonly XName InstallParameters = Namespace.Installation + "install-parameters"; public static readonly XName InstallScript = Namespace.Installation + "install-script"; } public static class MediaType { public const string PackageReference = "application/vnd.packagemanagement-canonicalid"; public const string SwidTagXml = "application/swid-tag+xml"; public const string SwidTagJsonLd = "application/swid-tag+json"; public const string MsiPackage = "application/vnd.ms.msi-package"; public const string MsuPackage = "application/vnd.ms.msu-package"; public const string ExePackage = "application/vnd.packagemanagement.exe-package"; public const string NuGetPackage = "application/vnd.packagemanagement.nuget-package"; public const string ChocolateyPackage = "application/vnd.packagemanagement.chocolatey-package"; } public static class Relationship { public const string Requires = "requires"; public const string InstallationMedia = "installationmedia"; public const string Component = "component"; public const string Supplemental = "supplemental"; public const string Parent = "parent"; public const string Ancestor = "ancestor"; // Package Discovery Relationships: public const string Feed = "feed"; // should point to a swidtag the represents a feed of packages public const string Package = "package"; // should point ot a swidtag that represents an installation package } public static class Role { public const string Aggregator = "aggregator"; public const string Distributor = "distributor"; public const string Licensor = "licensor"; public const string SoftwareCreator = "softwareCreator"; public const string Author = "author"; public const string Contributor = "contributor"; public const string Publisher = "publisher"; public const string TagCreator = "tagCreator"; } public static class Use { public const string Required = "required"; public const string Recommended = "recommended"; public const string Optional = "optional"; } public static class VersionScheme { public const string Alphanumeric = "alphanumeric"; public const string Decimal = "decimal"; public const string MultipartNumeric = "multipartnumeric"; public const string MultipartNumericPlusSuffix = "multipartnumeric+suffix"; public const string SemVer = "semver"; public const string Unknown = "unknown"; } public static class Ownership { public const string Abandon = "abandon"; public const string Private = "private"; public const string Shared = "shared"; } public static class Namespace { public static readonly XNamespace Iso19770_2 = XNamespace.Get("http://standards.iso.org/iso/19770/-2/2015/schema.xsd"); public static readonly XNamespace Discovery = XNamespace.Get("http://packagemanagement.org/discovery"); public static readonly XNamespace Installation = XNamespace.Get("http://packagemanagement.org/installation"); public static readonly XNamespace OneGet = XNamespace.Get("http://oneget.org/packagemanagement"); public static readonly XNamespace Xml = XNamespace.Get("http://www.w3.org/XML/1998/namespace"); public static XNamespace XmlDsig = XNamespace.Get("http://www.w3.org/2000/09/xmldsig#"); public static XNamespace XmNs = XNamespace.Get("http://www.w3.org/2000/xmlns/"); } public static class Elements { public static readonly XName SoftwareIdentity = Namespace.Iso19770_2 + "SoftwareIdentity"; public static readonly XName Entity = Namespace.Iso19770_2 + "Entity"; public static readonly XName Link = Namespace.Iso19770_2 + "Link"; public static readonly XName Evidence = Namespace.Iso19770_2 + "Evidence"; public static readonly XName Payload = Namespace.Iso19770_2 + "Payload"; public static readonly XName Meta = Namespace.Iso19770_2 + "Meta"; public static readonly XName Directory = Namespace.Iso19770_2 + "Directory"; public static readonly XName File = Namespace.Iso19770_2 + "File"; public static readonly XName Process = Namespace.Iso19770_2 + "Process"; public static readonly XName Resource = Namespace.Iso19770_2 + "Resource"; public static readonly XName[] MetaElements = { Meta, Directory, File, Process, Resource }; } public static class JSonMembers { public static readonly string SoftwareIdentity = Elements.SoftwareIdentity.ToJsonId(); public static readonly string Entity = Elements.Entity.ToJsonId(); public static readonly string Link = Elements.Link.ToJsonId(); public static readonly string Evidence = Elements.Evidence.ToJsonId(); public static readonly string Payload = Elements.Payload.ToJsonId(); public static readonly string Meta = Elements.Meta.ToJsonId(); public static readonly string Directory = Elements.Directory.ToJsonId(); public static readonly string File = Elements.File.ToJsonId(); public static readonly string Process = Elements.Process.ToJsonId(); public static readonly string Resource = Elements.Resource.ToJsonId(); public static readonly string Name = Namespace.Iso19770_2.ToString() + "#" + "name"; public static readonly string Patch = Namespace.Iso19770_2.ToString() + "#" + "patch"; public static readonly string Media = Namespace.Iso19770_2.ToString() + "#" + "media"; public static readonly string Supplemental = Namespace.Iso19770_2.ToString() + "#" + "supplemental"; public static readonly string TagVersion = Namespace.Iso19770_2.ToString() + "#" + "tagVersion"; public static readonly string TagId = Namespace.Iso19770_2.ToString() + "#" + "tagId"; public static readonly string Version = Namespace.Iso19770_2.ToString() + "#" + "version"; public static readonly string VersionScheme = Namespace.Iso19770_2.ToString() + "#" + "versionScheme"; public static readonly string Corpus = Namespace.Iso19770_2.ToString() + "#" + "corpus"; public static readonly string Summary = Namespace.Iso19770_2.ToString() + "#" + "summary"; public static readonly string Description = Namespace.Iso19770_2.ToString() + "#" + "description"; public static readonly string ActivationStatus = Namespace.Iso19770_2.ToString() + "#" + "activationStatus"; public static readonly string ChannelType = Namespace.Iso19770_2.ToString() + "#" + "channelType"; public static readonly string ColloquialVersion = Namespace.Iso19770_2.ToString() + "#" + "colloquialVersion"; public static readonly string Edition = Namespace.Iso19770_2.ToString() + "#" + "edition"; public static readonly string EntitlementDataRequired = Namespace.Iso19770_2.ToString() + "#" + "entitlementDataRequired"; public static readonly string EntitlementKey = Namespace.Iso19770_2.ToString() + "#" + "entitlementKey"; public static readonly string Generator = Namespace.Iso19770_2.ToString() + "#" + "generator"; public static readonly string PersistentId = Namespace.Iso19770_2.ToString() + "#" + "persistentId"; public static readonly string Product = Namespace.Iso19770_2.ToString() + "#" + "product"; public static readonly string ProductFamily = Namespace.Iso19770_2.ToString() + "#" + "productFamily"; public static readonly string Revision = Namespace.Iso19770_2.ToString() + "#" + "revision"; public static readonly string UnspscCode = Namespace.Iso19770_2.ToString() + "#" + "unspscCode"; public static readonly string UnspscVersion = Namespace.Iso19770_2.ToString() + "#" + "unspscVersion"; public static readonly string RegId = Namespace.Iso19770_2.ToString() + "#" + "regId"; public static readonly string Role = Namespace.Iso19770_2.ToString() + "#" + "role"; public static readonly string Thumbprint = Namespace.Iso19770_2.ToString() + "#" + "thumbprint"; public static readonly string HRef = Namespace.Iso19770_2.ToString() + "#" + "href"; public static readonly string Relationship = Namespace.Iso19770_2.ToString() + "#" + "rel"; public static readonly string MediaType = Namespace.Iso19770_2.ToString() + "#" + "type"; public static readonly string Ownership = Namespace.Iso19770_2.ToString() + "#" + "ownership"; public static readonly string Use = Namespace.Iso19770_2.ToString() + "#" + "use"; public static readonly string Artifact = Namespace.Iso19770_2.ToString() + "#" + "artifact"; public static readonly string Type = Namespace.Iso19770_2.ToString() + "#" + "type"; public static readonly string Key = Namespace.Iso19770_2.ToString() + "#" + "key"; public static readonly string Root = Namespace.Iso19770_2.ToString() + "#" + "root"; public static readonly string Location = Namespace.Iso19770_2.ToString() + "#" + "location"; public static readonly string Size = Namespace.Iso19770_2.ToString() + "#" + "size"; public static readonly string Pid = Namespace.Iso19770_2.ToString() + "#" + "pid"; public static readonly string Date = Namespace.Iso19770_2.ToString() + "#" + "date"; public static readonly string DeviceId = Namespace.Iso19770_2.ToString() + "#" + "deviceId"; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using OmniXaml; using Avalonia.Platform; namespace Avalonia.Markup.Xaml { using Context; using Controls; using Data; using OmniXaml.ObjectAssembler; using System.Linq; /// <summary> /// Loads XAML for a avalonia application. /// </summary> public class AvaloniaXamlLoader : XmlLoader { private static AvaloniaParserFactory s_parserFactory; private static IInstanceLifeCycleListener s_lifeCycleListener = new AvaloniaLifeCycleListener(); private static Stack<Uri> s_uriStack = new Stack<Uri>(); /// <summary> /// Initializes a new instance of the <see cref="AvaloniaXamlLoader"/> class. /// </summary> public AvaloniaXamlLoader() : this(GetParserFactory()) { } /// <summary> /// Initializes a new instance of the <see cref="AvaloniaXamlLoader"/> class. /// </summary> /// <param name="xamlParserFactory">The parser factory to use.</param> public AvaloniaXamlLoader(IParserFactory xamlParserFactory) : base(xamlParserFactory) { } /// <summary> /// Gets the URI of the XAML file currently being loaded. /// </summary> /// <remarks> /// TODO: Making this internal for now as I'm not sure that this is the correct /// thing to do, but its needd by <see cref="StyleInclude"/> to get the URL of /// the currently loading XAML file, as we can't use the OmniXAML parsing context /// there. Maybe we need a way to inject OmniXAML context into the objects its /// constructing? /// </remarks> internal static Uri UriContext => s_uriStack.Count > 0 ? s_uriStack.Peek() : null; /// <summary> /// Loads the XAML into a Avalonia component. /// </summary> /// <param name="obj">The object to load the XAML into.</param> public static void Load(object obj) { Contract.Requires<ArgumentNullException>(obj != null); var loader = new AvaloniaXamlLoader(); loader.Load(obj.GetType(), obj); } /// <summary> /// Loads the XAML for a type. /// </summary> /// <param name="type">The type.</param> /// <param name="rootInstance"> /// The optional instance into which the XAML should be loaded. /// </param> /// <returns>The loaded object.</returns> public object Load(Type type, object rootInstance = null) { Contract.Requires<ArgumentNullException>(type != null); // HACK: Currently Visual Studio is forcing us to change the extension of xaml files // in certain situations, so we try to load .xaml and if that's not found we try .xaml. // Ideally we'd be able to use .xaml everywhere var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>(); if (assetLocator == null) { throw new InvalidOperationException( "Could not create IAssetLoader : maybe Application.RegisterServices() wasn't called?"); } foreach (var uri in GetUrisFor(type)) { if (assetLocator.Exists(uri)) { using (var stream = assetLocator.Open(uri)) { var initialize = rootInstance as ISupportInitialize; initialize?.BeginInit(); return Load(stream, rootInstance, uri); } } } throw new FileNotFoundException("Unable to find view for " + type.FullName); } /// <summary> /// Loads XAML from a URI. /// </summary> /// <param name="uri">The URI of the XAML file.</param> /// <param name="baseUri"> /// A base URI to use if <paramref name="uri"/> is relative. /// </param> /// <param name="rootInstance"> /// The optional instance into which the XAML should be loaded. /// </param> /// <returns>The loaded object.</returns> public object Load(Uri uri, Uri baseUri = null, object rootInstance = null) { Contract.Requires<ArgumentNullException>(uri != null); var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>(); if (assetLocator == null) { throw new InvalidOperationException( "Could not create IAssetLoader : maybe Application.RegisterServices() wasn't called?"); } using (var stream = assetLocator.Open(uri, baseUri)) { return Load(stream, rootInstance, uri); } } /// <summary> /// Loads XAML from a string. /// </summary> /// <param name="xaml">The string containing the XAML.</param> /// <param name="rootInstance"> /// The optional instance into which the XAML should be loaded. /// </param> /// <returns>The loaded object.</returns> public object Load(string xaml, object rootInstance = null) { Contract.Requires<ArgumentNullException>(xaml != null); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xaml))) { return Load(stream, rootInstance); } } /// <summary> /// Loads XAML from a stream. /// </summary> /// <param name="stream">The stream containing the XAML.</param> /// <param name="rootInstance"> /// The optional instance into which the XAML should be loaded. /// </param> /// <param name="uri">The URI of the XAML</param> /// <returns>The loaded object.</returns> public object Load(Stream stream, object rootInstance = null, Uri uri = null) { try { if (uri != null) { s_uriStack.Push(uri); } var result = base.Load(stream, new Settings { RootInstance = rootInstance, InstanceLifeCycleListener = s_lifeCycleListener, ParsingContext = new Dictionary<string, object> { { "Uri", uri } } }); var topLevel = result as TopLevel; if (topLevel != null) { DelayedBinding.ApplyBindings(topLevel); } return result; } finally { if (uri != null) { s_uriStack.Pop(); } } } private static AvaloniaParserFactory GetParserFactory() { if (s_parserFactory == null) { s_parserFactory = new AvaloniaParserFactory(); } return s_parserFactory; } /// <summary> /// Gets the URI for a type. /// </summary> /// <param name="type">The type.</param> /// <returns>The URI.</returns> private static IEnumerable<Uri> GetUrisFor(Type type) { var asm = type.GetTypeInfo().Assembly.GetName().Name; var typeName = type.FullName; yield return new Uri("resm:" + typeName + ".xaml?assembly=" + asm); yield return new Uri("resm:" + typeName + ".paml?assembly=" + asm); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; namespace Apache.Geode.Client.FwkLib { using Apache.Geode.DUnitFramework; using Apache.Geode.Client; //using Region = Apache.Geode.Client.IRegion<Object, Object>; //using IntRegion = Apache.Geode.Client.IRegion<int, byte[]>; //using StringRegion = Apache.Geode.Client.IRegion<string, byte[]>; public class PerfTests<TKey, TVal> : FwkTest<TKey, TVal> { #region Protected members protected TKey[] m_keysA; protected int m_maxKeys; protected int m_keyIndexBegin; protected TVal[] m_cValues; protected int m_maxValues; public char m_keyType = 'i'; #endregion #region Protected constants protected const string ClientCount = "clientCount"; protected const string TimedInterval = "timedInterval"; protected const string DistinctKeys = "distinctKeys"; protected const string NumThreads = "numThreads"; protected const string ValueSizes = "valueSizes"; protected const string OpsSecond = "opsSecond"; protected const string KeyType = "keyType"; protected const string KeySize = "keySize"; protected const string KeyIndexBegin = "keyIndexBegin"; protected const string RegisterKeys = "registerKeys"; protected const string RegisterRegex = "registerRegex"; protected const string UnregisterRegex = "unregisterRegex"; protected const string ExpectedCount = "expectedCount"; protected const string InterestPercent = "interestPercent"; protected const string KeyStart = "keyStart"; protected const string KeyEnd = "keyEnd"; #endregion #region Protected utility methods protected void ClearKeys() { if (m_keysA != null) { for (int i = 0; i < m_keysA.Length; i++) { if (m_keysA[i] != null) { //m_keysA[i]; m_keysA[i] = default(TKey); } } m_keysA = null; m_maxKeys = 0; } } protected int InitKeys(bool useDefault) { string typ = GetStringValue(KeyType); // int is only value to use char newType = (typ == null || typ.Length == 0) ? 's' : typ[0]; int low = GetUIntValue(KeyIndexBegin); low = (low > 0) ? low : 0; //ResetKey(DistinctKeys); int numKeys = GetUIntValue(DistinctKeys); // check distinct keys first if (numKeys <= 0) { if (useDefault) { numKeys = 5000; } else { //FwkSevere("Failed to initialize keys with numKeys: {0}", numKeys); return numKeys; } } int high = numKeys + low; FwkInfo("InitKeys:: numKeys: {0}; low: {1}", numKeys, low); if ((newType == m_keyType) && (numKeys == m_maxKeys) && (m_keyIndexBegin == low)) { return numKeys; } ClearKeys(); m_maxKeys = numKeys; m_keyIndexBegin = low; m_keyType = newType; if (m_keyType == 'i') { InitIntKeys(low, high); } else { int keySize = GetUIntValue(KeySize); keySize = (keySize > 0) ? keySize : 10; string keyBase = new string('A', keySize); InitStrKeys(low, high, keyBase); } for (int j = 0; j < numKeys; j++) { int randIndx = Util.Rand(numKeys); if (randIndx != j) { TKey tmp = m_keysA[j]; m_keysA[j] = m_keysA[randIndx]; m_keysA[randIndx] = tmp; } } return m_maxKeys; } protected int InitKeys() { return InitKeys(true); } protected void InitStrKeys(int low, int high, string keyBase) { m_keysA = (TKey[])(object) new String[m_maxKeys]; FwkInfo("m_maxKeys: {0}; low: {1}; high: {2}", m_maxKeys, low, high); for (int i = low; i < high; i++) { m_keysA[i - low] = (TKey)(object)(keyBase.ToString() + i.ToString("D10")); } } protected void InitIntKeys(int low, int high) { m_keysA = (TKey[])(object) new Int32[m_maxKeys]; FwkInfo("m_maxKeys: {0}; low: {1}; high: {2}", m_maxKeys, low, high); for (int i = low; i < high; i++) { m_keysA[i - low] = (TKey)(object)i; } } protected int InitValues(int numKeys) { return InitValues(numKeys, 0); } protected int InitValues(int numKeys, int size) { if (size <= 0) { size = GetUIntValue(ValueSizes); } if (size <= 0) { //FwkSevere("Failed to initialize values with valueSize: {0}", size); return size; } if (numKeys <= 0) { numKeys = 500; } m_maxValues = numKeys; if (m_cValues != null) { for (int i = 0; i < m_cValues.Length; i++) { if (m_cValues[i] != null) { //m_cValues[i].Dispose(); m_cValues[i] = default(TVal); } } m_cValues = null; } m_cValues = new TVal[m_maxValues]; FwkInfo("InitValues() payload size: {0}", size); //byte[] createPrefix = Encoding.ASCII.GetBytes("Create "); //byte[] buffer = new byte[size]; for (int i = 0; i < m_maxValues; i++) { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int j = 0; j < size; j++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } //FwkInfo("rjk: InitValues() value {0}", builder.ToString()); //Util.RandBytes(buffer); //createPrefix.CopyTo(buffer, 0); //string tmp = buffer; if (typeof(TVal) == typeof(string)) { m_cValues[i] = (TVal)(object)builder.ToString(); //FwkInfo("rjk: InitValues() value {0} size is {1}", m_cValues[i].ToString(), m_cValues[i].ToString().Length); } else if (typeof(TVal) == typeof(byte[])) { //Encoding.ASCII.GetBytes(buffer); //Util.RandBytes(buffer); //createPrefix.CopyTo(buffer, 0); m_cValues[i] = (TVal)(object)(Encoding.ASCII.GetBytes(builder.ToString())); //FwkInfo("rjk: InitValues() type is byte[] value {0} size is {1}", m_cValues[i].ToString(), ((byte[])(object)m_cValues[i]).Length); } /* Util.RandBytes(buffer); createPrefix.CopyTo(buffer, 0); if (typeof(TVal) == typeof(string)) { String MyString; //Encoding ASCIIEncod = new Encoding(); MyString = Encoding.ASCII.GetString(buffer); m_cValues[i] = (TVal)(MyString as object); FwkInfo("rjk: InitValues() value {0} size is {1}", MyString.ToString(), m_cValues[i].ToString().Length); } else if (typeof(TVal) == typeof(byte[])) { Util.RandBytes(buffer); createPrefix.CopyTo(buffer, 0); m_cValues[i] = (TVal)(buffer as object); } * */ //for (int ii = 0; ii < buffer.Length; ++ii) //{ // FwkInfo("rjk: InitValues() index is {0} value is {1} buffer = {2}", i, m_cValues[ii], buffer[ii]); //} } return size; } protected IRegion<TKey, TVal> GetRegion() { return GetRegion(null); } protected IRegion<TKey, TVal> GetRegion(string regionName) { IRegion<TKey, TVal> region; if (regionName == null) { regionName = GetStringValue("regionName"); } if (regionName == null) { region = GetRootRegion(); if (region == null) { IRegion<TKey, TVal>[] rootRegions = CacheHelper<TKey, TVal>.DCache.RootRegions<TKey, TVal>(); if (rootRegions != null && rootRegions.Length > 0) { region = rootRegions[Util.Rand(rootRegions.Length)]; } } } else { region = CacheHelper<TKey, TVal>.GetRegion(regionName); } return region; } #endregion #region Public methods public static ICacheListener<TKey, TVal> CreatePerfTestCacheListener() { return new PerfTestCacheListener<TKey, TVal>(); } public static ICacheListener<TKey, TVal> CreateConflationTestCacheListener() { return new ConflationTestCacheListener<TKey, TVal>(); } public static ICacheListener<TKey, TVal> CreateLatencyListenerP() { return new LatencyListener<TKey, TVal>(); } public static ICacheListener<TKey, TVal> CreateDupChecker() { return new DupChecker<TKey, TVal>(); } public virtual void DoCreateRegion() { FwkInfo("In DoCreateRegion()"); try { IRegion<TKey,TVal> region = null; FwkInfo("Tkey = {0} , Val = {1}", typeof(TKey).Name, typeof(TVal)); region = CreateRootRegion(); if (region == null) { FwkException("DoCreateRegion() could not create region."); } FwkInfo("DoCreateRegion() Created region '{0}'", region.Name); } catch (Exception ex) { FwkException("DoCreateRegion() Caught Exception: {0}", ex); } FwkInfo("DoCreateRegion() complete."); } public void DoCloseCache() { FwkInfo("DoCloseCache() Closing cache and disconnecting from" + " distributed system."); CacheHelper<TKey,TVal>.Close(); } public void DoPuts() { FwkInfo("In DoPuts()"); try { IRegion<TKey, TVal> region = GetRegion(); int numClients = GetUIntValue(ClientCount); string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes); int timedInterval = GetTimeValue(TimedInterval) * 1000; if (timedInterval <= 0) { timedInterval = 5000; } int maxTime = 10 * timedInterval; // Loop over key set sizes ResetKey(DistinctKeys); int numKeys; while ((numKeys = InitKeys(false)) > 0) { // keys loop // Loop over value sizes ResetKey(ValueSizes); int valSize; while ((valSize = InitValues(numKeys)) > 0) { // value loop // Loop over threads ResetKey(NumThreads); int numThreads; while ((numThreads = GetUIntValue(NumThreads)) > 0) { try { //if (m_keyType == 's') //{ //StringRegion sregion = region as StringRegion; PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues); FwkInfo("Running warmup task for {0} iterations.", numKeys); RunTask(puts, 1, numKeys, -1, -1, null); // Running the warmup task Thread.Sleep(3000); // And we do the real work now FwkInfo("Running timed task for {0} secs and {1} threads; numKeys[{2}]", timedInterval / 1000, numThreads, numKeys); SetTaskRunInfo(label, "Puts", m_maxKeys, numClients, valSize, numThreads); RunTask(puts, numThreads, -1, timedInterval, maxTime, null); AddTaskRunRecord(puts.Iterations, puts.ElapsedTime); } catch (ClientTimeoutException) { FwkException("In DoPuts() Timed run timed out."); } Thread.Sleep(3000); // Put a marker of inactivity in the stats } Thread.Sleep(3000); // Put a marker of inactivity in the stats } // value loop Thread.Sleep(3000); // Put a marker of inactivity in the stats } // keys loop } catch (Exception ex) { FwkException("DoPuts() Caught Exception: {0}", ex); } Thread.Sleep(3000); // Put a marker of inactivity in the stats FwkInfo("DoPuts() complete."); } public void DoPopulateRegion() { FwkInfo("In DoPopulateRegion()"); try { IRegion<TKey,TVal> region = GetRegion(); ResetKey(DistinctKeys); int numKeys = InitKeys(); InitValues(numKeys); PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues); FwkInfo("Populating region."); RunTask(puts, 1, m_maxKeys, -1, -1, null); } catch (Exception ex) { FwkException("DoPopulateRegion() Caught Exception: {0}", ex); } FwkInfo("DoPopulateRegion() complete."); } public void DoSerialPuts() { FwkInfo("In DoSerialPuts()"); try { IRegion<int, int> region = (IRegion<int, int>)GetRegion(); int keyStart = GetUIntValue(KeyStart); int keyEnd = GetUIntValue(KeyEnd); for (Int32 keys = keyStart; keys <= keyEnd; keys++) { if (keys % 50 == 1) { FwkInfo("DoSerialPuts() putting 1000 values for key " + keys); } Int32 key = keys; for (Int32 values = 1; values <= 1000; values++) { Int32 value = values; region[key] = value; } } } catch (Exception ex) { FwkException("DoSerialPuts() Caught Exception: {0}", ex); } Thread.Sleep(3000); // Put a marker of inactivity in the stats FwkInfo("DoSerialPuts() complete."); } public void DoPutBursts() { FwkInfo("In DoPutBursts()"); try { IRegion<TKey,TVal> region = GetRegion(); int numClients = GetUIntValue(ClientCount); string label = CacheHelper<TKey,TVal>.RegionTag(region.Attributes); int timedInterval = GetTimeValue(TimedInterval) * 1000; if (timedInterval <= 0) { timedInterval = 5000; } int burstMillis = GetUIntValue("burstMillis"); if (burstMillis <= 0) { burstMillis = 500; } int burstPause = GetTimeValue("burstPause") * 1000; if (burstPause <= 0) { burstPause = 1000; } int opsSec = GetUIntValue(OpsSecond); if (opsSec <= 0) { opsSec = 100; } // Loop over key set sizes ResetKey(DistinctKeys); int numKeys; while ((numKeys = InitKeys(false)) > 0) { // keys loop // Loop over value sizes ResetKey(ValueSizes); int valSize; while ((valSize = InitValues(numKeys)) > 0) { // value loop // Loop over threads ResetKey(NumThreads); int numThreads; while ((numThreads = GetUIntValue(NumThreads)) > 0) { // thread loop // And we do the real work now MeteredPutsTask<TKey, TVal> mputs = new MeteredPutsTask<TKey, TVal>(region, m_keysA, m_cValues, opsSec); FwkInfo("Running warmup metered task for {0} iterations.", m_maxKeys); RunTask(mputs, 1, m_maxKeys, -1, -1, null); Thread.Sleep(10000); PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues); int loopIters = (timedInterval / burstMillis) + 1; FwkInfo("Running timed task for {0} secs and {1} threads.", timedInterval/1000, numThreads); SetTaskRunInfo(label, "PutBursts", numKeys, numClients, valSize, numThreads); int totIters = 0; TimeSpan totTime = TimeSpan.Zero; for (int i = loopIters; i > 0; i--) { try { RunTask(puts, numThreads, -1, burstMillis, 30000, null); } catch (ClientTimeoutException) { FwkException("In DoPutBursts() Timed run timed out."); } totIters += puts.Iterations; totTime += puts.ElapsedTime; double psec = (totIters * 1000.0) / totTime.TotalMilliseconds; FwkInfo("PerfSuite interim: {0} {1} {2}", psec, totIters, totTime); Thread.Sleep(burstPause); } AddTaskRunRecord(totIters, totTime); // real work complete for this pass thru the loop Thread.Sleep(3000); // Put a marker of inactivity in the stats } // thread loop Thread.Sleep(3000); // Put a marker of inactivity in the stats } // value loop Thread.Sleep(3000); // Put a marker of inactivity in the stats } // keys loop } catch (Exception ex) { FwkException("DoPutBursts() Caught Exception: {0}", ex); } Thread.Sleep(3000); // Put a marker of inactivity in the stats FwkInfo("DoPutBursts() complete."); } public void DoLatencyPuts() { FwkInfo("In DoLatencyPuts()"); try { IRegion<TKey,TVal> region = GetRegion(); int numClients = GetUIntValue(ClientCount); string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes); int timedInterval = GetTimeValue(TimedInterval) * 1000; if (timedInterval <= 0) { timedInterval = 5000; } int maxTime = 10 * timedInterval; int opsSec = GetUIntValue(OpsSecond); if (opsSec < 0) { opsSec = 100; } // Loop over key set sizes ResetKey(DistinctKeys); int numKeys; while ((numKeys = InitKeys(false)) > 0) { // keys loop // Loop over value sizes ResetKey(ValueSizes); int valSize; while ((valSize = InitValues(numKeys)) > 0) { // value loop // Loop over threads ResetKey(NumThreads); int numThreads; while ((numThreads = GetUIntValue(NumThreads)) > 0) { LatencyPutsTask<TKey, TVal> puts = new LatencyPutsTask<TKey, TVal>(region, m_keysA, m_cValues, opsSec); // Running the warmup task FwkInfo("Running warmup task for {0} iterations.", numKeys); RunTask(puts, 1, numKeys, -1, -1, null); Thread.Sleep(3000); // And we do the real work now FwkInfo("Running timed task for {0} secs and {1} threads.", timedInterval/1000, numThreads); SetTaskRunInfo(label, "LatencyPuts", numKeys, numClients, valSize, numThreads); Util.BBSet("LatencyBB", "LatencyTag", TaskData); try { RunTask(puts, numThreads, -1, timedInterval, maxTime, null); } catch (ClientTimeoutException) { FwkException("In DoLatencyPuts() Timed run timed out."); } AddTaskRunRecord(puts.Iterations, puts.ElapsedTime); // real work complete for this pass thru the loop Thread.Sleep(3000); // Put a marker of inactivity in the stats } // thread loop Thread.Sleep(3000); // Put a marker of inactivity in the stats } // value loop Thread.Sleep(3000); // Put a marker of inactivity in the stats } // keys loop } catch (Exception ex) { FwkException("DoLatencyPuts() Caught Exception: {0}", ex); } Thread.Sleep(3000); // Put a marker of inactivity in the stats FwkInfo("DoLatencyPuts() complete."); } public void DoGets() { FwkInfo("In DoGets()"); try { IRegion<TKey,TVal> region = GetRegion(); FwkInfo("rjk:DoGets region name is {0} ", region.Name); int numClients = GetUIntValue(ClientCount); string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes); int timedInterval = GetTimeValue(TimedInterval) * 1000; if (timedInterval <= 0) { timedInterval = 5000; } int maxTime = 10 * timedInterval; ResetKey(DistinctKeys); InitKeys(); int valSize = GetUIntValue(ValueSizes); FwkInfo("rjk:DoGets number of keys in region is {0} .", region.Keys.Count); // Loop over threads ResetKey(NumThreads); int numThreads; while ((numThreads = GetUIntValue(NumThreads)) > 0) { // thread loop // And we do the real work now GetsTask<TKey, TVal> gets = new GetsTask<TKey, TVal>(region, m_keysA); FwkInfo("Running warmup task for {0} iterations.", m_maxKeys); RunTask(gets, 1, m_maxKeys, -1, -1, null); region.GetLocalView().InvalidateRegion(); Thread.Sleep(3000); FwkInfo("Running timed task for {0} secs and {1} threads.", timedInterval/1000, numThreads); SetTaskRunInfo(label, "Gets", m_maxKeys, numClients, valSize, numThreads); try { RunTask(gets, numThreads, -1, timedInterval, maxTime, null); } catch (ClientTimeoutException) { FwkException("In DoGets() Timed run timed out."); } AddTaskRunRecord(gets.Iterations, gets.ElapsedTime); // real work complete for this pass thru the loop Thread.Sleep(3000); } // thread loop } catch (Exception ex) { FwkException("DoGets() Caught Exception: {0}", ex); } Thread.Sleep(3000); FwkInfo("DoGets() complete."); } public void DoPopServers() { FwkInfo("In DoPopServers()"); try { IRegion<TKey,TVal> region = GetRegion(); ResetKey(DistinctKeys); int numKeys = InitKeys(); ResetKey(ValueSizes); InitValues(numKeys); int opsSec = GetUIntValue(OpsSecond); MeteredPutsTask<TKey, TVal> mputs = new MeteredPutsTask<TKey, TVal>(region, m_keysA, m_cValues, opsSec); RunTask(mputs, 1, m_maxKeys, -1, -1, null); } catch (Exception ex) { FwkException("DoPopServers() Caught Exception: {0}", ex); } FwkInfo("DoPopServers() complete."); } public void DoPopClient() { FwkInfo("In DoPopClient()"); try { IRegion<TKey,TVal> region = GetRegion(); ResetKey(DistinctKeys); InitKeys(); GetsTask<TKey, TVal> gets = new GetsTask<TKey, TVal>(region, m_keysA); RunTask(gets, 1, m_maxKeys, -1, -1, null); } catch (Exception ex) { FwkException("DoPopClient() Caught Exception: {0}", ex); } FwkInfo("DopopClient() complete."); } public void DoPopClientMS() { FwkInfo("In DoPopClientMS()"); try { IRegion<TKey,TVal> region = GetRegion(); ResetKey(DistinctKeys); int numKeys = GetUIntValue(DistinctKeys); int clientCount = GetUIntValue(ClientCount); int interestPercent = GetUIntValue(InterestPercent); if (interestPercent <= 0) { if (clientCount <= 0) { interestPercent = 100; } else { interestPercent = (100 / clientCount); } } int myNumKeys = (numKeys * interestPercent) / 100; int myNum = Util.ClientNum; int myStart = myNum * myNumKeys; int myValSize = 10; m_maxKeys = numKeys; InitIntKeys(myStart, myStart + myNumKeys); InitValues(myNumKeys, myValSize); FwkInfo("DoPopClientMS() Client number: {0}, Client count: {1}, " + "MaxKeys: {2}", myNum, clientCount, m_maxKeys); PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues); RunTask(puts, 1, m_maxKeys, -1, -1, null); } catch (Exception ex) { FwkException("DoPopClientMS() Caught Exception: {0}", ex); } FwkInfo("DoPopClientMS() complete."); } public void DoDestroys() { FwkInfo("In DoDestroys()"); try { IRegion<TKey,TVal> region = GetRegion(); int numClients = GetUIntValue(ClientCount); FwkInfo("DoDestroys() numclients set to {0}", numClients); string label = CacheHelper<TKey, TVal>.RegionTag(region.Attributes); int timedInterval = GetTimeValue(TimedInterval) * 1000; if (timedInterval <= 0) { timedInterval = 5000; } int maxTime = 10 * timedInterval; // always use only one thread for destroys. int numKeys; // Loop over distinctKeys while ((numKeys = InitKeys(false)) > 0) { // thread loop int valSize = InitValues(numKeys); // And we do the real work now //populate the region PutsTask<TKey, TVal> puts = new PutsTask<TKey, TVal>(region, m_keysA, m_cValues); FwkInfo("DoDestroys() Populating region."); RunTask(puts, 1, m_maxKeys, -1, -1, null); DestroyTask<TKey, TVal> destroys = new DestroyTask<TKey, TVal>(region, m_keysA); FwkInfo("Running timed task for {0} iterations and {1} threads.", numKeys, 1); SetTaskRunInfo(label, "Destroys", numKeys, numClients, valSize, 1); try { RunTask(destroys, 1, numKeys, -1, maxTime, null); } catch (ClientTimeoutException) { FwkException("In DoDestroys() Timed run timed out."); } AddTaskRunRecord(destroys.Iterations, destroys.ElapsedTime); // real work complete for this pass thru the loop Thread.Sleep(3000); } // distinctKeys loop } catch (Exception ex) { FwkException("DoDestroys() Caught Exception: {0}", ex); } Thread.Sleep(3000); FwkInfo("DoDestroys() complete."); } public void DoCheckValues() { FwkInfo("In DoCheckValues()"); try { IRegion<TKey,TVal> region = GetRegion(); ICollection<TVal> vals = region.Values; int creates = 0; int updates = 0; int unknowns = 0; if (vals != null) { byte[] createPrefix = Encoding.ASCII.GetBytes("Create "); byte[] updatePrefix = Encoding.ASCII.GetBytes("Update "); foreach (object val in vals) { byte[] valBytes = val as byte[]; if (Util.CompareArraysPrefix(valBytes, createPrefix)) { creates++; } else if (Util.CompareArraysPrefix(valBytes, updatePrefix)) { updates++; } else { unknowns++; } } FwkInfo("DoCheckValues() Found {0} values from creates, " + "{1} values from updates, and {2} unknown values.", creates, updates, unknowns); } } catch (Exception ex) { FwkException("DoCheckValues() Caught Exception: {0}", ex); } } public void DoLocalDestroyEntries() { FwkInfo("In DoLocalDestroyEntries()"); try { IRegion<TKey,TVal> region = GetRegion(); ICollection<TKey> keys = region.GetLocalView().Keys; if (keys != null) { foreach (TKey key in keys) { region.GetLocalView().Remove(key); } } } catch (Exception ex) { FwkException("DoLocalDestroyEntries() Caught Exception: {0}", ex); } } public void DoDestroyRegion() { FwkInfo("In DoDestroyRegion"); try { IRegion<TKey,TVal> region = GetRegion(); region.DestroyRegion(); } catch (Exception ex) { FwkException("DoDestroyRegion() caught exception: {0}" , ex); } } public void DoLocalDestroyRegion() { FwkInfo("In DoLocalDestroyRegion()"); try { IRegion<TKey,TVal> region = GetRegion(); region.GetLocalView().DestroyRegion(); } catch (Exception ex) { FwkException("DoLocalDestroyRegion() Caught Exception: {0}", ex); } } public void DoPutAll() { FwkInfo("In DoPutAll()"); try { IRegion<TKey,TVal> region = GetRegion(); ResetKey(DistinctKeys); int numKeys = InitKeys(); ResetKey(ValueSizes); InitValues(numKeys); IDictionary<TKey, TVal> map = new Dictionary<TKey, TVal>(); map.Clear(); Int32 i = 0; while (i < numKeys) { map.Add(m_keysA[i], m_cValues[i]); i++; } DateTime startTime; DateTime endTime; TimeSpan elapsedTime; startTime = DateTime.Now; region.PutAll(map, TimeSpan.FromSeconds(60)); endTime = DateTime.Now; elapsedTime = endTime - startTime; FwkInfo("PerfTests.DoPutAll: Time Taken to execute" + " the putAll for {0}: is {1}ms", numKeys, elapsedTime.TotalMilliseconds); } catch (Exception ex) { FwkException("DoPutAll() Caught Exception: {0}", ex); } FwkInfo("DoPutAll() complete."); } public void DoGetAllAndVerification() { FwkInfo("In DoGetAllAndVerification()"); try { IRegion<TKey,TVal> region = GetRegion(); ResetKey(DistinctKeys); ResetKey(ValueSizes); ResetKey("addToLocalCache"); ResetKey("inValidateRegion"); int numKeys = InitKeys(false); Int32 i = 0; bool isInvalidateRegion = GetBoolValue("isInvalidateRegion"); if (isInvalidateRegion) { region.GetLocalView().InvalidateRegion(); } List<TKey> keys = new List<TKey>(); keys.Clear(); while (i < numKeys) { keys.Add(m_keysA[i]); i++; } bool isAddToLocalCache = GetBoolValue("addToLocalCache"); Dictionary<TKey, TVal> values = new Dictionary<TKey, TVal>(); values.Clear(); DateTime startTime; DateTime endTime; TimeSpan elapsedTime; startTime = DateTime.Now; region.GetAll(keys.ToArray(), values, null, isAddToLocalCache); endTime = DateTime.Now; elapsedTime = endTime - startTime; FwkInfo("PerfTests.DoGetAllAndVerification: Time Taken to execute" + " the getAll for {0}: is {1}ms", numKeys, elapsedTime.TotalMilliseconds); int payload = GetUIntValue("valueSizes"); FwkInfo("PerfTests.DoGetAllAndVerification: keyCount = {0}" + " valueCount = {1} ", keys.Count, values.Count); if (values.Count == keys.Count) { foreach (KeyValuePair<TKey, TVal> entry in values) { TVal item = entry.Value; //if (item != payload) // rjk Need to check how to verify //{ // FwkException("PerfTests.DoGetAllAndVerification: value size {0} is not equal to " + // "expected payload size {1} for key : {2}", item.Length, payload, entry.Key); //} } } if (isAddToLocalCache) { if (keys.Count != region.Count) { FwkException("PerfTests.DoGetAllAndVerification: number of keys in region do not" + " match expected number"); } } else { if (region.Count != 0) { FwkException("PerfTests.DoGetAllAndVerification: expected zero keys in region"); } } } catch (Exception ex) { FwkException("DoGetAllAndVerification() Caught Exception: {0}", ex); } FwkInfo("DoGetAllAndVerification() complete."); } public void DoResetListener() { try { IRegion<TKey,TVal> region = GetRegion(); int sleepTime = GetUIntValue("sleepTime"); PerfTestCacheListener<TKey,TVal> listener = region.Attributes.CacheListener as PerfTestCacheListener<TKey, TVal>; if (listener != null) { listener.Reset(sleepTime); } } catch (Exception ex) { FwkSevere("DoResetListener() Caught Exception: {0}", ex); } Thread.Sleep(3000); FwkInfo("DoResetListener() complete."); } public void DoRegisterInterestList() { FwkInfo("In DoRegisterInterestList()"); try { ResetKey(DistinctKeys); ResetKey(KeyIndexBegin); ResetKey(RegisterKeys); string typ = GetStringValue(KeyType); // int is only value to use char newType = (typ == null || typ.Length == 0) ? 's' : typ[0]; IRegion<TKey,TVal> region = GetRegion(); int numKeys = GetUIntValue(DistinctKeys); // check distince keys first if (numKeys <= 0) { FwkSevere("DoRegisterInterestList() Failed to initialize keys " + "with numKeys: {0}", numKeys); return; } int low = GetUIntValue(KeyIndexBegin); low = (low > 0) ? low : 0; int numOfRegisterKeys = GetUIntValue(RegisterKeys); int high = numOfRegisterKeys + low; ClearKeys(); m_maxKeys = numOfRegisterKeys; m_keyIndexBegin = low; m_keyType = newType; if (m_keyType == 'i') { InitIntKeys(low, high); } else { int keySize = GetUIntValue(KeySize); keySize = (keySize > 0) ? keySize : 10; string keyBase = new string('A', keySize); InitStrKeys(low, high, keyBase); } FwkInfo("DoRegisterInterestList() registering interest for {0} to {1}", low, high); TKey[] registerKeyList = new TKey[high - low]; for (int j = low; j < high; j++) { if (m_keysA[j - low] != null) { registerKeyList[j - low] = m_keysA[j - low]; } else { FwkInfo("DoRegisterInterestList() key[{0}] is null.", (j - low)); } } bool isDurable = GetBoolValue("isDurableReg"); ResetKey("getInitialValues"); bool isGetInitialValues = GetBoolValue("getInitialValues"); bool isReceiveValues = true; bool checkReceiveVal = GetBoolValue("checkReceiveVal"); if (checkReceiveVal) { ResetKey("receiveValue"); isReceiveValues = GetBoolValue("receiveValue"); } region.GetSubscriptionService().RegisterKeys(registerKeyList, isDurable, isGetInitialValues, isReceiveValues); String durableClientId = CacheHelper<TKey, TVal>.DCache.SystemProperties.DurableClientId; if (durableClientId.Length > 0) { CacheHelper<TKey, TVal>.DCache.ReadyForEvents(); } } catch (Exception ex) { FwkException("DoRegisterInterestList() Caught Exception: {0}", ex); } FwkInfo("DoRegisterInterestList() complete."); } public void DoRegisterAllKeys() { FwkInfo("In DoRegisterAllKeys()"); try { IRegion<TKey,TVal> region = GetRegion(); FwkInfo("DoRegisterAllKeys() region name is {0}", region.Name); bool isDurable = GetBoolValue("isDurableReg"); ResetKey("getInitialValues"); bool isGetInitialValues = GetBoolValue("getInitialValues"); bool checkReceiveVal = GetBoolValue("checkReceiveVal"); bool isReceiveValues = true; if (checkReceiveVal) { ResetKey("receiveValue"); isReceiveValues = GetBoolValue("receiveValue"); } region.GetSubscriptionService().RegisterAllKeys(isDurable, isGetInitialValues,isReceiveValues); String durableClientId = CacheHelper<TKey, TVal>.DCache.SystemProperties.DurableClientId; if (durableClientId.Length > 0) { CacheHelper<TKey, TVal>.DCache.ReadyForEvents(); } } catch (Exception ex) { FwkException("DoRegisterAllKeys() Caught Exception: {0}", ex); } FwkInfo("DoRegisterAllKeys() complete."); } public void DoVerifyInterestList() { FwkInfo("In DoVerifyInterestList()"); try { int countUpdate = 0; IRegion<TKey,TVal> region = GetRegion(); InitKeys(); ResetKey(RegisterKeys); int numOfRegisterKeys = GetUIntValue(RegisterKeys); int payload = GetUIntValue(ValueSizes); ICollection<TKey> keys = region.GetLocalView().Keys; byte[] value; int valueSize; if (keys != null) { foreach (TKey key in keys) { bool containsValue = region.ContainsValueForKey(key); RegionEntry<TKey,TVal> entry = region.GetEntry(key); if(!containsValue) { FwkInfo("Skipping check for key {0}",key); } else { if (entry == null) { FwkException("Failed to find entry for key [{0}] in local cache", key); } value = entry.Value as byte[]; if (value == null) { FwkException("Failed to find value for key [{0}] in local cache", key); } valueSize = (value == null ? -1 : value.Length); if (valueSize == payload) { ++countUpdate; } } GC.KeepAlive(entry); } } if (countUpdate != numOfRegisterKeys) { FwkException("DoVerifyInterestList() update interest list " + "count {0} is not equal to number of register keys {1}", countUpdate, numOfRegisterKeys); } } catch (Exception ex) { FwkException("DoVerifyInterestList() Caught Exception: {0} : {1}",ex.GetType().Name, ex); } FwkInfo("DoVerifyInterestList() complete."); } public void DoRegisterRegexList() { FwkInfo("In DoRegisterRegexList()"); try { IRegion<TKey,TVal> region = GetRegion(); string regex = GetStringValue(RegisterRegex); FwkInfo("DoRegisterRegexList() region name is {0}; regex is {1}", region.Name, regex); bool isDurable = GetBoolValue("isDurableReg"); ResetKey("getInitialValues"); bool isGetInitialValues = GetBoolValue("getInitialValues"); bool isReceiveValues = true; bool checkReceiveVal = GetBoolValue("checkReceiveVal"); if (checkReceiveVal) { ResetKey("receiveValue"); isReceiveValues = GetBoolValue("receiveValue"); } region.GetSubscriptionService().RegisterRegex(regex, isDurable, isGetInitialValues, isReceiveValues); String durableClientId = CacheHelper<TKey, TVal>.DCache.SystemProperties.DurableClientId; if (durableClientId.Length > 0) { CacheHelper<TKey, TVal>.DCache.ReadyForEvents(); } } catch (Exception ex) { FwkException("DoRegisterRegexList() Caught Exception: {0}", ex); } FwkInfo("DoRegisterRegexList() complete."); } public void DoUnRegisterRegexList() { FwkInfo("In DoUnRegisterRegexList()"); try { IRegion<TKey,TVal> region = GetRegion(); string regex = GetStringValue(UnregisterRegex); FwkInfo("DoUnRegisterRegexList() region name is {0}; regex is {1}", region.Name, regex); region.GetSubscriptionService().UnregisterRegex(regex); } catch (Exception ex) { FwkException("DoUnRegisterRegexList() Caught Exception: {0}", ex); } FwkInfo("DoUnRegisterRegexList() complete."); } public void DoDestroysKeys() { FwkInfo("In PerfTest::DoDestroyKeys()"); try { IRegion<TKey,TVal> region=GetRegion(); ResetKey("distinctKeys"); InitValues(InitKeys()); DestroyTask<TKey, TVal> destroys = new DestroyTask<TKey, TVal>(region, m_keysA); RunTask(destroys,1,m_maxKeys,-1,-1,null); } catch(Exception e) { FwkException("PerfTest caught exception: {0}", e); } FwkInfo("In PerfTest::DoDestroyKeys()complete"); } public void DoServerKeys() { FwkInfo("In DoServerKeys()"); try { IRegion<TKey,TVal> region = GetRegion(); FwkAssert(region != null, "DoServerKeys() No region to perform operations on."); FwkInfo("DoServerKeys() region name is {0}", region.Name); int expectedKeys = GetUIntValue(ExpectedCount); ICollection<TKey> serverKeys = region.Keys; int foundKeys = (serverKeys == null ? 0 : serverKeys.Count); FwkAssert(expectedKeys == foundKeys, "DoServerKeys() expected {0} keys but found {1} keys.", expectedKeys, foundKeys); } catch (Exception ex) { FwkException("DoServerKeys() Caught Exception: {0}", ex); } FwkInfo("DoServerKeys() complete."); } public void DoIterateInt32Keys() { FwkInfo("DoIterateInt32Keys() called."); try { IRegion<TKey,TVal> region = GetRegion(); FwkAssert(region != null, "DoIterateInt32Keys() No region to perform operations on."); FwkInfo("DoIterateInt32Keys() region name is {0}", region.Name); ICollection<TKey> serverKeys = region.Keys; FwkInfo("DoIterateInt32Keys() GetServerKeys() returned {0} keys.", (serverKeys != null ? serverKeys.Count : 0)); if (serverKeys != null) { foreach (TKey intKey in serverKeys) { FwkInfo("ServerKeys: {0}", intKey); } } } catch (Exception ex) { FwkException("DoIterateInt32Keys() Caught Exception: {0}", ex); } FwkInfo("DoIterateInt32Keys() complete."); } public void DoValidateQConflation() { FwkInfo("DoValidateQConflation() called."); try { IRegion<TKey,TVal> region = GetRegion(); region.GetLocalView().DestroyRegion(); int expectedAfterCreateEvent = GetUIntValue("expectedAfterCreateCount"); int expectedAfterUpdateEvent = GetUIntValue("expectedAfterUpdateCount"); bool isServerConflateTrue = GetBoolValue("isServerConflateTrue"); Int32 eventAfterCreate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_CREATE_COUNT_" + Util.ClientId + "_" + region.Name); Int32 eventAfterUpdate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_UPDATE_COUNT_" + Util.ClientId + "_" + region.Name); FwkInfo("DoValidateQConflation() -- eventAfterCreate {0} and eventAfterUpdate {1}", eventAfterCreate, eventAfterUpdate); String conflateEvent = CacheHelper<TKey, TVal>.DCache.SystemProperties.ConflateEvents; String durableClientId = CacheHelper<TKey, TVal>.DCache.SystemProperties.DurableClientId; Int32 totalCount = 3500; if(durableClientId.Length > 0) { FwkInfo("DoValidateQConflation() Validation for Durable client ."); if (conflateEvent.Equals("true") && ((eventAfterCreate + eventAfterUpdate) < totalCount +10)) { FwkInfo("DoValidateQConflation() Conflate Events is true complete."); } else if (conflateEvent.Equals("false") && ((eventAfterCreate + eventAfterUpdate) == totalCount +10)) { FwkInfo("DoValidateQConflation() Conflate Events is false complete."); } else if (conflateEvent.Equals("server") && isServerConflateTrue && ((eventAfterCreate + eventAfterUpdate) <= totalCount + 10)) { FwkInfo("DoValidateQConflation() Conflate Events is server=true complete."); } else if (conflateEvent.Equals("server") && !isServerConflateTrue && ((eventAfterCreate + eventAfterUpdate) == totalCount + 10)) { FwkInfo("DoValidateQConflation() Conflate Events is server=false complete."); } else { FwkException("DoValidateQConflation() ConflateEvent setting is {0} and Expected AfterCreateCount to have {1} keys and " + " found {2} . Expected AfterUpdateCount to have {3} keys, found {4} keys", conflateEvent, expectedAfterCreateEvent , eventAfterCreate, expectedAfterUpdateEvent, eventAfterUpdate); } } else { if (conflateEvent.Equals("true") && ((eventAfterCreate == expectedAfterCreateEvent) && (((eventAfterUpdate >= expectedAfterUpdateEvent)) && eventAfterUpdate < totalCount))) { FwkInfo("DoValidateQConflation() Conflate Events is true complete."); } else if (conflateEvent.Equals("false") && ((eventAfterCreate == expectedAfterCreateEvent) && (eventAfterUpdate == expectedAfterUpdateEvent))) { FwkInfo("DoValidateQConflation() Conflate Events is false complete."); } else if (conflateEvent.Equals("server") && isServerConflateTrue && ((eventAfterCreate == expectedAfterCreateEvent) && (((eventAfterUpdate >= expectedAfterUpdateEvent)) && eventAfterUpdate < totalCount))) { FwkInfo("DoValidateQConflation() Conflate Events is server=true complete."); } else if (conflateEvent.Equals("server") && !isServerConflateTrue && ((eventAfterCreate == expectedAfterCreateEvent) && (eventAfterUpdate == expectedAfterUpdateEvent))) { FwkInfo("DoValidateQConflation() Conflate Events is server=false complete."); } else { FwkException("DoValidateQConflation() ConflateEvent setting is {0} and Expected AfterCreateCount to have {1} keys and " + " found {2} . Expected AfterUpdateCount to have {3} keys, found {4} keys" , conflateEvent,expectedAfterCreateEvent , eventAfterCreate,expectedAfterUpdateEvent, eventAfterUpdate); } } } catch (Exception ex) { FwkException("DoValidateQConflation() Caught Exception: {0}", ex); } FwkInfo("DoValidateQConflation() complete."); } public void DoCreateUpdateDestroy() { FwkInfo("DoCreateUpdateDestroy() called."); try { DoPopulateRegion(); DoPopulateRegion(); DoDestroysKeys(); } catch (Exception ex) { FwkException("DoCreateUpdateDestroy() Caught Exception: {0}", ex); } FwkInfo("DoCreateUpdateDestroy() complete."); } public void DoValidateBankTest() { FwkInfo("DoValidateBankTest() called."); try { IRegion<TKey,TVal> region = GetRegion(); region.GetLocalView().DestroyRegion(); int expectedAfterCreateEvent = GetUIntValue("expectedAfterCreateCount"); int expectedAfterUpdateEvent = GetUIntValue("expectedAfterUpdateCount"); int expectedAfterInvalidateEvent = GetUIntValue("expectedAfterInvalidateCount"); int expectedAfterDestroyEvent = GetUIntValue("expectedAfterDestroyCount"); Int32 eventAfterCreate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_CREATE_COUNT_" + Util.ClientId + "_" + region.Name); Int32 eventAfterUpdate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_UPDATE_COUNT_" + Util.ClientId + "_" + region.Name); Int32 eventAfterInvalidate = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_INVALIDATE_COUNT_" + Util.ClientId + "_" + region.Name); Int32 eventAfterDestroy = (Int32)Util.BBGet("ConflationCacheListener", "AFTER_DESTROY_COUNT_" + Util.ClientId + "_" + region.Name); FwkInfo("DoValidateBankTest() -- eventAfterCreate {0} ,eventAfterUpdate {1} ," + "eventAfterInvalidate {2} , eventAfterDestroy {3}", eventAfterCreate, eventAfterUpdate,eventAfterInvalidate,eventAfterDestroy); if (expectedAfterCreateEvent == eventAfterCreate && expectedAfterUpdateEvent == eventAfterUpdate && expectedAfterInvalidateEvent == eventAfterInvalidate && expectedAfterDestroyEvent == eventAfterDestroy) { FwkInfo("DoValidateBankTest() Validation success."); } else { FwkException("Validation Failed() Region: {0} eventAfterCreate {1}, eventAfterUpdate {2} " + "eventAfterInvalidate {3}, eventAfterDestroy {4} ",region.Name, eventAfterCreate, eventAfterUpdate , eventAfterInvalidate, eventAfterDestroy); } } catch (Exception ex) { FwkException("DoValidateBankTest() Caught Exception: {0}", ex); } FwkInfo("DoValidateBankTest() complete."); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DevTestLabs { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for SchedulesOperations. /// </summary> public static partial class SchedulesOperationsExtensions { /// <summary> /// List schedules in a given lab. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<Schedule> List(this ISchedulesOperations operations, string labName, ODataQuery<Schedule> odataQuery = default(ODataQuery<Schedule>)) { return Task.Factory.StartNew(s => ((ISchedulesOperations)s).ListAsync(labName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List schedules in a given lab. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Schedule>> ListAsync(this ISchedulesOperations operations, string labName, ODataQuery<Schedule> odataQuery = default(ODataQuery<Schedule>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(labName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='expand'> /// Specify the $expand query. Example: 'properties($select=status)' /// </param> public static Schedule Get(this ISchedulesOperations operations, string labName, string name, string expand = default(string)) { return Task.Factory.StartNew(s => ((ISchedulesOperations)s).GetAsync(labName, name, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='expand'> /// Specify the $expand query. Example: 'properties($select=status)' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Schedule> GetAsync(this ISchedulesOperations operations, string labName, string name, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(labName, name, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create or replace an existing schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='schedule'> /// A schedule. /// </param> public static Schedule CreateOrUpdate(this ISchedulesOperations operations, string labName, string name, Schedule schedule) { return Task.Factory.StartNew(s => ((ISchedulesOperations)s).CreateOrUpdateAsync(labName, name, schedule), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or replace an existing schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='schedule'> /// A schedule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Schedule> CreateOrUpdateAsync(this ISchedulesOperations operations, string labName, string name, Schedule schedule, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(labName, name, schedule, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> public static void Delete(this ISchedulesOperations operations, string labName, string name) { Task.Factory.StartNew(s => ((ISchedulesOperations)s).DeleteAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete schedule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this ISchedulesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Modify properties of schedules. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='schedule'> /// A schedule. /// </param> public static Schedule Update(this ISchedulesOperations operations, string labName, string name, ScheduleFragment schedule) { return Task.Factory.StartNew(s => ((ISchedulesOperations)s).UpdateAsync(labName, name, schedule), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Modify properties of schedules. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='schedule'> /// A schedule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Schedule> UpdateAsync(this ISchedulesOperations operations, string labName, string name, ScheduleFragment schedule, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(labName, name, schedule, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Execute a schedule. This operation can take a while to complete. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> public static void Execute(this ISchedulesOperations operations, string labName, string name) { Task.Factory.StartNew(s => ((ISchedulesOperations)s).ExecuteAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Execute a schedule. This operation can take a while to complete. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ExecuteAsync(this ISchedulesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken)) { await operations.ExecuteWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Execute a schedule. This operation can take a while to complete. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> public static void BeginExecute(this ISchedulesOperations operations, string labName, string name) { Task.Factory.StartNew(s => ((ISchedulesOperations)s).BeginExecuteAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Execute a schedule. This operation can take a while to complete. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginExecuteAsync(this ISchedulesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginExecuteWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Lists all applicable schedules /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> public static IPage<Schedule> ListApplicable(this ISchedulesOperations operations, string labName, string name) { return Task.Factory.StartNew(s => ((ISchedulesOperations)s).ListApplicableAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all applicable schedules /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the schedule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Schedule>> ListApplicableAsync(this ISchedulesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListApplicableWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// List schedules in a given lab. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Schedule> ListNext(this ISchedulesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((ISchedulesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List schedules in a given lab. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Schedule>> ListNextAsync(this ISchedulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all applicable schedules /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Schedule> ListApplicableNext(this ISchedulesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((ISchedulesOperations)s).ListApplicableNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all applicable schedules /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Schedule>> ListApplicableNextAsync(this ISchedulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListApplicableNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: MemoryStream ** ** ** Purpose: A Stream whose backing store is memory. Great ** for temporary storage without creating a temp file. Also ** lets users expose a byte[] as a stream. ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; namespace System.IO { // A MemoryStream represents a Stream in memory (ie, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. [Serializable] public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? // <TODO>In V2, if we get support for arrays of more than 2 GB worth of elements, // consider removing this constraing, or setting it to Int64.MaxValue.</TODO> private const int MemStreamMaxLength = Int32.MaxValue; public MemoryStream() : this( 0 ) { } public MemoryStream( int capacity ) { if(capacity < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "capacity", Environment.GetResourceString( "ArgumentOutOfRange_NegativeCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } _buffer = new byte[capacity]; _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } public MemoryStream( byte[] buffer ) : this( buffer, true ) { } public MemoryStream( byte[] buffer, bool writable ) { if(buffer == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream( byte[] buffer, int index, int count ) : this( buffer, index, count, true, false ) { } public MemoryStream( byte[] buffer, int index, int count, bool writable ) : this( buffer, index, count, writable, false ) { } public MemoryStream( byte[] buffer, int index, int count, bool writable, bool publiclyVisible ) { if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can GetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { get { return _isOpen; } } public override bool CanSeek { get { return _isOpen; } } public override bool CanWrite { get { return _writable; } } protected override void Dispose( bool disposing ) { try { if(disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow GetBuffer & ToArray to work. } } finally { // Call base.Close() to cleanup async IO resources base.Dispose( disposing ); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity( int value ) { // Check for overflow if(value < 0) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_StreamTooLong" ) ); #else throw new IOException(); #endif } if(value > _capacity) { int newCapacity = value; if(newCapacity < 256) newCapacity = 256; if(newCapacity < _capacity * 2) newCapacity = _capacity * 2; Capacity = newCapacity; return true; } return false; } public override void Flush() { } public virtual byte[] GetBuffer() { if(!_exposable) { #if EXCEPTION_STRINGS throw new UnauthorizedAccessException( Environment.GetResourceString( "UnauthorizedAccess_MemStreamBuffer" ) ); #else throw new UnauthorizedAccessException(); #endif } return _buffer; } // -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) --------------- // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) internal byte[] InternalGetBuffer() { return _buffer; } // PERF: Get origin and length - used in ResourceWriter. internal void InternalGetOriginAndLength( out int origin, out int length ) { if(!_isOpen) { __Error.StreamIsClosed(); } origin = _origin; length = _length; } // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() { if(!_isOpen) { __Error.StreamIsClosed(); } return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if(!_isOpen) { __Error.StreamIsClosed(); } int pos = (_position += 4); // use temp to avoid race if(pos > _length) { _position = _length; __Error.EndOfFile(); } return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead( int count ) { if(!_isOpen) { __Error.StreamIsClosed(); } int n = _length - _position; if(n > count) n = count; if(n < 0) n = 0; BCLDebug.Assert( _position + n >= 0, "_position + n >= 0" ); // len is less than 2^31 -1. _position += n; return n; } // Gets &; sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if(!_isOpen) { __Error.StreamIsClosed(); } return _capacity - _origin; } set { if(!_isOpen) { __Error.StreamIsClosed(); } if(value != _capacity) { if(!_expandable) { __Error.MemoryStreamNotExpandable(); } if(value < _length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value > 0) { byte[] newBuffer = new byte[value]; if(_length > 0) Buffer.InternalBlockCopy( _buffer, 0, newBuffer, 0, _length ); _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { get { if(!_isOpen) { __Error.StreamIsClosed(); } return _length - _origin; } } public override long Position { get { if(!_isOpen) { __Error.StreamIsClosed(); } return _position - _origin; } set { if(!_isOpen) { __Error.StreamIsClosed(); } if(value < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value > MemStreamMaxLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_MemStreamLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } _position = _origin + (int)value; } } public override int Read( [In, Out] byte[] buffer, int offset, int count ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(offset < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - offset < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } int n = _length - _position; if(n > count) n = count; if(n <= 0) { return 0; } BCLDebug.Assert( _position + n >= 0, "_position + n >= 0" ); // len is less than 2^31 -1. if(n <= 8) { int byteCount = n; while(--byteCount >= 0) { buffer[offset + byteCount] = _buffer[_position + byteCount]; } } else { Buffer.InternalBlockCopy( _buffer, _position, buffer, offset, n ); } _position += n; return n; } public override int ReadByte() { if(!_isOpen) { __Error.StreamIsClosed(); } if(_position >= _length) return -1; return _buffer[_position++]; } public override long Seek( long offset, SeekOrigin loc ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(offset > MemStreamMaxLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", Environment.GetResourceString( "ArgumentOutOfRange_MemStreamLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } switch(loc) { case SeekOrigin.Begin: if(offset < 0) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_SeekBeforeBegin" ) ); #else throw new IOException(); #endif } _position = _origin + (int)offset; break; case SeekOrigin.Current: if(offset + _position < _origin) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_SeekBeforeBegin" ) ); #else throw new IOException(); #endif } _position += (int)offset; break; case SeekOrigin.End: if(_length + offset < _origin) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_SeekBeforeBegin" ) ); #else throw new IOException(); #endif } _position = _length + (int)offset; break; default: #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidSeekOrigin" ) ); #else throw new ArgumentException(); #endif } BCLDebug.Assert( _position >= 0, "_position >= 0" ); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength( long value ) { if(!_writable) { __Error.WriteNotSupported(); } if(value > MemStreamMaxLength) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_MemStreamLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(value < 0 || value > (Int32.MaxValue - _origin)) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_MemStreamLength" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity( newLength ); if(!allocatedNewArray && newLength > _length) { Array.Clear( _buffer, _length, newLength - _length ); } _length = newLength; if(_position > newLength) _position = newLength; } public virtual byte[] ToArray() { BCLDebug.Perf( _exposable, "MemoryStream::GetBuffer will let you avoid a copy." ); byte[] copy = new byte[_length - _origin]; Buffer.InternalBlockCopy( _buffer, _origin, copy, 0, _length - _origin ); return copy; } public override void Write( byte[] buffer, int offset, int count ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(!_writable) { __Error.WriteNotSupported(); } if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(offset < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "offset", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - offset < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } int i = _position + count; // Check for overflow if(i < 0) { #if EXCEPTION_STRINGS throw new IOException( Environment.GetResourceString( "IO.IO_StreamTooLong" ) ); #else throw new IOException(); #endif } if(i > _length) { bool mustZero = _position > _length; if(i > _capacity) { bool allocatedNewArray = EnsureCapacity( i ); if(allocatedNewArray) { mustZero = false; } } if(mustZero) { Array.Clear( _buffer, _length, i - _length ); } _length = i; } if((count <= 8) && (buffer != _buffer)) { int byteCount = count; while(--byteCount >= 0) { _buffer[_position + byteCount] = buffer[offset + byteCount]; } } else { Buffer.InternalBlockCopy( buffer, offset, _buffer, _position, count ); } _position = i; return; } public override void WriteByte( byte value ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(!_writable) { __Error.WriteNotSupported(); } if(_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if(newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity( newLength ); if(allocatedNewArray) { mustZero = false; } } if(mustZero) { Array.Clear( _buffer, _length, _position - _length ); } _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo( Stream stream ) { if(!_isOpen) { __Error.StreamIsClosed(); } if(stream == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "stream", Environment.GetResourceString( "ArgumentNull_Stream" ) ); #else throw new ArgumentNullException(); #endif } stream.Write( _buffer, _origin, _length - _origin ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class MaxTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > int.MinValue select x; Assert.Equal(q.Max(), q.Max()); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", string.Empty } where !string.IsNullOrEmpty(x) select x; Assert.Equal(q.Max(), q.Max()); } [Fact] public void Max_Int_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Max(i => i)); } [Fact] public void Max_Int_EmptySource_ThrowsInvalidOpertionException() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().Max()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().Max(x => x)); } public static IEnumerable<object[]> Max_Int_TestData() { yield return new object[] { Enumerable.Repeat(42, 1), 42 }; yield return new object[] { Enumerable.Range(1, 10).ToArray(), 10 }; yield return new object[] { new int[] { -100, -15, -50, -10 }, -10 }; yield return new object[] { new int[] { -16, 0, 50, 100, 1000 }, 1000 }; yield return new object[] { new int[] { -16, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat(int.MaxValue, 1)), int.MaxValue }; yield return new object[] { Enumerable.Repeat(20, 1), 20 }; yield return new object[] { Enumerable.Repeat(-2, 5), -2 }; yield return new object[] { new int[] { 16, 9, 10, 7, 8 }, 16 }; yield return new object[] { new int[] { 6, 9, 10, 0, 50 }, 50 }; yield return new object[] { new int[] { -6, 0, -9, 0, -10, 0 }, 0 }; } [Theory] [MemberData(nameof(Max_Int_TestData))] public void Max_Int(IEnumerable<int> source, int expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } public static IEnumerable<object[]> Max_Long_TestData() { yield return new object[] { Enumerable.Repeat(42L, 1), 42L }; yield return new object[] { Enumerable.Range(1, 10).Select(i => (long)i).ToArray(), 10L }; yield return new object[] { new long[] { -100, -15, -50, -10 }, -10L }; yield return new object[] { new long[] { -16, 0, 50, 100, 1000 }, 1000L }; yield return new object[] { new long[] { -16, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat(long.MaxValue, 1)), long.MaxValue }; yield return new object[] { Enumerable.Repeat(int.MaxValue + 10L, 1), int.MaxValue + 10L }; yield return new object[] { Enumerable.Repeat(500L, 5), 500L }; yield return new object[] { new long[] { 250, 49, 130, 47, 28 }, 250L }; yield return new object[] { new long[] { 6, 9, 10, 0, int.MaxValue + 50L }, int.MaxValue + 50L }; yield return new object[] { new long[] { 6, 50, 9, 50, 10, 50 }, 50L }; } [Theory] [MemberData(nameof(Max_Long_TestData))] public void Max_Long(IEnumerable<long> source, long expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Fact] public void Max_Long_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Max(i => i)); } [Fact] public void Max_Long_EmptySource_ThrowsInvalidOpertionException() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().Max()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().Max(x => x)); } public static IEnumerable<object[]> Max_Float_TestData() { yield return new object[] { Enumerable.Repeat(42f, 1), 42f }; yield return new object[] { Enumerable.Range(1, 10).Select(i => (float)i).ToArray(), 10f }; yield return new object[] { new float[] { -100, -15, -50, -10 }, -10f }; yield return new object[] { new float[] { -16, 0, 50, 100, 1000 }, 1000f }; yield return new object[] { new float[] { -16, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat(float.MaxValue, 1)), float.MaxValue }; yield return new object[] { Enumerable.Repeat(5.5f, 1), 5.5f }; yield return new object[] { new float[] { 112.5f, 4.9f, 30f, 4.7f, 28f }, 112.5f }; yield return new object[] { new float[] { 6.8f, 9.4f, -10f, 0f, float.NaN, 53.6f }, 53.6f }; yield return new object[] { new float[] { -5.5f, float.PositiveInfinity, 9.9f, float.PositiveInfinity }, float.PositiveInfinity }; yield return new object[] { Enumerable.Repeat(float.NaN, 5), float.NaN }; yield return new object[] { new float[] { float.NaN, 6.8f, 9.4f, 10f, 0, -5.6f }, 10f }; yield return new object[] { new float[] { 6.8f, 9.4f, 10f, 0, -5.6f, float.NaN }, 10f }; yield return new object[] { new float[] { float.NaN, float.NegativeInfinity }, float.NegativeInfinity }; yield return new object[] { new float[] { float.NegativeInfinity, float.NaN }, float.NegativeInfinity }; // Normally NaN < anything and anything < NaN returns false // However, this leads to some irksome outcomes in Min and Max. // If we use those semantics then Min(NaN, 5.0) is NaN, but // Min(5.0, NaN) is 5.0! To fix this, we impose a total // ordering where NaN is smaller than every value, including // negative infinity. yield return new object[] { Enumerable.Range(1, 10).Select(i => (float)i).Concat(Enumerable.Repeat(float.NaN, 1)).ToArray(), 10f }; yield return new object[] { new float[] { -1f, -10, float.NaN, 10, 200, 1000 }, 1000f }; yield return new object[] { new float[] { float.MinValue, 3000f, 100, 200, float.NaN, 1000 }, 3000f }; } [Theory] [MemberData(nameof(Max_Float_TestData))] public void Max_Float(IEnumerable<float> source, float expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Fact] public void Max_Float_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Max(i => i)); } [Fact] public void Max_Float_EmptySource_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().Max()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().Max(x => x)); } [Fact] public void Max_Float_SeveralNaNWithSelector() { Assert.True(float.IsNaN(Enumerable.Repeat(float.NaN, 5).Max(i => i))); } [Fact] public void Max_NullableFloat_SeveralNaNOrNullWithSelector() { float?[] source = new float?[] { float.NaN, null, float.NaN, null }; Assert.True(float.IsNaN(source.Max(i => i).Value)); } [Fact] public void Max_Float_NaNAtStartWithSelector() { float[] source = { float.NaN, 6.8f, 9.4f, 10f, 0, -5.6f }; Assert.Equal(10f, source.Max(i => i)); } public static IEnumerable<object[]> Max_Double_TestData() { yield return new object[] { Enumerable.Repeat(42.0, 1), 42.0 }; yield return new object[] { Enumerable.Range(1, 10).Select(i => (double)i).ToArray(), 10.0 }; yield return new object[] { new double[] { -100, -15, -50, -10 }, -10.0 }; yield return new object[] { new double[] { -16, 0, 50, 100, 1000 }, 1000.0 }; yield return new object[] { new double[] { -16, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat(double.MaxValue, 1)), double.MaxValue }; yield return new object[] { Enumerable.Repeat(5.5, 1), 5.5 }; yield return new object[] { Enumerable.Repeat(double.NaN, 5), double.NaN }; yield return new object[] { new double[] { 112.5, 4.9, 30, 4.7, 28 }, 112.5 }; yield return new object[] { new double[] { 6.8, 9.4, -10, 0, double.NaN, 53.6 }, 53.6 }; yield return new object[] { new double[] { -5.5, double.PositiveInfinity, 9.9, double.PositiveInfinity }, double.PositiveInfinity }; yield return new object[] { new double[] { double.NaN, 6.8, 9.4, 10.5, 0, -5.6 }, 10.5 }; yield return new object[] { new double[] { 6.8, 9.4, 10.5, 0, -5.6, double.NaN }, 10.5 }; yield return new object[] { new double[] { double.NaN, double.NegativeInfinity }, double.NegativeInfinity }; yield return new object[] { new double[] { double.NegativeInfinity, double.NaN }, double.NegativeInfinity }; // Normally NaN < anything and anything < NaN returns false // However, this leads to some irksome outcomes in Min and Max. // If we use those semantics then Min(NaN, 5.0) is NaN, but // Min(5.0, NaN) is 5.0! To fix this, we impose a total // ordering where NaN is smaller than every value, including // negative infinity. yield return new object[] { Enumerable.Range(1, 10).Select(i => (double)i).Concat(Enumerable.Repeat(double.NaN, 1)).ToArray(), 10.0 }; yield return new object[] { new double[] { -1F, -10, double.NaN, 10, 200, 1000 }, 1000.0 }; yield return new object[] { new double[] { double.MinValue, 3000F, 100, 200, double.NaN, 1000 }, 3000.0 }; } [Theory] [MemberData(nameof(Max_Double_TestData))] public void Max_Double(IEnumerable<double> source, double expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Fact] public void Max_Double_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Max(i => i)); } [Fact] public void Max_Double_EmptySource_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().Max()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().Max(x => x)); } [Fact] public void Max_Double_AllNaNWithSelector() { Assert.True(double.IsNaN(Enumerable.Repeat(double.NaN, 5).Max(i => i))); } [Fact] public void Max_Double_SeveralNaNOrNullWithSelector() { double?[] source = new double?[] { double.NaN, null, double.NaN, null }; Assert.True(double.IsNaN(source.Max(i => i).Value)); } [Fact] public void Max_Double_NaNThenNegativeInfinityWithSelector() { double[] source = { double.NaN, double.NegativeInfinity }; Assert.True(double.IsNegativeInfinity(source.Max(i => i))); } public static IEnumerable<object[]> Max_Decimal_TestData() { yield return new object[] { Enumerable.Repeat(42m, 1), 42m }; yield return new object[] { Enumerable.Range(1, 10).Select(i => (decimal)i).ToArray(), 10m }; yield return new object[] { new decimal[] { -100, -15, -50, -10 }, -10m }; yield return new object[] { new decimal[] { -16, 0, 50, 100, 1000 }, 1000m }; yield return new object[] { new decimal[] { -16, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat(decimal.MaxValue, 1)), decimal.MaxValue }; yield return new object[] { new decimal[] { 5.5m }, 5.5m }; yield return new object[] { Enumerable.Repeat(-3.4m, 5), -3.4m }; yield return new object[] { new decimal[] { 122.5m, 4.9m, 10m, 4.7m, 28m }, 122.5m }; yield return new object[] { new decimal[] { 6.8m, 9.4m, 10m, 0m, 0m, decimal.MaxValue }, decimal.MaxValue }; yield return new object[] { new decimal[] { -5.5m, 0m, 9.9m, -5.5m, 9.9m }, 9.9m }; } [Theory] [MemberData(nameof(Max_Decimal_TestData))] public void Max_Decimal(IEnumerable<decimal> source, decimal expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Fact] public void Max_Decimal_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Max(i => i)); } [Fact] public void Max_Decimal_EmptySource_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().Max()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().Max(x => x)); } public static IEnumerable<object[]> Max_NullableInt_TestData() { yield return new object[] { Enumerable.Repeat((int?)42, 1), 42 }; yield return new object[] { Enumerable.Range(1, 10).Select(i => (int?)i).ToArray(), 10 }; yield return new object[] { new int?[] { null, -100, -15, -50, -10 }, -10 }; yield return new object[] { new int?[] { null, -16, 0, 50, 100, 1000 }, 1000 }; yield return new object[] { new int?[] { null, -16, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat((int?)int.MaxValue, 1)), int.MaxValue }; yield return new object[] { Enumerable.Repeat(default(int?), 100), null }; yield return new object[] { Enumerable.Empty<int?>(), null }; yield return new object[] { Enumerable.Repeat((int?)-20, 1), -20 }; yield return new object[] { new int?[] { -6, null, -9, -10, null, -17, -18 }, -6 }; yield return new object[] { new int?[] { null, null, null, null, null, -5 }, -5 }; yield return new object[] { new int?[] { 6, null, null, 100, 9, 100, 10, 100 }, 100 }; yield return new object[] { Enumerable.Repeat(default(int?), 5), null }; } [Theory] [MemberData(nameof(Max_NullableInt_TestData))] public void Max_NullableInt(IEnumerable<int?> source, int? expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Theory, MemberData(nameof(Max_NullableInt_TestData))] public void Max_NullableIntRunOnce(IEnumerable<int?> source, int? expected) { Assert.Equal(expected, source.RunOnce().Max()); Assert.Equal(expected, source.RunOnce().Max(x => x)); } [Fact] public void Max_NullableInt_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Max(i => i)); } public static IEnumerable<object[]> Max_NullableLong_TestData() { yield return new object[] { Enumerable.Repeat((long?)42, 1), 42L }; yield return new object[] { Enumerable.Range(1, 10).Select(i => (long?)i).ToArray(), 10L }; yield return new object[] { new long?[] { null, -100, -15, -50, -10 }, -10L }; yield return new object[] { new long?[] { null, -16, 0, 50, 100, 1000 }, 1000L }; yield return new object[] { new long?[] { null, -16, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat((long?)long.MaxValue, 1)), long.MaxValue }; yield return new object[] { Enumerable.Repeat(default(long?), 100), null }; yield return new object[] { Enumerable.Empty<long?>(), null }; yield return new object[] { Enumerable.Repeat((long?)long.MaxValue, 1), long.MaxValue }; yield return new object[] { Enumerable.Repeat(default(long?), 5), null }; yield return new object[] { new long?[] { long.MaxValue, null, 9, 10, null, 7, 8 }, long.MaxValue }; yield return new object[] { new long?[] { null, null, null, null, null, -long.MaxValue }, -long.MaxValue }; yield return new object[] { new long?[] { -6, null, null, 0, -9, 0, -10, -30 }, 0L }; } [Theory] [MemberData(nameof(Max_NullableLong_TestData))] public void Max_NullableLong(IEnumerable<long?> source, long? expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Fact] public void Max_NullableLong_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Max(i => i)); } public static IEnumerable<object[]> Max_NullableFloat_TestData() { yield return new object[] { Enumerable.Repeat((float?)42, 1), 42f }; yield return new object[] { Enumerable.Range(1, 10).Select(i => (float?)i).ToArray(), 10f }; yield return new object[] { new float?[] { null, -100, -15, -50, -10 }, -10f }; yield return new object[] { new float?[] { null, -16, 0, 50, 100, 1000 }, 1000f }; yield return new object[] { new float?[] { null, -16, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat((float?)float.MaxValue, 1)), float.MaxValue }; yield return new object[] { Enumerable.Repeat(default(float?), 100), null }; yield return new object[] { Enumerable.Empty<float?>(), null }; yield return new object[] { Enumerable.Repeat((float?)float.MinValue, 1), float.MinValue }; yield return new object[] { Enumerable.Repeat(default(float?), 5), null }; yield return new object[] { new float?[] { 14.50f, null, float.NaN, 10.98f, null, 7.5f, 8.6f }, 14.50f }; yield return new object[] { new float?[] { null, null, null, null, null, 0f }, 0f }; yield return new object[] { new float?[] { -6.4f, null, null, -0.5f, -9.4f, -0.5f, -10.9f, -0.5f }, -0.5f }; yield return new object[] { new float?[] { float.NaN, 6.8f, 9.4f, 10f, 0, null, -5.6f }, 10f }; yield return new object[] { new float?[] { 6.8f, 9.4f, 10f, 0, null, -5.6f, float.NaN }, 10f }; yield return new object[] { new float?[] { float.NaN, float.NegativeInfinity }, float.NegativeInfinity }; yield return new object[] { new float?[] { float.NegativeInfinity, float.NaN }, float.NegativeInfinity }; yield return new object[] { Enumerable.Repeat((float?)float.NaN, 3), float.NaN }; yield return new object[] { new float?[] { float.NaN, null, null, null }, float.NaN }; yield return new object[] { new float?[] { null, null, null, float.NaN }, float.NaN }; yield return new object[] { new float?[] { null, float.NaN, null }, float.NaN }; } [Theory] [MemberData(nameof(Max_NullableFloat_TestData))] public void Max_NullableFloat(IEnumerable<float?> source, float? expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Fact] public void Max_NullableFloat_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Max(i => i)); } public static IEnumerable<object[]> Max_NullableDouble_TestData() { yield return new object[] { Enumerable.Repeat((double?)42, 1), 42.0 }; yield return new object[] { Enumerable.Range(1, 10).Select(i => (double?)i).ToArray(), 10.0 }; yield return new object[] { new double?[] { null, -100, -15, -50, -10 }, -10.0 }; yield return new object[] { new double?[] { null, -16, 0, 50, 100, 1000 }, 1000.0 }; yield return new object[] { new double?[] { null, -16, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat((double?)double.MaxValue, 1)), double.MaxValue }; yield return new object[] { Enumerable.Repeat(default(double?), 100), null }; yield return new object[] { Enumerable.Empty<double?>(), null }; yield return new object[] { Enumerable.Repeat((double?)double.MinValue, 1), double.MinValue }; yield return new object[] { Enumerable.Repeat(default(double?), 5), null }; yield return new object[] { new double?[] { 14.50, null, double.NaN, 10.98, null, 7.5, 8.6 }, 14.50 }; yield return new object[] { new double?[] { null, null, null, null, null, 0 }, 0.0 }; yield return new object[] { new double?[] { -6.4, null, null, -0.5, -9.4, -0.5, -10.9, -0.5 }, -0.5 }; yield return new object[] { new double?[] { double.NaN, 6.8, 9.4, 10.5, 0, null, -5.6 }, 10.5 }; yield return new object[] { new double?[] { 6.8, 9.4, 10.8, 0, null, -5.6, double.NaN }, 10.8 }; yield return new object[] { new double?[] { double.NaN, double.NegativeInfinity }, double.NegativeInfinity }; yield return new object[] { new double?[] { double.NegativeInfinity, double.NaN }, double.NegativeInfinity }; yield return new object[] { Enumerable.Repeat((double?)double.NaN, 3), double.NaN }; yield return new object[] { new double?[] { double.NaN, null, null, null }, double.NaN }; yield return new object[] { new double?[] { null, null, null, double.NaN }, double.NaN }; yield return new object[] { new double?[] { null, double.NaN, null }, double.NaN }; } [Theory] [MemberData(nameof(Max_NullableDouble_TestData))] public void Max_NullableDouble(IEnumerable<double?> source, double? expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Fact] public void Max_NullableDouble_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double?>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double?>)null).Max(i => i)); } public static IEnumerable<object[]> Max_NullableDecimal_TestData() { yield return new object[] { Enumerable.Repeat((decimal?)42, 1), 42m }; yield return new object[] { Enumerable.Range(1, 10).Select(i => (decimal?)i).ToArray(), 10m }; yield return new object[] { new decimal?[] { null, -100M, -15, -50, -10 }, -10m }; yield return new object[] { new decimal?[] { null, -16M, 0, 50, 100, 1000 }, 1000m }; yield return new object[] { new decimal?[] { null, -16M, 0, 50, 100, 1000 }.Concat(Enumerable.Repeat((decimal?)decimal.MaxValue, 1)), decimal.MaxValue }; yield return new object[] { Enumerable.Repeat(default(decimal?), 100), null }; yield return new object[] { Enumerable.Empty<decimal?>(), null }; yield return new object[] { Enumerable.Repeat((decimal?)decimal.MaxValue, 1), decimal.MaxValue }; yield return new object[] { Enumerable.Repeat(default(decimal?), 5), null }; yield return new object[] { new decimal?[] { 14.50m, null, null, 10.98m, null, 7.5m, 8.6m }, 14.50m }; yield return new object[] { new decimal?[] { null, null, null, null, null, 0m }, 0m }; yield return new object[] { new decimal?[] { 6.4m, null, null, decimal.MaxValue, 9.4m, decimal.MaxValue, 10.9m, decimal.MaxValue }, decimal.MaxValue }; } [Theory] [MemberData(nameof(Max_NullableDecimal_TestData))] public void Max_NullableDecimal(IEnumerable<decimal?> source, decimal? expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Fact] public void Max_NullableDecimal_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Max(i => i)); } public static IEnumerable<object[]> Max_DateTime_TestData() { yield return new object[] { Enumerable.Range(1, 10).Select(i => new DateTime(2000, 1, i)).ToArray(), new DateTime(2000, 1, 10) }; yield return new object[] { new DateTime[] { new DateTime(2000, 12, 1), new DateTime(2000, 12, 31), new DateTime(2000, 1, 12) }, new DateTime(2000, 12, 31) }; DateTime[] threeThousand = new DateTime[] { new DateTime(3000, 1, 1), new DateTime(100, 1, 1), new DateTime(200, 1, 1), new DateTime(1000, 1, 1) }; yield return new object[] { threeThousand, new DateTime(3000, 1, 1) }; yield return new object[] { threeThousand.Concat(Enumerable.Repeat(DateTime.MaxValue, 1)), DateTime.MaxValue }; } [Theory] [MemberData(nameof(Max_DateTime_TestData))] public void Max_DateTime(IEnumerable<DateTime> source, DateTime expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Fact] public void Max_DateTime_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<DateTime>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<DateTime>)null).Max(i => i)); } [Fact] public void Max_DateTime_EmptySource_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().Max()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().Max(i => i)); } public static IEnumerable<object[]> Max_String_TestData() { yield return new object[] { Enumerable.Range(1, 10).Select(i => i.ToString()).ToArray(), "9" }; yield return new object[] { new string[] { "Alice", "Bob", "Charlie", "Eve", "Mallory", "Victor", "Trent" }, "Victor" }; yield return new object[] { new string[] { null, "Charlie", null, "Victor", "Trent", null, "Eve", "Alice", "Mallory", "Bob" }, "Victor" }; yield return new object[] { Enumerable.Empty<string>(), null }; yield return new object[] { Enumerable.Repeat("Hello", 1), "Hello" }; yield return new object[] { Enumerable.Repeat("hi", 5), "hi" }; yield return new object[] { new string[] { "zzz", "aaa", "abcd", "bark", "temp", "cat" }, "zzz" }; yield return new object[] { new string[] { null, null, null, null, "aAa" }, "aAa" }; yield return new object[] { new string[] { "ooo", "ccc", "ccc", "ooo", "ooo", "nnn" }, "ooo" }; yield return new object[] { Enumerable.Repeat(default(string), 5), null }; } [Theory] [MemberData(nameof(Max_String_TestData))] public void Max_String(IEnumerable<string> source, string expected) { Assert.Equal(expected, source.Max()); Assert.Equal(expected, source.Max(x => x)); } [Theory, MemberData(nameof(Max_String_TestData))] public void Max_StringRunOnce(IEnumerable<string> source, string expected) { Assert.Equal(expected, source.RunOnce().Max()); Assert.Equal(expected, source.RunOnce().Max(x => x)); } [Fact] public void Max_String_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<string>)null).Max()); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<string>)null).Max(i => i)); } [Fact] public void Max_Int_NullSelector_ThrowsArgumentNullException() { Func<int, int> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int>().Max(selector)); } [Fact] public void Max_Int_WithSelectorAccessingProperty() { var source = new[] { new { name="Tim", num=10 }, new { name="John", num=-105 }, new { name="Bob", num=30 } }; Assert.Equal(30, source.Max(e => e.num)); } [Fact] public void Max_Long_NullSelector_ThrowsArgumentNullException() { Func<long, long> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long>().Max(selector)); } [Fact] public void Max_Long_WithSelectorAccessingProperty() { var source = new[] { new { name="Tim", num=10L }, new { name="John", num=-105L }, new { name="Bob", num=long.MaxValue } }; Assert.Equal(long.MaxValue, source.Max(e => e.num)); } [Fact] public void Max_Float_WithSelectorAccessingProperty() { var source = new[] { new { name = "Tim", num = 40.5f }, new { name = "John", num = -10.25f }, new { name = "Bob", num = 100.45f } }; Assert.Equal(100.45f, source.Select(e => e.num).Max()); } [Fact] public void Max_Float_NullSelector_ThrowsArgumentNullException() { Func<float, float> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float>().Max(selector)); } [Fact] public void Max_Double_NullSelector_ThrowsArgumentNullException() { Func<double, double> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double>().Max(selector)); } [Fact] public void Max_Double_WithSelectorAccessingField() { var source = new[] { new { name="Tim", num=40.5 }, new { name="John", num=-10.25 }, new { name="Bob", num=100.45 } }; Assert.Equal(100.45, source.Max(e => e.num)); } [Fact] public void Max_Decimal_NullSelector_ThrowsArgumentNullException() { Func<decimal, decimal> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal>().Max(selector)); } [Fact] public void Max_Decimal_WithSelectorAccessingProperty() { var source = new[]{ new { name="Tim", num=420.5m }, new { name="John", num=900.25m }, new { name="Bob", num=10.45m } }; Assert.Equal(900.25m, source.Max(e => e.num)); } [Fact] public void Max_NullableInt_NullSelector_ThrowsArgumentNullException() { Func<int?, int?> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int?>().Max(selector)); } [Fact] public void Max_NullableInt_WithSelectorAccessingField() { var source = new[]{ new { name="Tim", num=(int?)10 }, new { name="John", num=(int?)-105 }, new { name="Bob", num=(int?)null } }; Assert.Equal(10, source.Max(e => e.num)); } [Fact] public void Max_NullableLong_NullSelector_ThrowsArgumentNullException() { Func<long?, long?> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long?>().Max(selector)); } [Fact] public void Max_NullableLong_WithSelectorAccessingField() { var source = new[] { new {name="Tim", num=default(long?) }, new {name="John", num=(long?)-105L }, new {name="Bob", num=(long?)long.MaxValue } }; Assert.Equal(long.MaxValue, source.Max(e => e.num)); } [Fact] public void Max_NullableFloat_NullSelector_ThrowsArgumentNullException() { Func<float?, float?> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float?>().Max(selector)); } [Fact] public void Max_NullableFloat_WithSelectorAccessingProperty() { var source = new[] { new { name="Tim", num=(float?)40.5f }, new { name="John", num=(float?)null }, new { name="Bob", num=(float?)100.45f } }; Assert.Equal(100.45f, source.Max(e => e.num)); } [Fact] public void Max_NullableDouble_NullSelector_ThrowsArgumentNullException() { Func<double?, double?> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double?>().Max(selector)); } [Fact] public void Max_NullableDouble_WithSelectorAccessingProperty() { var source = new [] { new { name = "Tim", num = (double?)40.5}, new { name = "John", num = default(double?)}, new { name = "Bob", num = (double?)100.45} }; Assert.Equal(100.45, source.Max(e => e.num)); } [Fact] public void Max_NullableDecimal_NullSelector_ThrowsArgumentNullException() { Func<decimal?, decimal?> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal?>().Max(selector)); } [Fact] public void Max_NullableDecimal_WithSelectorAccessingProperty() { var source = new[] { new { name="Tim", num=(decimal?)420.5m }, new { name="John", num=default(decimal?) }, new { name="Bob", num=(decimal?)10.45m } }; Assert.Equal(420.5m, source.Max(e => e.num)); } [Fact] public void Max_NullableDateTime_EmptySourceWithSelector() { Assert.Null(Enumerable.Empty<DateTime?>().Max(x => x)); } [Fact] public void Max_NullableDateTime_NullSelector_ThrowsArgumentNullException() { Func<DateTime?, DateTime?> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<DateTime?>().Max(selector)); } [Fact] public void Max_String_NullSelector_ThrowsArgumentNullException() { Func<string, string> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<string>().Max(selector)); } [Fact] public void Max_String_WithSelectorAccessingProperty() { var source = new[] { new { name="Tim", num=420.5m }, new { name="John", num=900.25m }, new { name="Bob", num=10.45m } }; Assert.Equal("Tim", source.Max(e => e.name)); } [Fact] public void Max_Boolean_EmptySource_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<bool>().Max()); } } }
using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; using u16 = System.UInt16; using Pgno = System.UInt32; namespace Community.CsharpSqlite { using sqlite3_int64 = System.Int64; using sqlite3_stmt = Sqlite3.Vdbe; using System.Security.Cryptography; using System.IO; public partial class Sqlite3 { /* ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2010 Noah B Hart, Diego Torres ** C#-SQLite is an independent reimplementation of the SQLite software library ** ************************************************************************* */ /* ** SQLCipher ** crypto.c developed by Stephen Lombardo (Zetetic LLC) ** sjlombardo at zetetic dot net ** http://zetetic.net ** ** Copyright (c) 2009, ZETETIC LLC ** 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 ZETETIC LLC 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 ZETETIC LLC ''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 ZETETIC LLC 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. ** */ /* BEGIN CRYPTO */ #if !NOT_SQLITE_HAS_CODEC //#if SQLITE_HAS_CODEC //#include <assert.h> //#include <openssl/evp.h> //#include <openssl/rand.h> //#include <openssl/hmac.h> //#include "sqliteInt.h" //#include "btreeInt.h" //#include "crypto.h" #if CODEC_DEBUG || TRACE //#define CODEC_TRACE(X) {printf X;fflush(stdout);} static void CODEC_TRACE( string T, params object[] ap ) { if ( sqlite3PagerTrace )sqlite3DebugPrintf( T, ap ); } #else //#define CODEC_TRACE(X) static void CODEC_TRACE( string T, params object[] ap ) { } #endif //void sqlite3FreeCodecArg(void *pCodecArg); public class cipher_ctx {//typedef struct { public string pass; public int pass_sz; public bool derive_key; public byte[] key; public int key_sz; public byte[] iv; public int iv_sz; public ICryptoTransform encryptor; public ICryptoTransform decryptor; public cipher_ctx Copy() { cipher_ctx c = new cipher_ctx(); c.derive_key = derive_key; c.pass = pass; c.pass_sz = pass_sz; if ( key != null ) { c.key = new byte[key.Length]; key.CopyTo( c.key, 0 ); } c.key_sz = key_sz; if ( iv != null ) { c.iv = new byte[iv.Length]; iv.CopyTo( c.iv, 0 ); } c.iv_sz = iv_sz; c.encryptor = encryptor; c.decryptor = decryptor; return c; } public void CopyTo( cipher_ctx ct ) { ct.derive_key = derive_key; ct.pass = pass; ct.pass_sz = pass_sz; if ( key != null ) { ct.key = new byte[key.Length]; key.CopyTo( ct.key, 0 ); } ct.key_sz = key_sz; if ( iv != null ) { ct.iv = new byte[iv.Length]; iv.CopyTo( ct.iv, 0 ); } ct.iv_sz = iv_sz; ct.encryptor = encryptor; ct.decryptor = decryptor; } } public class codec_ctx {//typedef struct { public int mode_rekey; public byte[] buffer; public Btree pBt; public cipher_ctx read_ctx; public cipher_ctx write_ctx; public codec_ctx Copy() { codec_ctx c = new codec_ctx(); c.mode_rekey = mode_rekey; c.buffer = sqlite3MemMalloc( buffer.Length ); c.pBt = pBt; if ( read_ctx != null ) c.read_ctx = read_ctx.Copy(); if ( write_ctx != null ) c.write_ctx = write_ctx.Copy(); return c; } } const int FILE_HEADER_SZ = 16; //#define FILE_HEADER_SZ 16 const string CIPHER = "aes-256-cbc"; //#define CIPHER "aes-256-cbc" const int CIPHER_DECRYPT = 0; //#define CIPHER_DECRYPT 0 const int CIPHER_ENCRYPT = 1; //#define CIPHER_ENCRYPT 1 #if NET_2_0 static RijndaelManaged Aes = new RijndaelManaged(); #else static AesManaged Aes = new AesManaged(); #endif /* BEGIN CRYPTO */ static void sqlite3pager_get_codec( Pager pPager, ref codec_ctx ctx ) { ctx = pPager.pCodec; } static int sqlite3pager_is_mj_pgno( Pager pPager, Pgno pgno ) { return ( PAGER_MJ_PGNO( pPager ) == pgno ) ? 1 : 0; } static sqlite3_file sqlite3Pager_get_fd( Pager pPager ) { return ( isOpen( pPager.fd ) ) ? pPager.fd : null; } static void sqlite3pager_sqlite3PagerSetCodec( Pager pPager, dxCodec xCodec, dxCodecSizeChng xCodecSizeChng, dxCodecFree xCodecFree, codec_ctx pCodec ) { sqlite3PagerSetCodec( pPager, xCodec, xCodecSizeChng, xCodecFree, pCodec ); } /* END CRYPTO */ //static void activate_openssl() { // if(EVP_get_cipherbyname(CIPHER) == null) { // OpenSSL_add_all_algorithms(); // } //} /** * Free and wipe memory * If ptr is not null memory will be freed. * If sz is greater than zero, the memory will be overwritten with zero before it is freed */ static void codec_free( ref byte[] ptr, int sz ) { if ( ptr != null ) { if ( sz > 0 ) Array.Clear( ptr, 0, sz );//memset( ptr, 0, sz ); sqlite3_free( ref ptr ); } } /** * Set the raw password / key data for a cipher context * * returns SQLITE_OK if assignment was successfull * returns SQLITE_NOMEM if an error occured allocating memory * returns SQLITE_ERROR if the key couldn't be set because the pass was null or size was zero */ static int cipher_ctx_set_pass( cipher_ctx ctx, string zKey, int nKey ) { ctx.pass = null; // codec_free( ctx.pass, ctx.pass_sz ); ctx.pass_sz = nKey; if ( !String.IsNullOrEmpty( zKey ) && nKey > 0 ) { //ctx.pass = sqlite3Malloc(nKey); //if(ctx.pass == null) return SQLITE_NOMEM; ctx.pass = zKey;//memcpy(ctx.pass, zKey, nKey); return SQLITE_OK; } return SQLITE_ERROR; } /** * Initialize a new cipher_ctx struct. This function will allocate memory * for the cipher context and for the key * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ static int cipher_ctx_init( ref cipher_ctx iCtx ) { iCtx = new cipher_ctx(); //iCtx = sqlite3Malloc( sizeof( cipher_ctx ) ); //ctx = *iCtx; //if ( ctx == null ) return SQLITE_NOMEM; //memset( ctx, 0, sizeof( cipher_ctx ) ); //ctx.key = sqlite3Malloc( EVP_MAX_KEY_LENGTH ); //if ( ctx.key == null ) return SQLITE_NOMEM; return SQLITE_OK; } /** * free and wipe memory associated with a cipher_ctx */ static void cipher_ctx_free( ref cipher_ctx ictx ) { cipher_ctx ctx = ictx; CODEC_TRACE( "cipher_ctx_free: entered ictx=%d\n", ictx ); ctx.pass = null;//codec_free(ctx.pass, ctx.pass_sz); if ( ctx.key != null ) Array.Clear( ctx.key, 0, ctx.key.Length );//codec_free(ctx.key, ctx.key_sz); if ( ctx.iv != null ) Array.Clear( ctx.iv, 0, ctx.iv.Length ); ictx = new cipher_ctx();// codec_free( ref ctx, sizeof( cipher_ctx ) ); } /** * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a * fully initialized context, you could copy it to write_ctx and all yet data * and pass information across * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ static int cipher_ctx_copy( cipher_ctx target, cipher_ctx source ) { //byte[] key = target.key; CODEC_TRACE( "cipher_ctx_copy: entered target=%d, source=%d\n", target, source ); //codec_free(target.pass, target.pass_sz); source.CopyTo( target );//memcpy(target, source, sizeof(cipher_ctx); //target.key = key; //restore pointer to previously allocated key data //memcpy(target.key, source.key, EVP_MAX_KEY_LENGTH); //target.pass = sqlite3Malloc(source.pass_sz); //if(target.pass == null) return SQLITE_NOMEM; //memcpy(target.pass, source.pass, source.pass_sz); return SQLITE_OK; } /** * Compare one cipher_ctx to another. * * returns 0 if all the parameters (except the derived key data) are the same * returns 1 otherwise */ static int cipher_ctx_cmp( cipher_ctx c1, cipher_ctx c2 ) { CODEC_TRACE( "cipher_ctx_cmp: entered c1=%d c2=%d\n", c1, c2 ); if ( c1.key_sz == c2.key_sz && c1.pass_sz == c2.pass_sz && c1.pass == c2.pass ) return 0; return 1; } /** * Free and wipe memory associated with a cipher_ctx, including the allocated * read_ctx and write_ctx. */ static void codec_ctx_free( ref codec_ctx iCtx ) { codec_ctx ctx = iCtx; CODEC_TRACE( "codec_ctx_free: entered iCtx=%d\n", iCtx ); cipher_ctx_free( ref ctx.read_ctx ); cipher_ctx_free( ref ctx.write_ctx ); iCtx = new codec_ctx();//codec_free(ctx, sizeof(codec_ctx); } /** * Derive an encryption key for a cipher contex key based on the raw password. * * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill * the key space (i.e 64 hex chars for a 256 bit key) then the key data will be used directly. * * Otherwise, a key data will be derived using PBKDF2 * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if the key could't be derived (for instance if pass is null or pass_sz is 0) */ static int codec_key_derive( codec_ctx ctx, cipher_ctx c_ctx ) { CODEC_TRACE( "codec_key_derive: entered c_ctx.pass=%s, c_ctx.pass_sz=%d ctx.iv=%d ctx.iv_sz=%d c_ctx.kdf_iter=%d c_ctx.key_sz=%d\n", c_ctx.pass, c_ctx.pass_sz, c_ctx.iv, c_ctx.iv_sz, c_ctx.key_sz ); if ( c_ctx.pass != null && c_ctx.pass_sz > 0 ) { // if pass is not null if ( ( c_ctx.pass_sz == ( c_ctx.key_sz * 2 ) + 3 ) && c_ctx.pass.StartsWith( "x'", StringComparison.InvariantCultureIgnoreCase ) ) { int n = c_ctx.pass_sz - 3; /* adjust for leading x' and tailing ' */ string z = c_ctx.pass.Substring( 2 );// + 2; /* adjust lead offset of x' */ CODEC_TRACE( "codec_key_derive: deriving key from hex\n" ); c_ctx.key = sqlite3HexToBlob( null, z, n ); } else { CODEC_TRACE( "codec_key_derive: deriving key using AES256\n" ); Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes( c_ctx.pass, c_ctx.iv, 2010 ); c_ctx.key_sz = 32; c_ctx.key = k1.GetBytes( c_ctx.key_sz ); } #if NET_2_0 Aes.BlockSize = 0x80; Aes.FeedbackSize = 8; Aes.KeySize = 0x100; Aes.Mode = CipherMode.CBC; #endif c_ctx.encryptor = Aes.CreateEncryptor( c_ctx.key, c_ctx.iv ); c_ctx.decryptor = Aes.CreateDecryptor( c_ctx.key, c_ctx.iv ); return SQLITE_OK; }; return SQLITE_ERROR; } /* * ctx - codec context * pgno - page number in database * size - size in bytes of input and output buffers * mode - 1 to encrypt, 0 to decrypt * in - pointer to input bytes * out - pouter to output bytes */ static int codec_cipher( cipher_ctx ctx, Pgno pgno, int mode, int size, byte[] bIn, byte[] bOut ) { int iv; int tmp_csz, csz; CODEC_TRACE( "codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size ); /* just copy raw data from in to out when key size is 0 * i.e. during a rekey of a plaintext database */ if ( ctx.key_sz == 0 ) { Array.Copy( bIn, bOut, bIn.Length );//memcpy(out, in, size); return SQLITE_OK; } MemoryStream dataStream = new MemoryStream(); CryptoStream encryptionStream; if ( mode == CIPHER_ENCRYPT ) { encryptionStream = new CryptoStream( dataStream, ctx.encryptor, CryptoStreamMode.Write ); } else { encryptionStream = new CryptoStream( dataStream, ctx.decryptor, CryptoStreamMode.Write ); } encryptionStream.Write( bIn, 0, size ); encryptionStream.FlushFinalBlock(); dataStream.Position = 0; dataStream.Read( bOut, 0, (int)dataStream.Length ); encryptionStream.Close(); dataStream.Close(); return SQLITE_OK; } /** * * when for_ctx == 0 then it will change for read * when for_ctx == 1 then it will change for write * when for_ctx == 2 then it will change for both */ static int codec_set_cipher_name( sqlite3 db, int nDb, string cipher_name, int for_ctx ) { Db pDb = db.aDb[nDb]; CODEC_TRACE( "codec_set_cipher_name: entered db=%d nDb=%d cipher_name=%s for_ctx=%d\n", db, nDb, cipher_name, for_ctx ); if ( pDb.pBt != null ) { codec_ctx ctx = null; cipher_ctx c_ctx; sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); c_ctx = for_ctx != 0 ? ctx.write_ctx : ctx.read_ctx; c_ctx.derive_key = true; if ( for_ctx == 2 ) cipher_ctx_copy( for_ctx != 0 ? ctx.read_ctx : ctx.write_ctx, c_ctx ); return SQLITE_OK; } return SQLITE_ERROR; } static int codec_set_pass_key( sqlite3 db, int nDb, string zKey, int nKey, int for_ctx ) { Db pDb = db.aDb[nDb]; CODEC_TRACE( "codec_set_pass_key: entered db=%d nDb=%d cipher_name=%s nKey=%d for_ctx=%d\n", db, nDb, zKey, nKey, for_ctx ); if ( pDb.pBt != null ) { codec_ctx ctx = null; cipher_ctx c_ctx; sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); c_ctx = for_ctx != 0 ? ctx.write_ctx : ctx.read_ctx; cipher_ctx_set_pass( c_ctx, zKey, nKey ); c_ctx.derive_key = true; if ( for_ctx == 2 ) cipher_ctx_copy( for_ctx != 0 ? ctx.read_ctx : ctx.write_ctx, c_ctx ); return SQLITE_OK; } return SQLITE_ERROR; } /* * sqlite3Codec can be called in multiple modes. * encrypt mode - expected to return a pointer to the * encrypted data without altering pData. * decrypt mode - expected to return a pointer to pData, with * the data decrypted in the input buffer */ static byte[] sqlite3Codec( codec_ctx iCtx, byte[] data, Pgno pgno, int mode ) { codec_ctx ctx = (codec_ctx)iCtx; int pg_sz = sqlite3BtreeGetPageSize( ctx.pBt ); int offset = 0; byte[] pData = data; CODEC_TRACE( "sqlite3Codec: entered pgno=%d, mode=%d, ctx.mode_rekey=%d, pg_sz=%d\n", pgno, mode, ctx.mode_rekey, pg_sz ); /* derive key on first use if necessary */ if ( ctx.read_ctx.derive_key ) { codec_key_derive( ctx, ctx.read_ctx ); ctx.read_ctx.derive_key = false; } if ( ctx.write_ctx.derive_key ) { if ( cipher_ctx_cmp( ctx.write_ctx, ctx.read_ctx ) == 0 ) { cipher_ctx_copy( ctx.write_ctx, ctx.read_ctx ); // the relevant parameters are the same, just copy read key } else { codec_key_derive( ctx, ctx.write_ctx ); ctx.write_ctx.derive_key = false; } } CODEC_TRACE( "sqlite3Codec: switch mode=%d offset=%d\n", mode, offset ); if ( ctx.buffer.Length != pg_sz ) ctx.buffer = sqlite3MemMalloc( pg_sz ); switch ( mode ) { case SQLITE_DECRYPT: codec_cipher( ctx.read_ctx, pgno, CIPHER_DECRYPT, pg_sz, pData, ctx.buffer ); if ( pgno == 1 ) Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.buffer, 0, FILE_HEADER_SZ );// memcpy( ctx.buffer, SQLITE_FILE_HEADER, FILE_HEADER_SZ ); /* copy file header to the first 16 bytes of the page */ Buffer.BlockCopy( ctx.buffer, 0, pData, 0, pg_sz ); //memcpy( pData, ctx.buffer, pg_sz ); /* copy buffer data back to pData and return */ return pData; case SQLITE_ENCRYPT_WRITE_CTX: /* encrypt */ if ( pgno == 1 ) Buffer.BlockCopy( ctx.write_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */ codec_cipher( ctx.write_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer ); return ctx.buffer; /* return persistent buffer data, pData remains intact */ case SQLITE_ENCRYPT_READ_CTX: if ( pgno == 1 ) Buffer.BlockCopy( ctx.read_ctx.iv, 0, ctx.buffer, 0, FILE_HEADER_SZ );//memcpy( ctx.buffer, ctx.iv, FILE_HEADER_SZ ); /* copy salt to output buffer */ codec_cipher( ctx.read_ctx, pgno, CIPHER_ENCRYPT, pg_sz, pData, ctx.buffer ); return ctx.buffer; /* return persistent buffer data, pData remains intact */ default: return pData; } } static int sqlite3CodecAttach( sqlite3 db, int nDb, string zKey, int nKey ) { Db pDb = db.aDb[nDb]; CODEC_TRACE( "sqlite3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, zKey, nKey ); //activate_openssl(); if ( zKey != null && pDb.pBt != null ) { Aes.KeySize = 256; #if NO_SQLITE_SILVERLIGHT // #if !SQLITE_SILVERLIGHT Aes.Padding = PaddingMode.None; #endif codec_ctx ctx; int rc; Pager pPager = pDb.pBt.pBt.pPager; sqlite3_file fd; ctx = new codec_ctx();//sqlite3Malloc(sizeof(codec_ctx); //if(ctx == null) return SQLITE_NOMEM; //memset(ctx, 0, sizeof(codec_ctx); /* initialize all pointers and values to 0 */ ctx.pBt = pDb.pBt; /* assign pointer to database btree structure */ if ( ( rc = cipher_ctx_init( ref ctx.read_ctx ) ) != SQLITE_OK ) return rc; if ( ( rc = cipher_ctx_init( ref ctx.write_ctx ) ) != SQLITE_OK ) return rc; /* pre-allocate a page buffer of PageSize bytes. This will be used as a persistent buffer for encryption and decryption operations to avoid overhead of multiple memory allocations*/ ctx.buffer = sqlite3MemMalloc( sqlite3BtreeGetPageSize( ctx.pBt ) );//sqlite3Malloc(sqlite3BtreeGetPageSize(ctx.pBt); //if(ctx.buffer == null) return SQLITE_NOMEM; /* allocate space for salt data. Then read the first 16 bytes header as the salt for the key derivation */ ctx.read_ctx.iv_sz = FILE_HEADER_SZ; ctx.read_ctx.iv = new byte[ctx.read_ctx.iv_sz];//sqlite3Malloc( ctx.iv_sz ); Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.read_ctx.iv, 0, FILE_HEADER_SZ ); sqlite3pager_sqlite3PagerSetCodec( sqlite3BtreePager( pDb.pBt ), sqlite3Codec, null, sqlite3FreeCodecArg, ctx ); codec_set_cipher_name( db, nDb, CIPHER, 0 ); codec_set_pass_key( db, nDb, zKey, nKey, 0 ); cipher_ctx_copy( ctx.write_ctx, ctx.read_ctx ); //sqlite3BtreeSetPageSize( ctx.pBt, sqlite3BtreeGetPageSize( ctx.pBt ), MAX_IV_LENGTH, 0 ); } return SQLITE_OK; } static void sqlite3FreeCodecArg( ref codec_ctx pCodecArg ) { if ( pCodecArg == null ) return; codec_ctx_free( ref pCodecArg ); // wipe and free allocated memory for the context } static void sqlite3_activate_see( string zPassword ) { /* do nothing, security enhancements are always active */ } static public int sqlite3_key( sqlite3 db, string pKey, int nKey ) { CODEC_TRACE( "sqlite3_key: entered db=%d pKey=%s nKey=%d\n", db, pKey, nKey ); /* attach key if db and pKey are not null and nKey is > 0 */ if ( db != null && pKey != null ) { sqlite3CodecAttach( db, 0, pKey, nKey ); // operate only on the main db // // If we are reopening an existing database, redo the header information setup // BtShared pBt = db.aDb[0].pBt.pBt; byte[] zDbHeader = sqlite3MemMalloc( (int)pBt.pageSize );// pBt.pPager.pCodec.buffer; sqlite3PagerReadFileheader( pBt.pPager, zDbHeader.Length, zDbHeader ); if ( sqlite3Get4byte( zDbHeader ) > 0 ) // Existing Database, need to reset some values { CODEC2( pBt.pPager, zDbHeader, 2, SQLITE_DECRYPT, ref zDbHeader ); byte nReserve = zDbHeader[20]; pBt.pageSize = (uint)( ( zDbHeader[16] << 8 ) | ( zDbHeader[17] << 16 ) ); if ( pBt.pageSize < 512 || pBt.pageSize > SQLITE_MAX_PAGE_SIZE || ( ( pBt.pageSize - 1 ) & pBt.pageSize ) != 0 ) pBt.pageSize = 0; pBt.pageSizeFixed = true; #if !SQLITE_OMIT_AUTOVACUUM pBt.autoVacuum = sqlite3Get4byte( zDbHeader, 36 + 4 * 4 ) != 0; pBt.incrVacuum = sqlite3Get4byte( zDbHeader, 36 + 7 * 4 ) != 0; #endif sqlite3PagerSetPagesize( pBt.pPager, ref pBt.pageSize, nReserve ); pBt.usableSize = (u16)( pBt.pageSize - nReserve ); } return SQLITE_OK; } return SQLITE_ERROR; } /* sqlite3_rekey ** Given a database, this will reencrypt the database using a new key. ** There are two possible modes of operation. The first is rekeying ** an existing database that was not previously encrypted. The second ** is to change the key on an existing database. ** ** The proposed logic for this function follows: ** 1. Determine if there is already a key present ** 2. If there is NOT already a key present, create one and attach a codec (key would be null) ** 3. Initialize a ctx.rekey parameter of the codec ** ** Note: this will require modifications to the sqlite3Codec to support rekey ** */ static int sqlite3_rekey( sqlite3 db, string pKey, int nKey ) { CODEC_TRACE( "sqlite3_rekey: entered db=%d pKey=%s, nKey=%d\n", db, pKey, nKey ); //activate_openssl(); if ( db != null && pKey != null ) { Db pDb = db.aDb[0]; CODEC_TRACE( "sqlite3_rekey: database pDb=%d\n", pDb ); if ( pDb.pBt != null ) { codec_ctx ctx = null; int rc; Pgno page_count = 0; Pgno pgno; PgHdr page = null; Pager pPager = pDb.pBt.pBt.pPager; sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); if ( ctx == null ) { CODEC_TRACE( "sqlite3_rekey: no codec attached to db, attaching now\n" ); /* there was no codec attached to this database,so attach one now with a null password */ sqlite3CodecAttach( db, 0, pKey, nKey ); sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); /* prepare this setup as if it had already been initialized */ Buffer.BlockCopy( Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER ), 0, ctx.read_ctx.iv, 0, FILE_HEADER_SZ ); ctx.read_ctx.key_sz = ctx.read_ctx.iv_sz = ctx.read_ctx.pass_sz = 0; } //if ( ctx.read_ctx.iv_sz != ctx.write_ctx.iv_sz ) //{ // string error = ""; // CODEC_TRACE( "sqlite3_rekey: updating page size for iv_sz change from %d to %d\n", ctx.read_ctx.iv_sz, ctx.write_ctx.iv_sz ); // db.nextPagesize = sqlite3BtreeGetPageSize( pDb.pBt ); // pDb.pBt.pBt.pageSizeFixed = false; /* required for sqlite3BtreeSetPageSize to modify pagesize setting */ // sqlite3BtreeSetPageSize( pDb.pBt, db.nextPagesize, MAX_IV_LENGTH, 0 ); // sqlite3RunVacuum( ref error, db ); //} codec_set_pass_key( db, 0, pKey, nKey, 1 ); ctx.mode_rekey = 1; /* do stuff here to rewrite the database ** 1. Create a transaction on the database ** 2. Iterate through each page, reading it and then writing it. ** 3. If that goes ok then commit and put ctx.rekey into ctx.key ** note: don't deallocate rekey since it may be used in a subsequent iteration */ rc = sqlite3BtreeBeginTrans( pDb.pBt, 1 ); /* begin write transaction */ sqlite3PagerPagecount( pPager, out page_count ); for ( pgno = 1; rc == SQLITE_OK && pgno <= page_count; pgno++ ) { /* pgno's start at 1 see pager.c:pagerAcquire */ if ( 0 == sqlite3pager_is_mj_pgno( pPager, pgno ) ) { /* skip this page (see pager.c:pagerAcquire for reasoning) */ rc = sqlite3PagerGet( pPager, pgno, ref page ); if ( rc == SQLITE_OK ) { /* write page see pager_incr_changecounter for example */ rc = sqlite3PagerWrite( page ); //printf("sqlite3PagerWrite(%d)\n", pgno); if ( rc == SQLITE_OK ) { sqlite3PagerUnref( page ); } } } } /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */ if ( rc == SQLITE_OK ) { CODEC_TRACE( "sqlite3_rekey: committing\n" ); db.nextPagesize = sqlite3BtreeGetPageSize( pDb.pBt ); rc = sqlite3BtreeCommit( pDb.pBt ); if ( ctx != null ) cipher_ctx_copy( ctx.read_ctx, ctx.write_ctx ); } else { CODEC_TRACE( "sqlite3_rekey: rollback\n" ); sqlite3BtreeRollback( pDb.pBt ); } ctx.mode_rekey = 0; } return SQLITE_OK; } return SQLITE_ERROR; } static void sqlite3CodecGetKey( sqlite3 db, int nDb, out string zKey, out int nKey ) { Db pDb = db.aDb[nDb]; CODEC_TRACE( "sqlite3CodecGetKey: entered db=%d, nDb=%d\n", db, nDb ); if ( pDb.pBt != null ) { codec_ctx ctx = null; sqlite3pager_get_codec( pDb.pBt.pBt.pPager, ref ctx ); if ( ctx != null ) { /* if the codec has an attached codec_context user the raw key data */ zKey = ctx.read_ctx.pass; nKey = ctx.read_ctx.pass_sz; return; } } zKey = null; nKey = 0; } /* END CRYPTO */ #endif const int SQLITE_ENCRYPT_WRITE_CTX = 6; /* Encode page */ const int SQLITE_ENCRYPT_READ_CTX = 7; /* Encode page */ const int SQLITE_DECRYPT = 3; /* Decode page */ } }
// Copyright 2011 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. namespace Microsoft.Data.OData.Atom { #region Namespaces using System; using System.Diagnostics; using o = Microsoft.Data.OData; #endregion Namespaces /// <summary> /// Base class for all OData ATOM Metadata serializers. /// </summary> internal abstract class ODataAtomMetadataSerializer : ODataAtomSerializer { /// <summary> /// Constructor. /// </summary> /// <param name="atomOutputContext">The output context to write to.</param> internal ODataAtomMetadataSerializer(ODataAtomOutputContext atomOutputContext) : base(atomOutputContext) { DebugUtils.CheckNoExternalCallers(); } /// <summary> /// Writes an Xml element with the specified primitive value as content. /// </summary> /// <param name="prefix">The prefix for the element's namespace.</param> /// <param name="localName">The local name of the element.</param> /// <param name="ns">The namespace of the element.</param> /// <param name="textConstruct">The <see cref="AtomTextConstruct"/> value to be used as element content.</param> internal void WriteTextConstruct(string prefix, string localName, string ns, AtomTextConstruct textConstruct) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(prefix != null, "prefix != null"); Debug.Assert(!string.IsNullOrEmpty(localName), "!string.IsNullOrEmpty(localName)"); Debug.Assert(!string.IsNullOrEmpty(ns), "!string.IsNullOrEmpty(ns)"); this.XmlWriter.WriteStartElement(prefix, localName, ns); if (textConstruct != null) { AtomTextConstructKind textKind = textConstruct.Kind; this.XmlWriter.WriteAttributeString(AtomConstants.AtomTypeAttributeName, AtomValueUtils.ToString(textConstruct.Kind)); string textValue = textConstruct.Text; if (textValue == null) { textValue = String.Empty; } if (textKind == AtomTextConstructKind.Xhtml) { ODataAtomWriterUtils.WriteRaw(this.XmlWriter, textValue); } else { ODataAtomWriterUtils.WriteString(this.XmlWriter, textValue); } } this.XmlWriter.WriteEndElement(); } /// <summary> /// Writes the 'atom:category' element given category metadata. /// </summary> /// <param name="category">The category information to write.</param> internal void WriteCategory(AtomCategoryMetadata category) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(category != null, "Category must not be null."); this.WriteCategory(AtomConstants.AtomNamespacePrefix, category.Term, category.Scheme, category.Label); } /// <summary> /// Writes the 'atom:category' element with the specified attributes. /// </summary> /// <param name="atomPrefix">The prefix to use for the 'category' element.</param> /// <param name="term">The value for the 'term' attribute (required).</param> /// <param name="scheme">The value for the 'scheme' attribute (optional).</param> /// <param name="label">The value for the 'label' attribute (optional).</param> internal void WriteCategory(string atomPrefix, string term, string scheme, string label) { DebugUtils.CheckNoExternalCallers(); this.XmlWriter.WriteStartElement( atomPrefix, AtomConstants.AtomCategoryElementName, AtomConstants.AtomNamespace); if (term == null) { throw new ODataException(o.Strings.ODataAtomWriterMetadataUtils_CategoryMustSpecifyTerm); } this.XmlWriter.WriteAttributeString( AtomConstants.AtomCategoryTermAttributeName, term); if (scheme != null) { this.XmlWriter.WriteAttributeString(AtomConstants.AtomCategorySchemeAttributeName, scheme); } if (label != null) { this.XmlWriter.WriteAttributeString(AtomConstants.AtomCategoryLabelAttributeName, label); } this.XmlWriter.WriteEndElement(); } /// <summary> /// Write an empty author element that has the required name element /// </summary> internal void WriteEmptyAuthor() { DebugUtils.CheckNoExternalCallers(); // <atom:author> this.XmlWriter.WriteStartElement(AtomConstants.AtomNamespacePrefix, AtomConstants.AtomAuthorElementName, AtomConstants.AtomNamespace); // <atom:Name></atom:Name> this.WriteEmptyElement( AtomConstants.AtomNamespacePrefix, AtomConstants.AtomAuthorNameElementName, AtomConstants.AtomNamespace); // </atom:author> this.XmlWriter.WriteEndElement(); } /// <summary> /// Writes the specified start/end tags and the specified person metadata as content /// </summary> /// <param name="personMetadata">The person metadata to write.</param> internal void WritePersonMetadata(AtomPersonMetadata personMetadata) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(personMetadata != null, "Person metadata must not be null."); // <atom:name>name of person</atom:name> // NOTE: write an empty element if no name is specified because the element is required. this.WriteElementWithTextContent( AtomConstants.AtomNamespacePrefix, AtomConstants.AtomPersonNameElementName, AtomConstants.AtomNamespace, personMetadata.Name); string uriString = personMetadata.UriFromEpm; if (uriString != null) { Debug.Assert( personMetadata.Uri == null, "If the internal UriFromEpm was used, then the Uri property must be left null. The merge between custom and EPM is probably wrong."); } else { Uri uri = personMetadata.Uri; if (uri != null) { uriString = this.UriToUrlAttributeValue(uri); } } if (uriString != null) { this.WriteElementWithTextContent( AtomConstants.AtomNamespacePrefix, AtomConstants.AtomPersonUriElementName, AtomConstants.AtomNamespace, uriString); } string email = personMetadata.Email; if (email != null) { this.WriteElementWithTextContent( AtomConstants.AtomNamespacePrefix, AtomConstants.AtomPersonEmailElementName, AtomConstants.AtomNamespace, email); } } /// <summary> /// Write the metadata of a link in ATOM format /// </summary> /// <param name="linkMetadata">The link metadata to write.</param> /// <param name="etag">The (optional) ETag for a link.</param> internal void WriteAtomLink(AtomLinkMetadata linkMetadata, string etag) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(linkMetadata != null, "Link metadata must not be null."); // <atom:link ... this.XmlWriter.WriteStartElement( AtomConstants.AtomNamespacePrefix, AtomConstants.AtomLinkElementName, AtomConstants.AtomNamespace); // write the attributes of the link this.WriteAtomLinkAttributes(linkMetadata, etag); // </atom:link> this.XmlWriter.WriteEndElement(); } /// <summary> /// Write the metadata of a link in ATOM format /// </summary> /// <param name="linkMetadata">The link metadata to write.</param> /// <param name="etag">The (optional) ETag for a link.</param> internal void WriteAtomLinkAttributes(AtomLinkMetadata linkMetadata, string etag) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(linkMetadata != null, "Link metadata must not be null."); string linkHref = linkMetadata.Href == null ? null : this.UriToUrlAttributeValue(linkMetadata.Href); this.WriteAtomLinkMetadataAttributes(linkMetadata.Relation, linkHref, linkMetadata.HrefLang, linkMetadata.Title, linkMetadata.MediaType, linkMetadata.Length); if (etag != null) { ODataAtomWriterUtils.WriteETag(this.XmlWriter, etag); } } /// <summary> /// Write the metadata attributes of a link in ATOM format /// </summary> /// <param name="relation">The value for the 'rel' attribute.</param> /// <param name="href">The value for the 'href' attribute.</param> /// <param name="hrefLang">The value for the 'hreflang' attribute.</param> /// <param name="title">The value for the 'title' attribute.</param> /// <param name="mediaType">The value for the 'type' attribute.</param> /// <param name="length">The value for the 'length' attribute.</param> private void WriteAtomLinkMetadataAttributes(string relation, string href, string hrefLang, string title, string mediaType, int? length) { // rel="..." if (relation != null) { this.XmlWriter.WriteAttributeString(AtomConstants.AtomLinkRelationAttributeName, relation); } // type="..." if (mediaType != null) { this.XmlWriter.WriteAttributeString(AtomConstants.AtomLinkTypeAttributeName, mediaType); } // title="..." if (title != null) { this.XmlWriter.WriteAttributeString(AtomConstants.AtomLinkTitleAttributeName, title); } // href="..." if (href == null) { throw new ODataException(o.Strings.ODataAtomWriterMetadataUtils_LinkMustSpecifyHref); } this.XmlWriter.WriteAttributeString(AtomConstants.AtomHRefAttributeName, href); // hreflang="..." if (hrefLang != null) { this.XmlWriter.WriteAttributeString(AtomConstants.AtomLinkHrefLangAttributeName, hrefLang); } // length="..." if (length.HasValue) { this.XmlWriter.WriteAttributeString(AtomConstants.AtomLinkLengthAttributeName, ODataAtomConvert.ToString(length.Value)); } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type CalendarGroupRequest. /// </summary> public partial class CalendarGroupRequest : BaseRequest, ICalendarGroupRequest { /// <summary> /// Constructs a new CalendarGroupRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public CalendarGroupRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified CalendarGroup using POST. /// </summary> /// <param name="calendarGroupToCreate">The CalendarGroup to create.</param> /// <returns>The created CalendarGroup.</returns> public System.Threading.Tasks.Task<CalendarGroup> CreateAsync(CalendarGroup calendarGroupToCreate) { return this.CreateAsync(calendarGroupToCreate, CancellationToken.None); } /// <summary> /// Creates the specified CalendarGroup using POST. /// </summary> /// <param name="calendarGroupToCreate">The CalendarGroup to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created CalendarGroup.</returns> public async System.Threading.Tasks.Task<CalendarGroup> CreateAsync(CalendarGroup calendarGroupToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<CalendarGroup>(calendarGroupToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified CalendarGroup. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified CalendarGroup. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<CalendarGroup>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified CalendarGroup. /// </summary> /// <returns>The CalendarGroup.</returns> public System.Threading.Tasks.Task<CalendarGroup> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified CalendarGroup. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The CalendarGroup.</returns> public async System.Threading.Tasks.Task<CalendarGroup> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<CalendarGroup>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified CalendarGroup using PATCH. /// </summary> /// <param name="calendarGroupToUpdate">The CalendarGroup to update.</param> /// <returns>The updated CalendarGroup.</returns> public System.Threading.Tasks.Task<CalendarGroup> UpdateAsync(CalendarGroup calendarGroupToUpdate) { return this.UpdateAsync(calendarGroupToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified CalendarGroup using PATCH. /// </summary> /// <param name="calendarGroupToUpdate">The CalendarGroup to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated CalendarGroup.</returns> public async System.Threading.Tasks.Task<CalendarGroup> UpdateAsync(CalendarGroup calendarGroupToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<CalendarGroup>(calendarGroupToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public ICalendarGroupRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public ICalendarGroupRequest Expand(Expression<Func<CalendarGroup, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public ICalendarGroupRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public ICalendarGroupRequest Select(Expression<Func<CalendarGroup, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="calendarGroupToInitialize">The <see cref="CalendarGroup"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(CalendarGroup calendarGroupToInitialize) { if (calendarGroupToInitialize != null && calendarGroupToInitialize.AdditionalData != null) { if (calendarGroupToInitialize.Calendars != null && calendarGroupToInitialize.Calendars.CurrentPage != null) { calendarGroupToInitialize.Calendars.AdditionalData = calendarGroupToInitialize.AdditionalData; object nextPageLink; calendarGroupToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { calendarGroupToInitialize.Calendars.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Microsoft.VisualStudio.Text.Differencing; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public abstract class AbstractUserDiagnosticTest : AbstractCodeActionOrUserDiagnosticTest { internal abstract Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync( TestWorkspace workspace, string fixAllActionEquivalenceKey, object fixProviderData); internal abstract Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(TestWorkspace workspace, object fixProviderData); protected override async Task<IList<CodeAction>> GetCodeActionsWorkerAsync( TestWorkspace workspace, string fixAllActionEquivalenceKey, object fixProviderData) { var diagnostics = await GetDiagnosticAndFixAsync(workspace, fixAllActionEquivalenceKey, fixProviderData); return diagnostics?.Item2?.Fixes.Select(f => f.Action).ToList(); } internal async Task<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixAsync( TestWorkspace workspace, string fixAllActionEquivalenceKey = null, object fixProviderData = null) { return (await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceKey, fixProviderData)).FirstOrDefault(); } protected Document GetDocumentAndSelectSpan(TestWorkspace workspace, out TextSpan span) { var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any()); span = hostDocument.SelectedSpans.Single(); return workspace.CurrentSolution.GetDocument(hostDocument.Id); } protected bool TryGetDocumentAndSelectSpan(TestWorkspace workspace, out Document document, out TextSpan span) { var hostDocument = workspace.Documents.FirstOrDefault(d => d.SelectedSpans.Any()); if (hostDocument == null) { document = null; span = default(TextSpan); return false; } span = hostDocument.SelectedSpans.Single(); document = workspace.CurrentSolution.GetDocument(hostDocument.Id); return true; } protected Document GetDocumentAndAnnotatedSpan(TestWorkspace workspace, out string annotation, out TextSpan span) { var hostDocument = workspace.Documents.Single(d => d.AnnotatedSpans.Any()); var annotatedSpan = hostDocument.AnnotatedSpans.Single(); annotation = annotatedSpan.Key; span = annotatedSpan.Value.Single(); return workspace.CurrentSolution.GetDocument(hostDocument.Id); } protected FixAllScope? GetFixAllScope(string annotation) { if (annotation == null) { return null; } switch (annotation) { case "FixAllInDocument": return FixAllScope.Document; case "FixAllInProject": return FixAllScope.Project; case "FixAllInSolution": return FixAllScope.Solution; case "FixAllInSelection": return FixAllScope.Custom; } throw new InvalidProgramException("Incorrect FixAll annotation in test"); } internal async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync( IEnumerable<Diagnostic> diagnostics, DiagnosticAnalyzer provider, CodeFixProvider fixer, TestDiagnosticAnalyzerDriver testDriver, Document document, TextSpan span, string annotation, string fixAllActionId) { if (diagnostics.IsEmpty()) { return SpecializedCollections.EmptyEnumerable<Tuple<Diagnostic, CodeFixCollection>>(); } FixAllScope? scope = GetFixAllScope(annotation); return await GetDiagnosticAndFixesAsync(diagnostics, provider, fixer, testDriver, document, span, scope, fixAllActionId); } private async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync( IEnumerable<Diagnostic> diagnostics, DiagnosticAnalyzer provider, CodeFixProvider fixer, TestDiagnosticAnalyzerDriver testDriver, Document document, TextSpan span, FixAllScope? scope, string fixAllActionId) { Assert.NotEmpty(diagnostics); var result = new List<Tuple<Diagnostic, CodeFixCollection>>(); if (scope == null) { // Simple code fix. foreach (var diagnostic in diagnostics) { var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, diagnostic, (a, d) => fixes.Add(new CodeFix(document.Project, a, d)), CancellationToken.None); await fixer.RegisterCodeFixesAsync(context); if (fixes.Any()) { var codeFix = new CodeFixCollection(fixer, diagnostic.Location.SourceSpan, fixes); result.Add(Tuple.Create(diagnostic, codeFix)); } } } else { // Fix all fix. var fixAllProvider = fixer.GetFixAllProvider(); Assert.NotNull(fixAllProvider); var fixAllContext = GetFixAllContext(diagnostics, provider, fixer, testDriver, document, scope.Value, fixAllActionId); var fixAllFix = await fixAllProvider.GetFixAsync(fixAllContext); if (fixAllFix != null) { // Same fix applies to each diagnostic in scope. foreach (var diagnostic in diagnostics) { var diagnosticSpan = diagnostic.Location.IsInSource ? diagnostic.Location.SourceSpan : default(TextSpan); var codeFix = new CodeFixCollection(fixAllProvider, diagnosticSpan, ImmutableArray.Create(new CodeFix(document.Project, fixAllFix, diagnostic))); result.Add(Tuple.Create(diagnostic, codeFix)); } } } return result; } private static FixAllContext GetFixAllContext( IEnumerable<Diagnostic> diagnostics, DiagnosticAnalyzer provider, CodeFixProvider fixer, TestDiagnosticAnalyzerDriver testDriver, Document document, FixAllScope scope, string fixAllActionId) { Assert.NotEmpty(diagnostics); if (scope == FixAllScope.Custom) { // Bulk fixing diagnostics in selected scope. var diagnosticsToFix = ImmutableDictionary.CreateRange(SpecializedCollections.SingletonEnumerable(KeyValuePair.Create(document, diagnostics.ToImmutableArray()))); return FixMultipleContext.Create(diagnosticsToFix, fixer, fixAllActionId, CancellationToken.None); } var diagnostic = diagnostics.First(); Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync = async (d, diagIds, c) => { var root = await d.GetSyntaxRootAsync(); var diags = await testDriver.GetDocumentDiagnosticsAsync(provider, d, root.FullSpan); diags = diags.Where(diag => diagIds.Contains(diag.Id)); return diags; }; Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync = async (p, includeAllDocumentDiagnostics, diagIds, c) => { var diags = includeAllDocumentDiagnostics ? await testDriver.GetAllDiagnosticsAsync(provider, p) : await testDriver.GetProjectDiagnosticsAsync(provider, p); diags = diags.Where(diag => diagIds.Contains(diag.Id)); return diags; }; var diagnosticIds = ImmutableHashSet.Create(diagnostic.Id); var fixAllDiagnosticProvider = new FixAllCodeActionContext.FixAllDiagnosticProvider(diagnosticIds, getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync); return diagnostic.Location.IsInSource ? new FixAllContext(document, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None) : new FixAllContext(document.Project, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None); } protected async Task TestEquivalenceKeyAsync(string initialMarkup, string equivalenceKey) { using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions: null, compilationOptions: null)) { var diagnosticAndFix = await GetDiagnosticAndFixAsync(workspace); Assert.Equal(equivalenceKey, diagnosticAndFix.Item2.Fixes.ElementAt(index: 0).Action.EquivalenceKey); } } protected async Task TestActionCountInAllFixesAsync( string initialMarkup, int count, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, object fixProviderData = null) { using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions)) { var diagnosticAndFix = await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceKey: null, fixProviderData: fixProviderData); var diagnosticCount = diagnosticAndFix.Select(x => x.Item2.Fixes.Count()).Sum(); Assert.Equal(count, diagnosticCount); } } protected async Task TestSpansAsync( string initialMarkup, string expectedMarkup, int index = 0, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, string diagnosticId = null, string fixAllActionEquivalenceId = null, object fixProviderData = null) { IList<TextSpan> spansList; string unused; MarkupTestFile.GetSpans(expectedMarkup, out unused, out spansList); var expectedTextSpans = spansList.ToSet(); using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions)) { ISet<TextSpan> actualTextSpans; if (diagnosticId == null) { var diagnosticsAndFixes = await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceId, fixProviderData); var diagnostics = diagnosticsAndFixes.Select(t => t.Item1); actualTextSpans = diagnostics.Select(d => d.Location.SourceSpan).ToSet(); } else { var diagnostics = await GetDiagnosticsAsync(workspace, fixProviderData); actualTextSpans = diagnostics.Where(d => d.Id == diagnosticId).Select(d => d.Location.SourceSpan).ToSet(); } Assert.True(expectedTextSpans.SetEquals(actualTextSpans)); } } protected async Task TestAddDocument( string initialMarkup, string expectedMarkup, IList<string> expectedContainers, string expectedDocumentName, int index = 0, bool compareTokens = true, bool isLine = true) { await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, null, null, compareTokens, isLine); await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, GetScriptOptions(), null, compareTokens, isLine); } private async Task TestAddDocument( string initialMarkup, string expectedMarkup, int index, IList<string> expectedContainers, string expectedDocumentName, ParseOptions parseOptions, CompilationOptions compilationOptions, bool compareTokens, bool isLine) { using (var workspace = isLine ? await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions) : await TestWorkspace.CreateAsync(initialMarkup)) { var codeActions = await GetCodeActionsAsync(workspace, fixAllActionEquivalenceKey: null); await TestAddDocument(workspace, expectedMarkup, index, expectedContainers, expectedDocumentName, codeActions, compareTokens); } } private async Task TestAddDocument( TestWorkspace workspace, string expectedMarkup, int index, IList<string> expectedFolders, string expectedDocumentName, IList<CodeAction> actions, bool compareTokens) { var operations = await VerifyInputsAndGetOperationsAsync(index, actions); await TestAddDocument( workspace, expectedMarkup, operations, hasProjectChange: false, modifiedProjectId: null, expectedFolders: expectedFolders, expectedDocumentName: expectedDocumentName, compareTokens: compareTokens); } private async Task<Tuple<Solution, Solution>> TestAddDocument( TestWorkspace workspace, string expected, IEnumerable<CodeActionOperation> operations, bool hasProjectChange, ProjectId modifiedProjectId, IList<string> expectedFolders, string expectedDocumentName, bool compareTokens) { var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations); var oldSolution = appliedChanges.Item1; var newSolution = appliedChanges.Item2; Document addedDocument = null; if (!hasProjectChange) { addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution); } else { Assert.NotNull(modifiedProjectId); addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName); } Assert.NotNull(addedDocument); AssertEx.Equal(expectedFolders, addedDocument.Folders); Assert.Equal(expectedDocumentName, addedDocument.Name); if (compareTokens) { TokenUtilities.AssertTokensEqual( expected, (await addedDocument.GetTextAsync()).ToString(), GetLanguage()); } else { Assert.Equal(expected, (await addedDocument.GetTextAsync()).ToString()); } var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); if (!hasProjectChange) { // If there is just one document change then we expect the preview to be a WpfTextView var content = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0]; var diffView = content as IWpfDifferenceViewer; Assert.NotNull(diffView); diffView.Close(); } else { // If there are more changes than just the document we need to browse all the changes and get the document change var contents = editHandler.GetPreviews(workspace, operations, CancellationToken.None); bool hasPreview = false; var previews = await contents.GetPreviewsAsync(); if (previews != null) { foreach (var preview in previews) { if (preview != null) { var diffView = preview as IWpfDifferenceViewer; if (diffView != null) { hasPreview = true; diffView.Close(); break; } } } } Assert.True(hasPreview); } return Tuple.Create(oldSolution, newSolution); } internal async Task TestWithMockedGenerateTypeDialog( string initial, string languageName, string typeName, string expected = null, bool isLine = true, bool isMissing = false, Accessibility accessibility = Accessibility.NotApplicable, TypeKind typeKind = TypeKind.Class, string projectName = null, bool isNewFile = false, string existingFilename = null, IList<string> newFileFolderContainers = null, string fullFilePath = null, string newFileName = null, string assertClassName = null, bool checkIfUsingsIncluded = false, bool checkIfUsingsNotIncluded = false, string expectedTextWithUsings = null, string defaultNamespace = "", bool areFoldersValidIdentifiers = true, GenerateTypeDialogOptions assertGenerateTypeDialogOptions = null, IList<TypeKindOptions> assertTypeKindPresent = null, IList<TypeKindOptions> assertTypeKindAbsent = null, bool isCancelled = false) { using (var testState = await GenerateTypeTestState.CreateAsync(initial, isLine, projectName, typeName, existingFilename, languageName)) { // Initialize the viewModel values testState.TestGenerateTypeOptionsService.SetGenerateTypeOptions( accessibility: accessibility, typeKind: typeKind, typeName: testState.TypeName, project: testState.ProjectToBeModified, isNewFile: isNewFile, newFileName: newFileName, folders: newFileFolderContainers, fullFilePath: fullFilePath, existingDocument: testState.ExistingDocument, areFoldersValidIdentifiers: areFoldersValidIdentifiers, isCancelled: isCancelled); testState.TestProjectManagementService.SetDefaultNamespace( defaultNamespace: defaultNamespace); var diagnosticsAndFixes = await GetDiagnosticAndFixesAsync(testState.Workspace, fixAllActionEquivalenceKey: null, fixProviderData: null); var generateTypeDiagFixes = diagnosticsAndFixes.SingleOrDefault(df => GenerateTypeTestState.FixIds.Contains(df.Item1.Id)); if (isMissing) { Assert.Null(generateTypeDiagFixes); return; } var fixes = generateTypeDiagFixes.Item2.Fixes; Assert.NotNull(fixes); var fixActions = MassageActions(fixes.Select(f => f.Action).ToList()); Assert.NotNull(fixActions); // Since the dialog option is always fed as the last CodeAction var index = fixActions.Count() - 1; var action = fixActions.ElementAt(index); Assert.Equal(action.Title, FeaturesResources.GenerateNewType); var operations = await action.GetOperationsAsync(CancellationToken.None); Tuple<Solution, Solution> oldSolutionAndNewSolution = null; if (!isNewFile) { oldSolutionAndNewSolution = await TestOperationsAsync( testState.Workspace, expected, operations, conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false, expectedChangedDocumentId: testState.ExistingDocument.Id); } else { oldSolutionAndNewSolution = await TestAddDocument( testState.Workspace, expected, operations, projectName != null, testState.ProjectToBeModified.Id, newFileFolderContainers, newFileName, compareTokens: false); } if (checkIfUsingsIncluded) { Assert.NotNull(expectedTextWithUsings); await TestOperationsAsync(testState.Workspace, expectedTextWithUsings, operations, conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false, expectedChangedDocumentId: testState.InvocationDocument.Id); } if (checkIfUsingsNotIncluded) { var oldSolution = oldSolutionAndNewSolution.Item1; var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id)); } // Added into a different project than the triggering project if (projectName != null) { var appliedChanges = ApplyOperationsAndGetSolution(testState.Workspace, operations); var newSolution = appliedChanges.Item2; var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id); // Make sure the Project reference is present Assert.True(triggeredProject.ProjectReferences.Any(pr => pr.ProjectId == testState.ProjectToBeModified.Id)); } // Assert Option Calculation if (assertClassName != null) { Assert.True(assertClassName == testState.TestGenerateTypeOptionsService.ClassName); } if (assertGenerateTypeDialogOptions != null || assertTypeKindPresent != null || assertTypeKindAbsent != null) { var generateTypeDialogOptions = testState.TestGenerateTypeOptionsService.GenerateTypeDialogOptions; if (assertGenerateTypeDialogOptions != null) { Assert.True(assertGenerateTypeDialogOptions.IsPublicOnlyAccessibility == generateTypeDialogOptions.IsPublicOnlyAccessibility); Assert.True(assertGenerateTypeDialogOptions.TypeKindOptions == generateTypeDialogOptions.TypeKindOptions); Assert.True(assertGenerateTypeDialogOptions.IsAttribute == generateTypeDialogOptions.IsAttribute); } if (assertTypeKindPresent != null) { foreach (var typeKindPresentEach in assertTypeKindPresent) { Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) != 0); } } if (assertTypeKindAbsent != null) { foreach (var typeKindPresentEach in assertTypeKindAbsent) { Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) == 0); } } } } } } }
using Shouldly; using StructureMap.Graph; using StructureMap.Testing.GenericWidgets; using StructureMap.TypeRules; using System; using System.Reflection; using Xunit; namespace StructureMap.Testing { public class GenericsAcceptanceTester { public interface IService<T> { } public interface IHelper<T> { } public class Service<T> : IService<T> { private readonly IHelper<T> _helper; public Service(IHelper<T> helper) { _helper = helper; } public IHelper<T> Helper { get { return _helper; } } } public class Service2<T> : IService<T> { public Type GetT() { return typeof(T); } } public class ServiceWithPlug<T> : IService<T> { private readonly IPlug<T> _plug; public ServiceWithPlug(IPlug<T> plug) { _plug = plug; } public IPlug<T> Plug { get { return _plug; } } } public class Helper<T> : IHelper<T> { } [Fact] public void CanBuildAGenericObjectThatHasAnotherGenericObjectAsAChild() { var container = new Container(x => { x.For(typeof(IService<>)).Use(typeof(Service<>)); x.For(typeof(IHelper<>)).Use(typeof(Helper<>)); }); container.GetInstance<IService<string>>() .ShouldBeOfType<Service<string>>() .Helper.ShouldBeOfType<Helper<string>>(); } [Fact] public void CanCreatePluginFamilyForGenericTypeWithGenericParameter() { var family = new PluginFamily(typeof(IGenericService<int>)); } [Fact] public void CanCreatePluginFamilyForGenericTypeWithoutGenericParameter() { var family = new PluginFamily(typeof(IGenericService<>)); } [Fact] public void CanGetPluginFamilyFromPluginGraphWithNoParameters() { //var builder = new PluginGraphBuilder(); //var scanner = new AssemblyScanner(); //scanner.Assembly(GetType().GetAssembly()); //builder.AddScanner(scanner); var graph = PluginGraph.CreateRoot(); graph.Families[typeof(IGenericService<int>)].ShouldBeTheSameAs( graph.Families[typeof(IGenericService<int>)]); graph.Families[typeof(IGenericService<string>)].ShouldBeTheSameAs( graph.Families[typeof(IGenericService<string>)]); graph.Families[typeof(IGenericService<>)].ShouldBeTheSameAs( graph.Families[typeof(IGenericService<>)]); } [Fact] public void CanGetTheSameInstanceOfGenericInterfaceWithSingletonLifecycle() { var con = new Container(x => { x.ForSingletonOf(typeof(IService<>)).Use(typeof(Service<>)); x.For(typeof(IHelper<>)).Use(typeof(Helper<>)); }); var first = con.GetInstance<IService<string>>(); var second = con.GetInstance<IService<string>>(); first.ShouldBeTheSameAs(second); } [Fact] public void CanPlugGenericConcreteClassIntoGenericInterfaceWithNoGenericParametersSpecified() { var canPlug = typeof(GenericService<>).CanBeCastTo(typeof(IGenericService<>)); canPlug.ShouldBeTrue(); } [Fact] public void CanPlugConcreteNonGenericClassIntoGenericInterface() { typeof(NotSoGenericService).CanBeCastTo(typeof(IGenericService<>)) .ShouldBeTrue(); } [Fact] public void Define_profile_with_generics_and_concrete_type() { var container = new Container(registry => { registry.For(typeof(IHelper<>)).Use(typeof(Helper<>)); registry.Profile("1", x => x.For(typeof(IService<>)).Use(typeof(Service<>))); registry.Profile("2", x => x.For(typeof(IService<>)).Use(typeof(Service2<>))); }); container.GetProfile("1").GetInstance<IService<string>>().ShouldBeOfType<Service<string>>(); container.GetProfile("2").GetInstance<IService<string>>().ShouldBeOfType<Service2<string>>(); } [Fact] public void Define_profile_with_generics_with_named_instance() { IContainer container = new Container(r => { r.For(typeof(IService<>)).Add(typeof(Service<>)).Named("Service1"); r.For(typeof(IService<>)).Add(typeof(Service2<>)).Named("Service2"); r.For(typeof(IHelper<>)).Use(typeof(Helper<>)); r.Profile("1", x => x.For(typeof(IService<>)).Use("Service1")); r.Profile("2", x => x.For(typeof(IService<>)).Use("Service2")); }); container.GetProfile("1").GetInstance<IService<string>>().ShouldBeOfType<Service<string>>(); container.GetProfile("2").GetInstance<IService<int>>().ShouldBeOfType<Service2<int>>(); } [Fact] public void GenericsTypeAndProfileOrMachine() { var container = new Container(registry => { registry.For(typeof(IHelper<>)).Use(typeof(Helper<>)); registry.For(typeof(IService<>)).Use(typeof(Service<>)).Named("Default"); registry.For(typeof(IService<>)).Add(typeof(ServiceWithPlug<>)).Named("Plugged"); registry.For(typeof(IPlug<>)).Use(typeof(ConcretePlug<>)); registry.Profile("1", x => { x.For(typeof(IService<>)).Use("Default"); }); registry.Profile("2", x => { x.For(typeof(IService<>)).Use("Plugged"); }); }); container.GetProfile("1").GetInstance(typeof(IService<string>)).ShouldBeOfType<Service<string>>(); container.GetProfile("2").GetInstance(typeof(IService<string>)) .ShouldBeOfType<ServiceWithPlug<string>>(); container.GetProfile("1").GetInstance(typeof(IService<string>)).ShouldBeOfType<Service<string>>(); } [Fact] public void GetGenericTypeByString() { var assem = GetType().GetAssembly(); var type = assem.GetType("StructureMap.Testing.ITarget`2"); type.GetGenericTypeDefinition() .ShouldBe(typeof(ITarget<,>)); } [Fact] public void SmokeTestCanBeCaseWithImplementationOfANonGenericInterface() { GenericsPluginGraph.CanBeCast(typeof(ITarget<,>), typeof(DisposableTarget<,>)).ShouldBeTrue(); } } public class ComplexType<T> { private readonly int _age; private readonly string _name; public ComplexType(string name, int age) { _name = name; _age = age; } public string Name { get { return _name; } } public int Age { get { return _age; } } [ValidationMethod] public void Validate() { throw new Exception("Break!"); } } public interface ITarget<T, U> { } public class SpecificTarget<T, U> : ITarget<T, U> { } public class DisposableTarget<T, U> : ITarget<T, U>, IDisposable { #region IDisposable Members public void Dispose() { } #endregion IDisposable Members } public interface ITarget2<T, U, V> { } public class SpecificTarget2<T, U, V> : ITarget2<T, U, V> { } public interface IGenericService<T> { void DoSomething(T thing); } public class GenericService<T> : IGenericService<T> { #region IGenericService<T> Members public void DoSomething(T thing) { throw new NotImplementedException(); } #endregion IGenericService<T> Members public Type GetGenericType() { return typeof(T); } } public class NotSoGenericService : IGenericService<string> { public void DoSomething(string thing) { } } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol.Models { using System.Linq; /// <summary> /// Resource usage statistics for a job schedule. /// </summary> public partial class JobScheduleStatistics { /// <summary> /// Initializes a new instance of the JobScheduleStatistics class. /// </summary> public JobScheduleStatistics() { } /// <summary> /// Initializes a new instance of the JobScheduleStatistics class. /// </summary> /// <param name="url">The URL of the statistics.</param> /// <param name="startTime">The start time of the time range covered /// by the statistics.</param> /// <param name="lastUpdateTime">The time at which the statistics were /// last updated. All statistics are limited to the range between /// startTime and lastUpdateTime.</param> /// <param name="userCPUTime">The total user mode CPU time (summed /// across all cores and all compute nodes) consumed by all tasks in /// all jobs created under the schedule.</param> /// <param name="kernelCPUTime">The total kernel mode CPU time (summed /// across all cores and all compute nodes) consumed by all tasks in /// all jobs created under the schedule.</param> /// <param name="wallClockTime">The total wall clock time of all the /// tasks in all the jobs created under the schedule.</param> /// <param name="readIOps">The total number of disk read operations /// made by all tasks in all jobs created under the schedule.</param> /// <param name="writeIOps">The total number of disk write operations /// made by all tasks in all jobs created under the schedule.</param> /// <param name="readIOGiB">The total gibibytes read from disk by all /// tasks in all jobs created under the schedule.</param> /// <param name="writeIOGiB">The total gibibytes written to disk by /// all tasks in all jobs created under the schedule.</param> /// <param name="numSucceededTasks">The total number of tasks /// successfully completed during the given time range in jobs /// created under the schedule. A task completes successfully if it /// returns exit code 0.</param> /// <param name="numFailedTasks">The total number of tasks that failed /// during the given time range in jobs created under the schedule. A /// task fails if it exhausts its maximum retry count without /// returning exit code 0.</param> /// <param name="numTaskRetries">The total number of retries during /// the given time range on all tasks in all jobs created under the /// schedule.</param> /// <param name="waitTime">The total wait time of all tasks in all /// jobs created under the schedule. The wait time for a task is /// defined as the elapsed time between the creation of the task and /// the start of task execution. (If the task is retried due to /// failures, the wait time is the time to the most recent task /// execution.)</param> public JobScheduleStatistics(string url, System.DateTime startTime, System.DateTime lastUpdateTime, System.TimeSpan userCPUTime, System.TimeSpan kernelCPUTime, System.TimeSpan wallClockTime, long readIOps, long writeIOps, double readIOGiB, double writeIOGiB, long numSucceededTasks, long numFailedTasks, long numTaskRetries, System.TimeSpan waitTime) { Url = url; StartTime = startTime; LastUpdateTime = lastUpdateTime; UserCPUTime = userCPUTime; KernelCPUTime = kernelCPUTime; WallClockTime = wallClockTime; ReadIOps = readIOps; WriteIOps = writeIOps; ReadIOGiB = readIOGiB; WriteIOGiB = writeIOGiB; NumSucceededTasks = numSucceededTasks; NumFailedTasks = numFailedTasks; NumTaskRetries = numTaskRetries; WaitTime = waitTime; } /// <summary> /// Gets or sets the URL of the statistics. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "url")] public string Url { get; set; } /// <summary> /// Gets or sets the start time of the time range covered by the /// statistics. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "startTime")] public System.DateTime StartTime { get; set; } /// <summary> /// Gets or sets the time at which the statistics were last updated. /// All statistics are limited to the range between startTime and /// lastUpdateTime. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "lastUpdateTime")] public System.DateTime LastUpdateTime { get; set; } /// <summary> /// Gets or sets the total user mode CPU time (summed across all cores /// and all compute nodes) consumed by all tasks in all jobs created /// under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "userCPUTime")] public System.TimeSpan UserCPUTime { get; set; } /// <summary> /// Gets or sets the total kernel mode CPU time (summed across all /// cores and all compute nodes) consumed by all tasks in all jobs /// created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "kernelCPUTime")] public System.TimeSpan KernelCPUTime { get; set; } /// <summary> /// Gets or sets the total wall clock time of all the tasks in all the /// jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "wallClockTime")] public System.TimeSpan WallClockTime { get; set; } /// <summary> /// Gets or sets the total number of disk read operations made by all /// tasks in all jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "readIOps")] public long ReadIOps { get; set; } /// <summary> /// Gets or sets the total number of disk write operations made by all /// tasks in all jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "writeIOps")] public long WriteIOps { get; set; } /// <summary> /// Gets or sets the total gibibytes read from disk by all tasks in /// all jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "readIOGiB")] public double ReadIOGiB { get; set; } /// <summary> /// Gets or sets the total gibibytes written to disk by all tasks in /// all jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "writeIOGiB")] public double WriteIOGiB { get; set; } /// <summary> /// Gets or sets the total number of tasks successfully completed /// during the given time range in jobs created under the schedule. A /// task completes successfully if it returns exit code 0. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "numSucceededTasks")] public long NumSucceededTasks { get; set; } /// <summary> /// Gets or sets the total number of tasks that failed during the /// given time range in jobs created under the schedule. A task fails /// if it exhausts its maximum retry count without returning exit /// code 0. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "numFailedTasks")] public long NumFailedTasks { get; set; } /// <summary> /// Gets or sets the total number of retries during the given time /// range on all tasks in all jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "numTaskRetries")] public long NumTaskRetries { get; set; } /// <summary> /// Gets or sets the total wait time of all tasks in all jobs created /// under the schedule. The wait time for a task is defined as the /// elapsed time between the creation of the task and the start of /// task execution. (If the task is retried due to failures, the wait /// time is the time to the most recent task execution.) /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "waitTime")] public System.TimeSpan WaitTime { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Url == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Url"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Collections.ObjectModel; using Signum.Utilities; using System.Diagnostics; namespace Signum.Engine.Linq { /// <summary> /// An extended expression visitor including custom DbExpression nodes /// </summary> internal class DbExpressionVisitor : ExpressionVisitor { protected internal virtual Expression VisitCommandAggregate(CommandAggregateExpression cea) { var commands = VisitCommands(cea.Commands); if (cea.Commands != commands) return new CommandAggregateExpression(commands); return cea; } protected IEnumerable<CommandExpression> VisitCommands(ReadOnlyCollection<CommandExpression> commands) { return Visit(commands, c => (CommandExpression)Visit(c)); } protected internal virtual Expression VisitDelete(DeleteExpression delete) { var source = VisitSource(delete.Source); var where = Visit(delete.Where); if (source != delete.Source || where != delete.Where) return new DeleteExpression(delete.Table, delete.UseHistoryTable, (SourceWithAliasExpression)source, where, delete.ReturnRowCount); return delete; } protected internal virtual Expression VisitUpdate(UpdateExpression update) { var source = VisitSource(update.Source); var where = Visit(update.Where); var assigments = Visit(update.Assigments, VisitColumnAssigment); if(source != update.Source || where != update.Where || assigments != update.Assigments) return new UpdateExpression(update.Table, update.UseHistoryTable, (SourceWithAliasExpression)source, where, assigments, update.ReturnRowCount); return update; } protected internal virtual Expression VisitInsertSelect(InsertSelectExpression insertSelect) { var source = VisitSource(insertSelect.Source); var assigments = Visit(insertSelect.Assigments, VisitColumnAssigment); if (source != insertSelect.Source || assigments != insertSelect.Assigments) return new InsertSelectExpression(insertSelect.Table, insertSelect.UseHistoryTable, (SourceWithAliasExpression)source, assigments, insertSelect.ReturnRowCount); return insertSelect; } protected internal virtual ColumnAssignment VisitColumnAssigment(ColumnAssignment c) { var exp = Visit(c.Expression); if (exp != c.Expression) return new ColumnAssignment(c.Column, exp); return c; } protected internal virtual Expression VisitLiteReference(LiteReferenceExpression lite) { var newRef = Visit(lite.Reference); var newToStr = Visit(lite.CustomToStr); if (newRef != lite.Reference || newToStr != lite.CustomToStr) return new LiteReferenceExpression(lite.Type, newRef, newToStr, lite.LazyToStr, lite.EagerEntity); return lite; } protected internal virtual Expression VisitLiteValue(LiteValueExpression lite) { var newTypeId = Visit(lite.TypeId); var newId = Visit(lite.Id); var newToStr = Visit(lite.ToStr); if (newTypeId != lite.TypeId || newId != lite.Id || newToStr != lite.ToStr) return new LiteValueExpression(lite.Type, newTypeId, newId, newToStr); return lite; } protected internal virtual Expression VisitTypeEntity(TypeEntityExpression typeFie) { var externalId = (PrimaryKeyExpression)Visit(typeFie.ExternalId); if (externalId != typeFie.ExternalId) return new TypeEntityExpression(externalId, typeFie.TypeValue); return typeFie; } [DebuggerStepThrough] protected static ReadOnlyDictionary<K, V> Visit<K, V>(ReadOnlyDictionary<K, V> dictionary, Func<V, V> newValue) where K : notnull where V : class { Dictionary<K, V>? alternate = null; foreach (var k in dictionary.Keys) { V item = dictionary[k]; V newItem = newValue(item); if (alternate == null && item != newItem) { alternate = new Dictionary<K, V>(); foreach (var k2 in dictionary.Keys.TakeWhile(k2 => !k2.Equals(k))) alternate.Add(k2, dictionary[k2]); } if (alternate != null && newItem != null) { alternate.Add(k, newItem); } } if (alternate != null) { return alternate.ToReadOnly(); } return dictionary; } protected internal virtual Expression VisitTypeImplementedBy(TypeImplementedByExpression typeIb) { var implementations = Visit(typeIb.TypeImplementations, eid => (PrimaryKeyExpression)Visit(eid)); if (implementations != typeIb.TypeImplementations) return new TypeImplementedByExpression(implementations); return typeIb; } protected internal virtual Expression VisitTypeImplementedByAll(TypeImplementedByAllExpression typeIba) { var column = (PrimaryKeyExpression)Visit(typeIba.TypeColumn); if (column != typeIba.TypeColumn) return new TypeImplementedByAllExpression(column); return typeIba; } protected internal virtual Expression VisitMList(MListExpression ml) { var newBackID = (PrimaryKeyExpression)Visit(ml.BackID); var externalPeriod = (IntervalExpression)Visit(ml.ExternalPeriod); if (newBackID != ml.BackID || externalPeriod != ml.ExternalPeriod) return new MListExpression(ml.Type, newBackID, externalPeriod, ml.TableMList); return ml; } protected internal virtual Expression VisitMListProjection(MListProjectionExpression mlp) { var proj = (ProjectionExpression)Visit(mlp.Projection); if (proj != mlp.Projection) return new MListProjectionExpression(mlp.Type, proj); return mlp; } protected internal virtual Expression VisitMListElement(MListElementExpression mle) { var rowId = (PrimaryKeyExpression)Visit(mle.RowId); var parent = (EntityExpression)Visit(mle.Parent); var order = Visit(mle.Order); var element = Visit(mle.Element); var period = (IntervalExpression)Visit(mle.TablePeriod); if (rowId != mle.RowId || parent != mle.Parent || order != mle.Order || element != mle.Element || period != mle.TablePeriod) return new MListElementExpression(rowId, parent, order, element, period, mle.Table, mle.Alias); return mle; } protected internal virtual Expression VisitAdditionalField(AdditionalFieldExpression ml) { var newBackID = (PrimaryKeyExpression)Visit(ml.BackID); var externalPeriod = (IntervalExpression)Visit(ml.ExternalPeriod); if (newBackID != ml.BackID || externalPeriod != ml.ExternalPeriod) return new AdditionalFieldExpression(ml.Type, newBackID, externalPeriod, ml.Route); return ml; } protected internal virtual Expression VisitSqlLiteral(SqlLiteralExpression sqlEnum) { return sqlEnum; } protected internal virtual Expression VisitSqlCast(SqlCastExpression castExpr) { var expression = Visit(castExpr.Expression); if (expression != castExpr.Expression) return new SqlCastExpression(castExpr.Type, expression,castExpr.DbType); return castExpr; } protected internal virtual Expression VisitTable(TableExpression table) { return table; } protected internal virtual Expression VisitColumn(ColumnExpression column) { return column; } protected internal virtual Expression VisitImplementedByAll(ImplementedByAllExpression iba) { var id = Visit(iba.Id); var typeId = (TypeImplementedByAllExpression)Visit(iba.TypeId); var externalPeriod = (IntervalExpression)Visit(iba.ExternalPeriod); if (id != iba.Id || typeId != iba.TypeId || externalPeriod != iba.ExternalPeriod) return new ImplementedByAllExpression(iba.Type, id, typeId, externalPeriod); return iba; } protected internal virtual Expression VisitImplementedBy(ImplementedByExpression ib) { var implementations = Visit(ib.Implementations, v => (EntityExpression)Visit(v)); if (implementations != ib.Implementations) return new ImplementedByExpression(ib.Type, ib.Strategy, implementations); return ib; } protected internal virtual Expression VisitEntity(EntityExpression ee) { var bindings = Visit(ee.Bindings, VisitFieldBinding); var mixins = Visit(ee.Mixins, VisitMixinEntity); var externalId = (PrimaryKeyExpression)Visit(ee.ExternalId); var externalPeriod = (IntervalExpression)Visit(ee.ExternalPeriod); var period = (IntervalExpression)Visit(ee.TablePeriod); if (ee.Bindings != bindings || ee.ExternalId != externalId || ee.ExternalPeriod != externalPeriod || ee.Mixins != mixins || ee.TablePeriod != period) return new EntityExpression(ee.Type, externalId, externalPeriod, ee.TableAlias, bindings, mixins, period, ee.AvoidExpandOnRetrieving); return ee; } protected internal virtual Expression VisitEmbeddedEntity(EmbeddedEntityExpression eee) { var bindings = Visit(eee.Bindings, VisitFieldBinding); var hasValue = Visit(eee.HasValue); if (eee.Bindings != bindings || eee.HasValue != hasValue) { return new EmbeddedEntityExpression(eee.Type, hasValue, bindings, eee.FieldEmbedded, eee.ViewTable); } return eee; } protected internal virtual MixinEntityExpression VisitMixinEntity(MixinEntityExpression me) { var bindings = Visit(me.Bindings, VisitFieldBinding); if (me.Bindings != bindings) { return new MixinEntityExpression(me.Type, bindings, me.MainEntityAlias, me.FieldMixin); } return me; } protected internal virtual FieldBinding VisitFieldBinding(FieldBinding fb) { var r = Visit(fb.Binding); if(r == fb.Binding) return fb; return new FieldBinding(fb.FieldInfo, r); } protected internal virtual Expression VisitLike(LikeExpression like) { Expression exp = Visit(like.Expression); Expression pattern = Visit(like.Pattern); if (exp != like.Expression || pattern != like.Pattern) return new LikeExpression(exp, pattern); return like; } protected internal virtual Expression VisitScalar(ScalarExpression scalar) { var select = (SelectExpression)this.Visit(scalar.Select); if (select != scalar.Select) return new ScalarExpression(scalar.Type, select); return scalar; } protected internal virtual Expression VisitExists(ExistsExpression exists) { var select = (SelectExpression)this.Visit(exists.Select); if (select != exists.Select) return new ExistsExpression(select); return exists; } protected internal virtual Expression VisitIn(InExpression @in) { var expression = this.Visit(@in.Expression); var select = (SelectExpression)this.Visit(@in.Select); if (expression != @in.Expression || select != @in.Select) { if (select != null) return new InExpression(expression, select); else return InExpression.FromValues(expression, @in.Values!); } return @in; } protected internal virtual Expression VisitIsNull(IsNullExpression isNull) { var newExpr = Visit(isNull.Expression); if (newExpr != isNull.Expression) return new IsNullExpression(newExpr); return isNull; } protected internal virtual Expression VisitIsNotNull(IsNotNullExpression isNotNull) { var newExpr = Visit(isNotNull.Expression); if (newExpr != isNotNull.Expression) return new IsNotNullExpression(newExpr); return isNotNull; } protected internal virtual Expression VisitRowNumber(RowNumberExpression rowNumber) { var orderBys = Visit(rowNumber.OrderBy, VisitOrderBy); if (orderBys != rowNumber.OrderBy) return new RowNumberExpression(orderBys); return rowNumber; } protected internal virtual Expression VisitAggregate(AggregateExpression aggregate) { var expressions = Visit(aggregate.Arguments); if (expressions != aggregate.Arguments) return new AggregateExpression(aggregate.Type, aggregate.AggregateFunction, expressions); return aggregate; } protected internal virtual Expression VisitAggregateRequest(AggregateRequestsExpression request) { var ag = (AggregateExpression)this.Visit(request.Aggregate); if (ag != request.Aggregate) return new AggregateRequestsExpression(request.GroupByAlias, ag); return request; } protected internal virtual Expression VisitSelect(SelectExpression select) { Expression top = this.Visit(select.Top); SourceExpression from = this.VisitSource(select.From!); Expression where = this.Visit(select.Where); ReadOnlyCollection<ColumnDeclaration> columns = Visit(select.Columns, VisitColumnDeclaration); ReadOnlyCollection<OrderExpression> orderBy = Visit(select.OrderBy, VisitOrderBy); ReadOnlyCollection<Expression> groupBy = Visit(select.GroupBy, Visit); if (top != select.Top || from != select.From || where != select.Where || columns != select.Columns || orderBy != select.OrderBy || groupBy != select.GroupBy) return new SelectExpression(select.Alias, select.IsDistinct, top, columns, from, where, orderBy, groupBy, select.SelectOptions); return select; } protected internal virtual Expression VisitJoin(JoinExpression join) { SourceExpression left = this.VisitSource(join.Left); SourceExpression right = this.VisitSource(join.Right); Expression condition = this.Visit(join.Condition); if (left != join.Left || right != join.Right || condition != join.Condition) { return new JoinExpression(join.JoinType, left, right, condition); } return join; } protected internal virtual Expression VisitSetOperator(SetOperatorExpression set) { SourceWithAliasExpression left = (SourceWithAliasExpression)this.VisitSource(set.Left)!; SourceWithAliasExpression right = (SourceWithAliasExpression)this.VisitSource(set.Right)!; if (left != set.Left || right != set.Right) { return new SetOperatorExpression(set.Operator, left, right, set.Alias); } return set; } protected internal virtual SourceExpression VisitSource(SourceExpression source) { return (SourceExpression)this.Visit(source); } protected internal virtual Expression VisitProjection(ProjectionExpression proj) { SelectExpression source = (SelectExpression)this.Visit(proj.Select); Expression projector = this.Visit(proj.Projector); if (source != proj.Select || projector != proj.Projector) return new ProjectionExpression(source, projector, proj.UniqueFunction, proj.Type); return proj; } protected internal virtual Expression VisitChildProjection(ChildProjectionExpression child) { ProjectionExpression proj = (ProjectionExpression)this.Visit(child.Projection); Expression key = this.Visit(child.OuterKey); if (proj != child.Projection || key != child.OuterKey) { return new ChildProjectionExpression(proj, key, child.IsLazyMList, child.Type, child.Token); } return child; } protected internal virtual Expression VisitSqlFunction(SqlFunctionExpression sqlFunction) { Expression obj = Visit(sqlFunction.Object); ReadOnlyCollection<Expression> args = Visit(sqlFunction.Arguments); if (args != sqlFunction.Arguments || obj != sqlFunction.Object) return new SqlFunctionExpression(sqlFunction.Type, obj, sqlFunction.SqlFunction, args); return sqlFunction; } protected internal virtual Expression VisitSqlTableValuedFunction(SqlTableValuedFunctionExpression sqlFunction) { ReadOnlyCollection<Expression> args = Visit(sqlFunction.Arguments); if (args != sqlFunction.Arguments) return new SqlTableValuedFunctionExpression(sqlFunction.SqlFunction, sqlFunction.ViewTable, sqlFunction.SingleColumnType, sqlFunction.Alias, args); return sqlFunction; } protected internal virtual Expression VisitSqlConstant(SqlConstantExpression sce) { return sce; } protected internal virtual Expression VisitSqlVariable(SqlVariableExpression sve) { return sve; } protected internal virtual Expression VisitCase(CaseExpression cex) { var newWhens = Visit(cex.Whens, w => VisitWhen(w)); var newDefault = Visit(cex.DefaultValue); if (newWhens != cex.Whens || newDefault != cex.DefaultValue) return new CaseExpression(newWhens, newDefault); return cex; } protected internal virtual When VisitWhen(When when) { var newCondition = Visit(when.Condition); var newValue = Visit(when.Value); if (when.Condition != newCondition || newValue != when.Value) return new When(newCondition, newValue); return when; } protected internal virtual ColumnDeclaration VisitColumnDeclaration(ColumnDeclaration c) { var e = Visit(c.Expression); if (e == c.Expression) return c; return new ColumnDeclaration(c.Name, e); } protected internal virtual Expression VisitToDayOfWeek(ToDayOfWeekExpression toDayOfWeek) { var exp = Visit(toDayOfWeek.Expression); if (exp == toDayOfWeek.Expression) return toDayOfWeek; return new ToDayOfWeekExpression(exp); } protected internal virtual OrderExpression VisitOrderBy(OrderExpression o) { var e = Visit(o.Expression); if (e == o.Expression) return o; return new OrderExpression(o.OrderType, e); } protected internal virtual Expression VisitPrimaryKey(PrimaryKeyExpression pk) { var e = Visit(pk.Value); if (e == pk.Value) return pk; return new PrimaryKeyExpression(e); } protected internal virtual Expression VisitPrimaryKeyString(PrimaryKeyStringExpression pk) { var typeId = Visit(pk.TypeId); var id = Visit(pk.Id); if (typeId == pk && pk.Id == id) return pk; return new PrimaryKeyStringExpression(id, (TypeImplementedByAllExpression)typeId); } protected internal virtual Expression VisitInterval(IntervalExpression interval) { Expression min = Visit(interval.Min); Expression max = Visit(interval.Max); Expression postgresRange = Visit(interval.PostgresRange); if (min != interval.Min || max != interval.Max || postgresRange != interval.PostgresRange) return new IntervalExpression(interval.Type, min, max, postgresRange, interval.AsUtc); return interval; } } }
// 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.Xml.Serialization { using System.Reflection; using System; using System.Globalization; using System.Xml.Schema; using System.Collections; using System.ComponentModel; using System.Threading; using System.Linq; /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class SoapReflectionImporter { private TypeScope _typeScope; private SoapAttributeOverrides _attributeOverrides; private NameTable _types = new NameTable(); // xmltypename + xmlns -> Mapping private NameTable _nullables = new NameTable(); // xmltypename + xmlns -> NullableMapping private StructMapping _root; private string _defaultNs; private ModelScope _modelScope; /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.SoapReflectionImporter"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapReflectionImporter() : this(null, null) { } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.SoapReflectionImporter1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapReflectionImporter(string defaultNamespace) : this(null, defaultNamespace) { } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.SoapReflectionImporter2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapReflectionImporter(SoapAttributeOverrides attributeOverrides) : this(attributeOverrides, null) { } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.SoapReflectionImporter3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapReflectionImporter(SoapAttributeOverrides attributeOverrides, string defaultNamespace) { if (defaultNamespace == null) defaultNamespace = String.Empty; if (attributeOverrides == null) attributeOverrides = new SoapAttributeOverrides(); _attributeOverrides = attributeOverrides; _defaultNs = defaultNamespace; _typeScope = new TypeScope(); _modelScope = new ModelScope(_typeScope); } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.IncludeTypes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void IncludeTypes(ICustomAttributeProvider provider) { IncludeTypes(provider, new RecursionLimiter()); } private void IncludeTypes(ICustomAttributeProvider provider, RecursionLimiter limiter) { object[] attrs = provider.GetCustomAttributes(typeof(SoapIncludeAttribute), false); for (int i = 0; i < attrs.Length; i++) { IncludeType(((SoapIncludeAttribute)attrs[i]).Type, limiter); } } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.IncludeType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void IncludeType(Type type) { IncludeType(type, new RecursionLimiter()); } private void IncludeType(Type type, RecursionLimiter limiter) { ImportTypeMapping(_modelScope.GetTypeModel(type), limiter); } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="XmlReflectionImporter.ImportTypeMapping"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlTypeMapping ImportTypeMapping(Type type) { return ImportTypeMapping(type, null); } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="XmlReflectionImporter.ImportTypeMapping1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; element.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(type), new RecursionLimiter()); element.Name = element.Mapping.DefaultElementName; element.Namespace = element.Mapping.Namespace == null ? defaultNamespace : element.Mapping.Namespace; element.Form = XmlSchemaForm.Qualified; XmlTypeMapping xmlMapping = new XmlTypeMapping(_typeScope, element); xmlMapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, defaultNamespace)); xmlMapping.IsSoap = true; xmlMapping.GenerateSerializer = true; return xmlMapping; } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.ImportMembersMapping"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members) { return ImportMembersMapping(elementName, ns, members, true, true, false); } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.ImportMembersMapping1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, writeAccessors, false); } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.ImportMembersMapping2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, writeAccessors, validate, XmlMappingAccess.Read | XmlMappingAccess.Write); } /// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.ImportMembersMapping3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate, XmlMappingAccess access) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; element.Name = elementName == null || elementName.Length == 0 ? elementName : XmlConvert.EncodeLocalName(elementName); element.Mapping = ImportMembersMapping(members, ns, hasWrapperElement, writeAccessors, validate, new RecursionLimiter()); element.Mapping.TypeName = elementName; element.Namespace = element.Mapping.Namespace == null ? ns : element.Mapping.Namespace; element.Form = XmlSchemaForm.Qualified; XmlMembersMapping xmlMapping = new XmlMembersMapping(_typeScope, element, access); xmlMapping.IsSoap = true; xmlMapping.GenerateSerializer = true; return xmlMapping; } private Exception ReflectionException(string context, Exception e) { return new InvalidOperationException(SR.Format(SR.XmlReflectionError, context), e); } private SoapAttributes GetAttributes(Type type) { SoapAttributes attrs = _attributeOverrides[type]; if (attrs != null) return attrs; return new SoapAttributes(type); } private SoapAttributes GetAttributes(MemberInfo memberInfo) { SoapAttributes attrs = _attributeOverrides[memberInfo.DeclaringType, memberInfo.Name]; if (attrs != null) return attrs; return new SoapAttributes(memberInfo); } private TypeMapping ImportTypeMapping(TypeModel model, RecursionLimiter limiter) { return ImportTypeMapping(model, String.Empty, limiter); } private TypeMapping ImportTypeMapping(TypeModel model, string dataType, RecursionLimiter limiter) { if (dataType.Length > 0) { if (!model.TypeDesc.IsPrimitive) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidDataTypeUsage, dataType, "SoapElementAttribute.DataType")); } TypeDesc td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); if (td == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXsdDataType, dataType, "SoapElementAttribute.DataType", new XmlQualifiedName(dataType, XmlSchema.Namespace).ToString())); } if (model.TypeDesc.FullName != td.FullName) { throw new InvalidOperationException(SR.Format(SR.XmlDataTypeMismatch, dataType, "SoapElementAttribute.DataType", model.TypeDesc.FullName)); } } SoapAttributes a = GetAttributes(model.Type); if ((a.SoapFlags & ~SoapAttributeFlags.Type) != 0) throw new InvalidOperationException(SR.Format(SR.XmlInvalidTypeAttributes, model.Type.FullName)); switch (model.TypeDesc.Kind) { case TypeKind.Enum: return ImportEnumMapping((EnumModel)model); case TypeKind.Primitive: return ImportPrimitiveMapping((PrimitiveModel)model, dataType); case TypeKind.Array: case TypeKind.Collection: case TypeKind.Enumerable: return ImportArrayLikeMapping((ArrayModel)model, limiter); case TypeKind.Root: case TypeKind.Class: case TypeKind.Struct: if (model.TypeDesc.IsOptionalValue) { TypeDesc baseTypeDesc = model.TypeDesc.BaseTypeDesc; SoapAttributes baseAttributes = GetAttributes(baseTypeDesc.Type); string typeNs = _defaultNs; if (baseAttributes.SoapType != null && baseAttributes.SoapType.Namespace != null) typeNs = baseAttributes.SoapType.Namespace; TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); string xsdTypeName = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc.Name : dataType; TypeMapping baseMapping = GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc); if (baseMapping == null) baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type), dataType, limiter); return CreateNullableMapping(baseMapping, model.TypeDesc.Type); } else { return ImportStructLikeMapping((StructModel)model, limiter); } default: throw new NotSupportedException(SR.Format(SR.XmlUnsupportedSoapTypeKind, model.TypeDesc.FullName)); } } private StructMapping CreateRootMapping() { TypeDesc typeDesc = _typeScope.GetTypeDesc(typeof(object)); StructMapping mapping = new StructMapping(); mapping.IsSoap = true; mapping.TypeDesc = typeDesc; mapping.Members = new MemberMapping[0]; mapping.IncludeInSchema = false; mapping.TypeName = Soap.UrType; mapping.Namespace = XmlSchema.Namespace; return mapping; } private StructMapping GetRootMapping() { if (_root == null) { _root = CreateRootMapping(); _typeScope.AddTypeMapping(_root); } return _root; } private TypeMapping GetTypeMapping(string typeName, string ns, TypeDesc typeDesc) { TypeMapping mapping = (TypeMapping)_types[typeName, ns]; if (mapping == null) return null; if (mapping.TypeDesc != typeDesc) throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc.FullName, typeName, ns)); return mapping; } private NullableMapping CreateNullableMapping(TypeMapping baseMapping, Type type) { TypeDesc typeDesc = baseMapping.TypeDesc.GetNullableTypeDesc(type); TypeMapping existingMapping = (TypeMapping)_nullables[baseMapping.TypeName, baseMapping.Namespace]; NullableMapping mapping; if (existingMapping != null) { if (existingMapping is NullableMapping) { mapping = (NullableMapping)existingMapping; if (mapping.BaseMapping is PrimitiveMapping && baseMapping is PrimitiveMapping) return mapping; else if (mapping.BaseMapping == baseMapping) { return mapping; } else { throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); } } else if (!(baseMapping is PrimitiveMapping)) { throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); } } mapping = new NullableMapping(); mapping.BaseMapping = baseMapping; mapping.TypeDesc = typeDesc; mapping.TypeName = baseMapping.TypeName; mapping.Namespace = baseMapping.Namespace; mapping.IncludeInSchema = false; //baseMapping.IncludeInSchema; _nullables.Add(baseMapping.TypeName, mapping.Namespace, mapping); _typeScope.AddTypeMapping(mapping); return mapping; } private StructMapping ImportStructLikeMapping(StructModel model, RecursionLimiter limiter) { if (model.TypeDesc.Kind == TypeKind.Root) return GetRootMapping(); SoapAttributes a = GetAttributes(model.Type); string typeNs = _defaultNs; if (a.SoapType != null && a.SoapType.Namespace != null) typeNs = a.SoapType.Namespace; string typeName = XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); StructMapping mapping = (StructMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc); if (mapping == null) { mapping = new StructMapping(); mapping.IsSoap = true; mapping.TypeDesc = model.TypeDesc; mapping.Namespace = typeNs; mapping.TypeName = typeName; if (a.SoapType != null) mapping.IncludeInSchema = a.SoapType.IncludeInSchema; _typeScope.AddTypeMapping(mapping); _types.Add(typeName, typeNs, mapping); if (limiter.IsExceededLimit) { limiter.DeferredWorkItems.Add(new ImportStructWorkItem(model, mapping)); return mapping; } limiter.Depth++; InitializeStructMembers(mapping, model, limiter); while (limiter.DeferredWorkItems.Count > 0) { int index = limiter.DeferredWorkItems.Count - 1; ImportStructWorkItem item = limiter.DeferredWorkItems[index]; if (InitializeStructMembers(item.Mapping, item.Model, limiter)) { // // if InitializeStructMembers returns true, then there were *no* changes to the DeferredWorkItems // #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (index != limiter.DeferredWorkItems.Count - 1) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "DeferredWorkItems.Count have changed")); if (item != limiter.DeferredWorkItems[index]) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "DeferredWorkItems.Top have changed")); #endif // Remove the last work item limiter.DeferredWorkItems.RemoveAt(index); } } limiter.Depth--; } return mapping; } private bool InitializeStructMembers(StructMapping mapping, StructModel model, RecursionLimiter limiter) { if (mapping.IsFullyInitialized) return true; if (model.TypeDesc.BaseTypeDesc != null) { StructMapping baseMapping = ImportStructLikeMapping((StructModel)_modelScope.GetTypeModel(model.Type.BaseType, false), limiter); // check to see if the import of the baseMapping was deferred int baseIndex = limiter.DeferredWorkItems.IndexOf(mapping.BaseMapping); if (baseIndex < 0) { mapping.BaseMapping = baseMapping; } else { // the import of the baseMapping was deferred, make sure that the derived mappings is deferred as well if (!limiter.DeferredWorkItems.Contains(mapping)) { limiter.DeferredWorkItems.Add(new ImportStructWorkItem(model, mapping)); } // make sure that baseMapping get processed before the derived int top = limiter.DeferredWorkItems.Count - 1; if (baseIndex < top) { ImportStructWorkItem baseMappingWorkItem = limiter.DeferredWorkItems[baseIndex]; limiter.DeferredWorkItems[baseIndex] = limiter.DeferredWorkItems[top]; limiter.DeferredWorkItems[top] = baseMappingWorkItem; } return false; } } ArrayList members = new ArrayList(); foreach (MemberInfo memberInfo in model.GetMemberInfos()) { if (!(memberInfo is FieldInfo) && !(memberInfo is PropertyInfo)) continue; SoapAttributes memberAttrs = GetAttributes(memberInfo); if (memberAttrs.SoapIgnore) continue; FieldModel fieldModel = model.GetFieldModel(memberInfo); if (fieldModel == null) continue; MemberMapping member = ImportFieldMapping(fieldModel, memberAttrs, mapping.Namespace, limiter); if (member == null) continue; if (!member.TypeDesc.IsPrimitive && !member.TypeDesc.IsEnum && !member.TypeDesc.IsOptionalValue) { if (model.TypeDesc.IsValueType) throw new NotSupportedException(SR.Format(SR.XmlRpcRefsInValueType, model.TypeDesc.FullName)); if (member.TypeDesc.IsValueType) throw new NotSupportedException(SR.Format(SR.XmlRpcNestedValueType, member.TypeDesc.FullName)); } if (mapping.BaseMapping != null) { if (mapping.BaseMapping.Declares(member, mapping.TypeName)) continue; } members.Add(member); } mapping.Members = (MemberMapping[])members.ToArray(typeof(MemberMapping)); if (mapping.BaseMapping == null) mapping.BaseMapping = GetRootMapping(); IncludeTypes(model.Type, limiter); return true; } private ArrayMapping ImportArrayLikeMapping(ArrayModel model, RecursionLimiter limiter) { ArrayMapping mapping = new ArrayMapping(); mapping.IsSoap = true; TypeMapping itemTypeMapping = ImportTypeMapping(model.Element, limiter); if (itemTypeMapping.TypeDesc.IsValueType && !itemTypeMapping.TypeDesc.IsPrimitive && !itemTypeMapping.TypeDesc.IsEnum) throw new NotSupportedException(SR.Format(SR.XmlRpcArrayOfValueTypes, model.TypeDesc.FullName)); mapping.TypeDesc = model.TypeDesc; mapping.Elements = new ElementAccessor[] { CreateElementAccessor(itemTypeMapping, mapping.Namespace) }; SetArrayMappingType(mapping); // in the case of an ArrayMapping we can have more that one mapping correspond to a type // examples of that are ArrayList and object[] both will map tp ArrayOfur-type // so we create a link list for all mappings of the same XSD type ArrayMapping existingMapping = (ArrayMapping)_types[mapping.TypeName, mapping.Namespace]; if (existingMapping != null) { ArrayMapping first = existingMapping; while (existingMapping != null) { if (existingMapping.TypeDesc == model.TypeDesc) return existingMapping; existingMapping = existingMapping.Next; } mapping.Next = first; _types[mapping.TypeName, mapping.Namespace] = mapping; return mapping; } _typeScope.AddTypeMapping(mapping); _types.Add(mapping.TypeName, mapping.Namespace, mapping); IncludeTypes(model.Type); return mapping; } // UNDONE Nullable private void SetArrayMappingType(ArrayMapping mapping) { bool useDefaultNs = false; string itemTypeName; string itemTypeNamespace; TypeMapping itemTypeMapping; if (mapping.Elements.Length == 1) itemTypeMapping = mapping.Elements[0].Mapping; else itemTypeMapping = null; if (itemTypeMapping is EnumMapping) { itemTypeNamespace = itemTypeMapping.Namespace; itemTypeName = itemTypeMapping.TypeName; } else if (itemTypeMapping is PrimitiveMapping) { itemTypeNamespace = itemTypeMapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; itemTypeName = itemTypeMapping.TypeDesc.DataType.Name; useDefaultNs = true; } else if (itemTypeMapping is StructMapping) { if (itemTypeMapping.TypeDesc.IsRoot) { itemTypeNamespace = XmlSchema.Namespace; itemTypeName = Soap.UrType; useDefaultNs = true; } else { itemTypeNamespace = itemTypeMapping.Namespace; itemTypeName = itemTypeMapping.TypeName; } } else if (itemTypeMapping is ArrayMapping) { itemTypeNamespace = itemTypeMapping.Namespace; itemTypeName = itemTypeMapping.TypeName; } else { throw new InvalidOperationException(SR.Format(SR.XmlInvalidSoapArray, mapping.TypeDesc.FullName)); } itemTypeName = CodeIdentifier.MakePascal(itemTypeName); string uniqueName = "ArrayOf" + itemTypeName; string ns = useDefaultNs ? _defaultNs : itemTypeNamespace; int i = 1; TypeMapping existingMapping = (TypeMapping)_types[uniqueName, ns]; while (existingMapping != null) { if (existingMapping is ArrayMapping) { ArrayMapping arrayMapping = (ArrayMapping)existingMapping; if (AccessorMapping.ElementsMatch(arrayMapping.Elements, mapping.Elements)) { break; } } // need to re-name the mapping uniqueName = itemTypeName + i.ToString(CultureInfo.InvariantCulture); existingMapping = (TypeMapping)_types[uniqueName, ns]; i++; } mapping.Namespace = ns; mapping.TypeName = uniqueName; } private PrimitiveMapping ImportPrimitiveMapping(PrimitiveModel model, string dataType) { PrimitiveMapping mapping = new PrimitiveMapping(); mapping.IsSoap = true; if (dataType.Length > 0) { mapping.TypeDesc = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); if (mapping.TypeDesc == null) { // try it as a non-Xsd type mapping.TypeDesc = _typeScope.GetTypeDesc(dataType, UrtTypes.Namespace); if (mapping.TypeDesc == null) { throw new InvalidOperationException(SR.Format(SR.XmlUdeclaredXsdType, dataType)); } } } else { mapping.TypeDesc = model.TypeDesc; } mapping.TypeName = mapping.TypeDesc.DataType.Name; mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; return mapping; } private EnumMapping ImportEnumMapping(EnumModel model) { SoapAttributes a = GetAttributes(model.Type); string typeNs = _defaultNs; if (a.SoapType != null && a.SoapType.Namespace != null) typeNs = a.SoapType.Namespace; string typeName = XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); EnumMapping mapping = (EnumMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc); if (mapping == null) { mapping = new EnumMapping(); mapping.IsSoap = true; mapping.TypeDesc = model.TypeDesc; mapping.TypeName = typeName; mapping.Namespace = typeNs; mapping.IsFlags = model.Type.IsDefined(typeof(FlagsAttribute), false); _typeScope.AddTypeMapping(mapping); _types.Add(typeName, typeNs, mapping); ArrayList constants = new ArrayList(); for (int i = 0; i < model.Constants.Length; i++) { ConstantMapping constant = ImportConstantMapping(model.Constants[i]); if (constant != null) constants.Add(constant); } if (constants.Count == 0) { throw new InvalidOperationException(SR.Format(SR.XmlNoSerializableMembers, model.TypeDesc.FullName)); } mapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping)); } return mapping; } private ConstantMapping ImportConstantMapping(ConstantModel model) { SoapAttributes a = GetAttributes(model.FieldInfo); if (a.SoapIgnore) return null; if ((a.SoapFlags & ~SoapAttributeFlags.Enum) != 0) throw new InvalidOperationException(SR.XmlInvalidEnumAttribute); if (a.SoapEnum == null) a.SoapEnum = new SoapEnumAttribute(); ConstantMapping constant = new ConstantMapping(); constant.XmlName = a.SoapEnum.Name.Length == 0 ? model.Name : a.SoapEnum.Name; constant.Name = model.Name; constant.Value = model.Value; return constant; } private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, string ns, bool hasWrapperElement, bool writeAccessors, bool validateWrapperElement, RecursionLimiter limiter) { MembersMapping members = new MembersMapping(); members.TypeDesc = _typeScope.GetTypeDesc(typeof(object[])); MemberMapping[] mappings = new MemberMapping[xmlReflectionMembers.Length]; for (int i = 0; i < mappings.Length; i++) { try { XmlReflectionMember member = xmlReflectionMembers[i]; MemberMapping mapping = ImportMemberMapping(member, ns, xmlReflectionMembers, hasWrapperElement ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified, limiter); if (member.IsReturnValue && writeAccessors) { // no special treatment for return values with doc/enc if (i > 0) throw new InvalidOperationException(SR.XmlInvalidReturnPosition); mapping.IsReturnValue = true; } mappings[i] = mapping; } catch (Exception e) { if (e is OutOfMemoryException) { throw; } throw ReflectionException(xmlReflectionMembers[i].MemberName, e); } } members.Members = mappings; members.HasWrapperElement = hasWrapperElement; if (hasWrapperElement) { members.ValidateRpcWrapperElement = validateWrapperElement; } members.WriteAccessors = writeAccessors; members.IsSoap = true; if (hasWrapperElement && !writeAccessors) members.Namespace = ns; return members; } private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string ns, XmlReflectionMember[] xmlReflectionMembers, XmlSchemaForm form, RecursionLimiter limiter) { SoapAttributes a = xmlReflectionMember.SoapAttributes; if (a.SoapIgnore) return null; MemberMapping member = new MemberMapping(); member.IsSoap = true; member.Name = xmlReflectionMember.MemberName; bool checkSpecified = XmlReflectionImporter.FindSpecifiedMember(xmlReflectionMember.MemberName, xmlReflectionMembers) != null; FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType), checkSpecified, false); member.CheckShouldPersist = model.CheckShouldPersist; member.CheckSpecified = model.CheckSpecified; member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.HasDefaultConstructor; ImportAccessorMapping(member, model, a, ns, form, limiter); if (xmlReflectionMember.OverrideIsNullable) member.Elements[0].IsNullable = false; return member; } private MemberMapping ImportFieldMapping(FieldModel model, SoapAttributes a, string ns, RecursionLimiter limiter) { if (a.SoapIgnore) return null; MemberMapping member = new MemberMapping(); member.IsSoap = true; member.Name = model.Name; member.CheckShouldPersist = model.CheckShouldPersist; member.CheckSpecified = model.CheckSpecified; member.MemberInfo = model.MemberInfo; member.CheckSpecifiedMemberInfo = model.CheckSpecifiedMemberInfo; member.CheckShouldPersistMethodInfo = model.CheckShouldPersistMethodInfo; member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.HasDefaultConstructor; ImportAccessorMapping(member, model, a, ns, XmlSchemaForm.Unqualified, limiter); return member; } private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, SoapAttributes a, string ns, XmlSchemaForm form, RecursionLimiter limiter) { Type accessorType = model.FieldType; string accessorName = model.Name; accessor.TypeDesc = _typeScope.GetTypeDesc(accessorType); if (accessor.TypeDesc.IsVoid) { throw new InvalidOperationException(SR.XmlInvalidVoid); } SoapAttributeFlags flags = a.SoapFlags; if ((flags & SoapAttributeFlags.Attribute) == SoapAttributeFlags.Attribute) { if (!accessor.TypeDesc.IsPrimitive && !accessor.TypeDesc.IsEnum) throw new InvalidOperationException(SR.Format(SR.XmlIllegalSoapAttribute, accessorName, accessor.TypeDesc.FullName)); if ((flags & SoapAttributeFlags.Attribute) != flags) throw new InvalidOperationException(SR.XmlInvalidElementAttribute); AttributeAccessor attribute = new AttributeAccessor(); attribute.Name = Accessor.EscapeQName(a.SoapAttribute == null || a.SoapAttribute.AttributeName.Length == 0 ? accessorName : a.SoapAttribute.AttributeName); attribute.Namespace = a.SoapAttribute == null || a.SoapAttribute.Namespace == null ? ns : a.SoapAttribute.Namespace; attribute.Form = XmlSchemaForm.Qualified; // attributes are always qualified since they're only used for encoded soap headers attribute.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(accessorType), (a.SoapAttribute == null ? String.Empty : a.SoapAttribute.DataType), limiter); attribute.Default = GetDefaultValue(model.FieldTypeDesc, a); accessor.Attribute = attribute; accessor.Elements = new ElementAccessor[0]; } else { if ((flags & SoapAttributeFlags.Element) != flags) throw new InvalidOperationException(SR.XmlInvalidElementAttribute); ElementAccessor element = new ElementAccessor(); element.IsSoap = true; element.Name = XmlConvert.EncodeLocalName(a.SoapElement == null || a.SoapElement.ElementName.Length == 0 ? accessorName : a.SoapElement.ElementName); element.Namespace = ns; element.Form = form; element.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(accessorType), (a.SoapElement == null ? String.Empty : a.SoapElement.DataType), limiter); if (a.SoapElement != null) element.IsNullable = a.SoapElement.IsNullable; accessor.Elements = new ElementAccessor[] { element }; } } private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string ns) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; element.Name = mapping.TypeName; //XmlConvert.EncodeLocalName(name == null || name.Length == 0 ? mapping.TypeName : name); element.Namespace = ns; element.Mapping = mapping; return element; } private object GetDefaultValue(TypeDesc fieldTypeDesc, SoapAttributes a) { if (a.SoapDefaultValue == null || a.SoapDefaultValue == DBNull.Value) return null; if (!(fieldTypeDesc.Kind == TypeKind.Primitive || fieldTypeDesc.Kind == TypeKind.Enum)) { a.SoapDefaultValue = null; return a.SoapDefaultValue; } // for enums validate and return a string representation if (fieldTypeDesc.Kind == TypeKind.Enum) { if (fieldTypeDesc != _typeScope.GetTypeDesc(a.SoapDefaultValue.GetType())) throw new InvalidOperationException(SR.Format(SR.XmlInvalidDefaultEnumValue, a.SoapDefaultValue.GetType().FullName, fieldTypeDesc.FullName)); string strValue = Enum.Format(a.SoapDefaultValue.GetType(), a.SoapDefaultValue, "G").Replace(",", " "); string numValue = Enum.Format(a.SoapDefaultValue.GetType(), a.SoapDefaultValue, "D"); if (strValue == numValue) // means enum value wasn't recognized throw new InvalidOperationException(SR.Format(SR.XmlInvalidDefaultValue, strValue, a.SoapDefaultValue.GetType().FullName)); return strValue; } return a.SoapDefaultValue; } internal string XsdTypeName(Type type) { if (type == typeof(object)) return Soap.UrType; TypeDesc typeDesc = _typeScope.GetTypeDesc(type); if (typeDesc.IsPrimitive && typeDesc.DataType != null && typeDesc.DataType.Name != null && typeDesc.DataType.Name.Length > 0) return typeDesc.DataType.Name; return XsdTypeName(type, GetAttributes(type), typeDesc.Name); } internal string XsdTypeName(Type type, SoapAttributes a, string name) { string typeName = name; if (a.SoapType != null && a.SoapType.TypeName.Length > 0) typeName = a.SoapType.TypeName; if (type.IsGenericType && typeName.IndexOf('{') >= 0) { Type genType = type.GetGenericTypeDefinition(); Type[] names = genType.GetGenericArguments(); Type[] types = type.GetGenericArguments(); for (int i = 0; i < names.Length; i++) { string argument = "{" + names[i] + "}"; if (typeName.Contains(argument)) { typeName = typeName.Replace(argument, XsdTypeName(types[i])); if (typeName.IndexOf('{') < 0) { break; } } } } // CONSIDER: throw if not all parameters were filled return typeName; } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents the schema for meeting requests. /// </summary> [Schema] public class MeetingRequestSchema : MeetingMessageSchema { /// <summary> /// Field URIs for MeetingRequest. /// </summary> private static class FieldUris { public const string MeetingRequestType = "meetingRequest:MeetingRequestType"; public const string IntendedFreeBusyStatus = "meetingRequest:IntendedFreeBusyStatus"; public const string ChangeHighlights = "meetingRequest:ChangeHighlights"; } /// <summary> /// Defines the MeetingRequestType property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MeetingRequestType = new GenericPropertyDefinition<MeetingRequestType>( XmlElementNames.MeetingRequestType, FieldUris.MeetingRequestType, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the IntendedFreeBusyStatus property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IntendedFreeBusyStatus = new GenericPropertyDefinition<LegacyFreeBusyStatus>( XmlElementNames.IntendedFreeBusyStatus, FieldUris.IntendedFreeBusyStatus, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the ChangeHighlights property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ChangeHighlights = new ComplexPropertyDefinition<ChangeHighlights>( XmlElementNames.ChangeHighlights, FieldUris.ChangeHighlights, ExchangeVersion.Exchange2013, delegate() { return new ChangeHighlights(); }); /// <summary> /// Enhanced Location property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition EnhancedLocation = AppointmentSchema.EnhancedLocation; /// <summary> /// Defines the Start property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Start = AppointmentSchema.Start; /// <summary> /// Defines the End property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition End = AppointmentSchema.End; /// <summary> /// Defines the OriginalStart property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition OriginalStart = AppointmentSchema.OriginalStart; /// <summary> /// Defines the IsAllDayEvent property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsAllDayEvent = AppointmentSchema.IsAllDayEvent; /// <summary> /// Defines the LegacyFreeBusyStatus property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition LegacyFreeBusyStatus = AppointmentSchema.LegacyFreeBusyStatus; /// <summary> /// Defines the Location property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Location = AppointmentSchema.Location; /// <summary> /// Defines the When property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition When = AppointmentSchema.When; /// <summary> /// Defines the IsMeeting property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsMeeting = AppointmentSchema.IsMeeting; /// <summary> /// Defines the IsCancelled property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsCancelled = AppointmentSchema.IsCancelled; /// <summary> /// Defines the IsRecurring property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsRecurring = AppointmentSchema.IsRecurring; /// <summary> /// Defines the MeetingRequestWasSent property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MeetingRequestWasSent = AppointmentSchema.MeetingRequestWasSent; /// <summary> /// Defines the AppointmentType property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AppointmentType = AppointmentSchema.AppointmentType; /// <summary> /// Defines the MyResponseType property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MyResponseType = AppointmentSchema.MyResponseType; /// <summary> /// Defines the Organizer property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Organizer = AppointmentSchema.Organizer; /// <summary> /// Defines the RequiredAttendees property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition RequiredAttendees = AppointmentSchema.RequiredAttendees; /// <summary> /// Defines the OptionalAttendees property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition OptionalAttendees = AppointmentSchema.OptionalAttendees; /// <summary> /// Defines the Resources property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Resources = AppointmentSchema.Resources; /// <summary> /// Defines the ConflictingMeetingCount property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ConflictingMeetingCount = AppointmentSchema.ConflictingMeetingCount; /// <summary> /// Defines the AdjacentMeetingCount property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AdjacentMeetingCount = AppointmentSchema.AdjacentMeetingCount; /// <summary> /// Defines the ConflictingMeetings property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ConflictingMeetings = AppointmentSchema.ConflictingMeetings; /// <summary> /// Defines the AdjacentMeetings property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AdjacentMeetings = AppointmentSchema.AdjacentMeetings; /// <summary> /// Defines the Duration property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Duration = AppointmentSchema.Duration; /// <summary> /// Defines the TimeZone property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition TimeZone = AppointmentSchema.TimeZone; /// <summary> /// Defines the AppointmentReplyTime property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AppointmentReplyTime = AppointmentSchema.AppointmentReplyTime; /// <summary> /// Defines the AppointmentSequenceNumber property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AppointmentSequenceNumber = AppointmentSchema.AppointmentSequenceNumber; /// <summary> /// Defines the AppointmentState property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AppointmentState = AppointmentSchema.AppointmentState; /// <summary> /// Defines the Recurrence property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Recurrence = AppointmentSchema.Recurrence; /// <summary> /// Defines the FirstOccurrence property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition FirstOccurrence = AppointmentSchema.FirstOccurrence; /// <summary> /// Defines the LastOccurrence property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition LastOccurrence = AppointmentSchema.LastOccurrence; /// <summary> /// Defines the ModifiedOccurrences property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ModifiedOccurrences = AppointmentSchema.ModifiedOccurrences; /// <summary> /// Defines the DeletedOccurrences property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition DeletedOccurrences = AppointmentSchema.DeletedOccurrences; /// <summary> /// Defines the MeetingTimeZone property. /// </summary> internal static readonly PropertyDefinition MeetingTimeZone = AppointmentSchema.MeetingTimeZone; /// <summary> /// Defines the StartTimeZone property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition StartTimeZone = AppointmentSchema.StartTimeZone; /// <summary> /// Defines the EndTimeZone property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition EndTimeZone = AppointmentSchema.EndTimeZone; /// <summary> /// Defines the ConferenceType property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ConferenceType = AppointmentSchema.ConferenceType; /// <summary> /// Defines the AllowNewTimeProposal property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AllowNewTimeProposal = AppointmentSchema.AllowNewTimeProposal; /// <summary> /// Defines the IsOnlineMeeting property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsOnlineMeeting = AppointmentSchema.IsOnlineMeeting; /// <summary> /// Defines the MeetingWorkspaceUrl property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MeetingWorkspaceUrl = AppointmentSchema.MeetingWorkspaceUrl; /// <summary> /// Defines the NetShowUrl property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition NetShowUrl = AppointmentSchema.NetShowUrl; // This must be after the declaration of property definitions internal static new readonly MeetingRequestSchema Instance = new MeetingRequestSchema(); /// <summary> /// Registers properties. /// </summary> /// <remarks> /// IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd) /// </remarks> internal override void RegisterProperties() { base.RegisterProperties(); this.RegisterProperty(MeetingRequestType); this.RegisterProperty(IntendedFreeBusyStatus); this.RegisterProperty(ChangeHighlights); this.RegisterProperty(Start); this.RegisterProperty(End); this.RegisterProperty(OriginalStart); this.RegisterProperty(IsAllDayEvent); this.RegisterProperty(LegacyFreeBusyStatus); this.RegisterProperty(Location); this.RegisterProperty(When); this.RegisterProperty(IsMeeting); this.RegisterProperty(IsCancelled); this.RegisterProperty(IsRecurring); this.RegisterProperty(MeetingRequestWasSent); this.RegisterProperty(AppointmentType); this.RegisterProperty(MyResponseType); this.RegisterProperty(Organizer); this.RegisterProperty(RequiredAttendees); this.RegisterProperty(OptionalAttendees); this.RegisterProperty(Resources); this.RegisterProperty(ConflictingMeetingCount); this.RegisterProperty(AdjacentMeetingCount); this.RegisterProperty(ConflictingMeetings); this.RegisterProperty(AdjacentMeetings); this.RegisterProperty(Duration); this.RegisterProperty(TimeZone); this.RegisterProperty(AppointmentReplyTime); this.RegisterProperty(AppointmentSequenceNumber); this.RegisterProperty(AppointmentState); this.RegisterProperty(Recurrence); this.RegisterProperty(FirstOccurrence); this.RegisterProperty(LastOccurrence); this.RegisterProperty(ModifiedOccurrences); this.RegisterProperty(DeletedOccurrences); this.RegisterInternalProperty(MeetingTimeZone); this.RegisterProperty(StartTimeZone); this.RegisterProperty(EndTimeZone); this.RegisterProperty(ConferenceType); this.RegisterProperty(AllowNewTimeProposal); this.RegisterProperty(IsOnlineMeeting); this.RegisterProperty(MeetingWorkspaceUrl); this.RegisterProperty(NetShowUrl); this.RegisterProperty(EnhancedLocation); } /// <summary> /// Initializes a new instance of the <see cref="MeetingRequestSchema"/> class. /// </summary> internal MeetingRequestSchema() : base() { } } }
using System; using System.Collections; using System.IO; using MSCLoader; using UnityEngine; //Standard unity MonoBehaviour class namespace MSCStill { public class ModBehaviour : MonoBehaviour { private AssetBundle m_bundle; private GameObject m_stillPrefab; private GameObject m_bottlePrefab; private GameObject m_buyerPrefab; public static AudioClipContainer buyerBottleReturn, buyerGreet, buyerPayment, buyerTaste, buyerTasteGood, buyerTasteMethanol, buyerTasteWater, buyerNoBuyWater, buyerNoBuyMethanol, buyerByeBye, buyerAsk, buyerStory; private GameObject m_drinkBottlePrefab; private Animation m_drinkHandAnimation; private Transform m_drinkHand; private GameObject m_drinkBottle; private Transform m_handBottles; private GameObject m_alcometerPrefab; void Awake() { Instance = this; try { SetupMod(); } catch (Exception e) { ModConsole.Error(e.ToString()); throw; } } void OnDestroy() { m_bundle.Unload(true); } private void SetupMod() { ModConsole.Print("Still mod loading assetbundle..."); var path = MSCStill.assetPath; if (SystemInfo.graphicsDeviceVersion.StartsWith("OpenGL") && Application.platform == RuntimePlatform.WindowsPlayer) path = Path.Combine(path, "bundle-linux"); // apparently fixes opengl else if (Application.platform == RuntimePlatform.WindowsPlayer) path = Path.Combine(path, "bundle-windows"); else if (Application.platform == RuntimePlatform.OSXPlayer) path = Path.Combine(path, "bundle-osx"); else if (Application.platform == RuntimePlatform.LinuxPlayer) path = Path.Combine(path, "bundle-linux"); if (!File.Exists(path)) { ModConsole.Error("Couldn't find asset bundle from path " + path); } else { m_bundle = AssetBundle.CreateFromMemoryImmediate(File.ReadAllBytes(path)); LoadAssets(); SetupGameObjects(); SetupBottle(); m_bundle.Unload(false); ModConsole.Print("Still mod Setup!"); } } private void SetupBottle() { ModConsole.Print("Setting up bottle..."); var bottle = (GameObject)Instantiate(m_bottlePrefab, new Vector3(-839, -2f, 505), Quaternion.identity); bottle.AddComponent<Bottle>(); } private void LoadAssets() { m_stillPrefab = m_bundle.LoadAssetWithSubAssets<GameObject>("StillPrefab")[0]; m_bottlePrefab = m_bundle.LoadAssetWithSubAssets<GameObject>("BottlePrefab")[0]; m_buyerPrefab = m_bundle.LoadAssetWithSubAssets<GameObject>("BuyerPrefab")[0]; m_drinkBottlePrefab = m_bundle.LoadAssetWithSubAssets<GameObject>("DrinkBottlePrefab")[0]; m_alcometerPrefab = m_bundle.LoadAssetWithSubAssets<GameObject>("AlcoholometerPrefab")[0]; buyerGreet = new AudioClipContainer(); buyerGreet.AddClip(m_bundle.LoadAsset<AudioClip>("Greet1")); buyerGreet.AddClip(m_bundle.LoadAsset<AudioClip>("Greet2")); buyerGreet.AddClip(m_bundle.LoadAsset<AudioClip>("Greet3")); buyerGreet.AddClip(m_bundle.LoadAsset<AudioClip>("Greet4")); buyerTaste = new AudioClipContainer(); buyerTaste.AddClip(m_bundle.LoadAsset<AudioClip>("TasteMoonshine1")); buyerTaste.AddClip(m_bundle.LoadAsset<AudioClip>("TasteMoonshine2")); buyerTaste.AddClip(m_bundle.LoadAsset<AudioClip>("TasteMoonshine3")); buyerTaste.AddClip(m_bundle.LoadAsset<AudioClip>("TasteMoonshine4")); buyerTasteGood = new AudioClipContainer(); buyerTasteGood.AddClip(m_bundle.LoadAsset<AudioClip>("Good1")); buyerTasteGood.AddClip(m_bundle.LoadAsset<AudioClip>("Good2")); buyerTasteGood.AddClip(m_bundle.LoadAsset<AudioClip>("Good3")); buyerPayment = new AudioClipContainer(); buyerPayment.AddClip(m_bundle.LoadAsset<AudioClip>("Payment1")); buyerPayment.AddClip(m_bundle.LoadAsset<AudioClip>("Payment2")); buyerPayment.AddClip(m_bundle.LoadAsset<AudioClip>("Payment3")); buyerPayment.AddClip(m_bundle.LoadAsset<AudioClip>("Payment4")); buyerTasteWater = new AudioClipContainer(); buyerTasteWater.AddClip(m_bundle.LoadAsset<AudioClip>("Water1")); buyerTasteWater.AddClip(m_bundle.LoadAsset<AudioClip>("Water2")); buyerTasteWater.AddClip(m_bundle.LoadAsset<AudioClip>("Water3")); buyerNoBuyWater = new AudioClipContainer(); buyerNoBuyWater.AddClip(m_bundle.LoadAsset<AudioClip>("NoBuyWater1")); buyerNoBuyWater.AddClip(m_bundle.LoadAsset<AudioClip>("NoBuyWater2")); buyerNoBuyWater.AddClip(m_bundle.LoadAsset<AudioClip>("NoBuyWater3")); buyerNoBuyWater.AddClip(m_bundle.LoadAsset<AudioClip>("NoBuyWater4")); buyerTasteMethanol = new AudioClipContainer(); buyerTasteMethanol.AddClip(m_bundle.LoadAsset<AudioClip>("Methanol1")); buyerTasteMethanol.AddClip(m_bundle.LoadAsset<AudioClip>("Methanol2")); buyerTasteMethanol.AddClip(m_bundle.LoadAsset<AudioClip>("Methanol3")); buyerNoBuyMethanol = new AudioClipContainer(); buyerNoBuyMethanol.AddClip(m_bundle.LoadAsset<AudioClip>("NoBuyMethanol1")); buyerNoBuyMethanol.AddClip(m_bundle.LoadAsset<AudioClip>("NoBuyMethanol2")); buyerNoBuyMethanol.AddClip(m_bundle.LoadAsset<AudioClip>("NoBuyMethanol3")); buyerBottleReturn = new AudioClipContainer(); buyerBottleReturn.AddClip(m_bundle.LoadAsset<AudioClip>("BottleReturn1")); buyerBottleReturn.AddClip(m_bundle.LoadAsset<AudioClip>("BottleReturn2")); buyerBottleReturn.AddClip(m_bundle.LoadAsset<AudioClip>("BottleReturn3")); buyerByeBye = new AudioClipContainer(); buyerByeBye.AddClip(m_bundle.LoadAsset<AudioClip>("Thanks1")); buyerByeBye.AddClip(m_bundle.LoadAsset<AudioClip>("Thanks2")); buyerByeBye.AddClip(m_bundle.LoadAsset<AudioClip>("Thanks3")); buyerAsk = new AudioClipContainer(); buyerAsk.AddClip(m_bundle.LoadAsset<AudioClip>("AskBring1")); buyerAsk.AddClip(m_bundle.LoadAsset<AudioClip>("AskBring2")); buyerAsk.AddClip(m_bundle.LoadAsset<AudioClip>("AskBring3")); buyerAsk.AddClip(m_bundle.LoadAsset<AudioClip>("AskBring4")); buyerStory = new AudioClipContainer(); buyerStory.AddClip(m_bundle.LoadAsset<AudioClip>("Story1")); buyerStory.AddClip(m_bundle.LoadAsset<AudioClip>("Story2")); } private void SetupGameObjects() { ModConsole.Print("Setting up still..."); var still = Instantiate(m_stillPrefab).AddComponent<Still>(); still.transform.position = new Vector3(-839, -3.15f, 504); ModConsole.Print("Setting up buyer..."); var buyer = Instantiate(m_buyerPrefab).AddComponent<Buyer>(); buyer.transform.position = new Vector3(-1527.8f, 5.158f, 1388.8f); buyer.transform.rotation = Quaternion.Euler(new Vector3(0, 270, 0)); ModConsole.Print("Setting up drink bottle..."); m_drinkHand = GameObject.Find("PLAYER/Pivot/Camera/FPSCamera/FPSCamera/Drink").transform.FindChild("Hand"); m_drinkHandAnimation = m_drinkHand.GetComponent<Animation>(); m_handBottles = m_drinkHand.transform.FindChild("HandBottles"); var beer = m_drinkHand.transform.FindChild("BeerBottle"); m_drinkBottle = Instantiate(m_drinkBottlePrefab); m_drinkBottle.transform.SetParent(beer.parent); m_drinkBottle.transform.localPosition = new Vector3(0.33f, 0.14f, 0f); m_drinkBottle.transform.localRotation = Quaternion.Euler(90f, 180f, 0f); m_drinkBottle.SetActive(false); ModConsole.Print("Setting up alcoholometer"); Instantiate(m_alcometerPrefab).AddComponent<Alcoholometer>(); } public void DrinkMoonshine() { StartCoroutine(Drink()); } private IEnumerator Drink() { m_handBottles.gameObject.SetActive(true); m_drinkBottle.SetActive(true); m_drinkHand.gameObject.SetActive(true); m_drinkHandAnimation.Play("drink_rotate"); yield return new WaitForSeconds(m_drinkHandAnimation.GetClip("drink_rotate").length); m_drinkBottle.SetActive(false); m_drinkHand.gameObject.SetActive(false); m_handBottles.gameObject.SetActive(false); } public static ModBehaviour Instance { get; set; } } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.Project.Automation { /// <summary> /// Contains ProjectItem objects /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ComVisible(true), CLSCompliant(false)] public class OAProjectItems : OANavigableProjectItems { #region ctor public OAProjectItems(OAProject project, HierarchyNode nodeWithItems) : base(project, nodeWithItems) { } #endregion #region EnvDTE.ProjectItems /// <summary> /// Creates a new project item from an existing item template file and adds it to the project. /// </summary> /// <param name="fileName">The full path and file name of the template project file.</param> /// <param name="name">The file name to use for the new project item.</param> /// <returns>A ProjectItem object. </returns> public override EnvDTE.ProjectItem AddFromTemplate(string fileName, string name) { if(this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed) { throw new InvalidOperationException(); } ProjectNode proj = this.Project.Project; EnvDTE.ProjectItem itemAdded = null; using(AutomationScope scope = new AutomationScope(this.Project.Project.Site)) { // Determine the operation based on the extension of the filename. // We should run the wizard only if the extension is vstemplate // otherwise it's a clone operation VSADDITEMOPERATION op; if(Utilities.IsTemplateFile(fileName)) { op = VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD; } else { op = VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE; } VSADDRESULT[] result = new VSADDRESULT[1]; // It is not a very good idea to throw since the AddItem might return Cancel or Abort. // The problem is that up in the call stack the wizard code does not check whether it has received a ProjectItem or not and will crash. // The other problem is that we cannot get add wizard dialog back if a cancel or abort was returned because we throw and that code will never be executed. Typical catch 22. ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, name, 0, new string[1] { fileName }, IntPtr.Zero, result)); string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems); string templateFilePath = System.IO.Path.Combine(fileDirectory, name); itemAdded = this.EvaluateAddResult(result[0], templateFilePath); } return itemAdded; } /// <summary> /// Adds a folder to the collection of ProjectItems with the given name. /// /// The kind must be null, empty string, or the string value of vsProjectItemKindPhysicalFolder. /// Virtual folders are not supported by this implementation. /// </summary> /// <param name="name">The name of the new folder to add</param> /// <param name="kind">A string representing a Guid of the folder kind.</param> /// <returns>A ProjectItem representing the newly added folder.</returns> public override ProjectItem AddFolder(string name, string kind) { if(this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed) { throw new InvalidOperationException(); } //Verify name is not null or empty Utilities.ValidateFileName(this.Project.Project.Site, name); //Verify that kind is null, empty, or a physical folder if(!(string.IsNullOrEmpty(kind) || kind.Equals(EnvDTE.Constants.vsProjectItemKindPhysicalFolder))) { throw new ArgumentException("Parameter specification for AddFolder was not meet", "kind"); } for(HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if(child.Caption.Equals(name, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Folder already exists with the name '{0}'", name)); } } ProjectNode proj = this.Project.Project; HierarchyNode newFolder = null; using(AutomationScope scope = new AutomationScope(this.Project.Project.Site)) { //In the case that we are adding a folder to a folder, we need to build up //the path to the project node. name = Path.Combine(this.NodeWithItems.VirtualNodeName, name); newFolder = proj.CreateFolderNodes(name); } return newFolder.GetAutomationObject() as ProjectItem; } /// <summary> /// Copies a source file and adds it to the project. /// </summary> /// <param name="filePath">The path and file name of the project item to be added.</param> /// <returns>A ProjectItem object. </returns> public override EnvDTE.ProjectItem AddFromFileCopy(string filePath) { return this.AddItem(filePath, VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE); } /// <summary> /// Adds a project item from a file that is installed in a project directory structure. /// </summary> /// <param name="fileName">The file name of the item to add as a project item. </param> /// <returns>A ProjectItem object. </returns> public override EnvDTE.ProjectItem AddFromFile(string fileName) { // TODO: VSADDITEMOP_LINKTOFILE return this.AddItem(fileName, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE); } #endregion #region helper methods /// <summary> /// Adds an item to the project. /// </summary> /// <param name="path">The full path of the item to add.</param> /// <param name="op">The <paramref name="VSADDITEMOPERATION"/> to use when adding the item.</param> /// <returns>A ProjectItem object. </returns> protected virtual EnvDTE.ProjectItem AddItem(string path, VSADDITEMOPERATION op) { if(this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed) { throw new InvalidOperationException(); } ProjectNode proj = this.Project.Project; EnvDTE.ProjectItem itemAdded = null; using(AutomationScope scope = new AutomationScope(this.Project.Project.Site)) { VSADDRESULT[] result = new VSADDRESULT[1]; ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, path, 0, new string[1] { path }, IntPtr.Zero, result)); string fileName = System.IO.Path.GetFileName(path); string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems); string filePathInProject = System.IO.Path.Combine(fileDirectory, fileName); itemAdded = this.EvaluateAddResult(result[0], filePathInProject); } return itemAdded; } /// <summary> /// Evaluates the result of an add operation. /// </summary> /// <param name="result">The <paramref name="VSADDRESULT"/> returned by the Add methods</param> /// <param name="path">The full path of the item added.</param> /// <returns>A ProjectItem object.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] protected virtual EnvDTE.ProjectItem EvaluateAddResult(VSADDRESULT result, string path) { if(result == VSADDRESULT.ADDRESULT_Success) { HierarchyNode nodeAdded = this.NodeWithItems.FindChild(path); Debug.Assert(nodeAdded != null, "We should have been able to find the new element in the hierarchy"); if(nodeAdded != null) { EnvDTE.ProjectItem item = null; if(nodeAdded is FileNode) { item = new OAFileItem(this.Project, nodeAdded as FileNode); } else if(nodeAdded is NestedProjectNode) { item = new OANestedProjectItem(this.Project, nodeAdded as NestedProjectNode); } else { item = new OAProjectItem<HierarchyNode>(this.Project, nodeAdded); } this.Items.Add(item); return item; } } return null; } #endregion } }
using System; using System.Collections; using System.Text; using Raksha.Asn1.IsisMtt; using Raksha.Asn1; using Raksha.Asn1.X509; using Raksha.Asn1.X500; using Raksha.Crypto; using Raksha.Crypto.Parameters; using Raksha.Math; using Raksha.Security.Certificates; using Raksha.Utilities; using Raksha.Utilities.Collections; using Raksha.X509; using Raksha.X509.Store; namespace Raksha.Pkix { /** * Implements the PKIX CertPathBuilding algorithm for BouncyCastle. * * @see CertPathBuilderSpi */ public class PkixCertPathBuilder // : CertPathBuilderSpi { /** * Build and validate a CertPath using the given parameter. * * @param params PKIXBuilderParameters object containing all information to * build the CertPath */ public virtual PkixCertPathBuilderResult Build( PkixBuilderParameters pkixParams) { // search target certificates IX509Selector certSelect = pkixParams.GetTargetCertConstraints(); if (!(certSelect is X509CertStoreSelector)) { throw new PkixCertPathBuilderException( "TargetConstraints must be an instance of " + typeof(X509CertStoreSelector).FullName + " for " + this.GetType() + " class."); } ISet targets = new HashSet(); try { targets.AddAll(PkixCertPathValidatorUtilities.FindCertificates((X509CertStoreSelector)certSelect, pkixParams.GetStores())); // TODO Should this include an entry for pkixParams.GetAdditionalStores() too? } catch (Exception e) { throw new PkixCertPathBuilderException( "Error finding target certificate.", e); } if (targets.IsEmpty) throw new PkixCertPathBuilderException("No certificate found matching targetContraints."); PkixCertPathBuilderResult result = null; IList certPathList = Platform.CreateArrayList(); // check all potential target certificates foreach (X509Certificate cert in targets) { result = Build(cert, pkixParams, certPathList); if (result != null) break; } if (result == null && certPathException != null) { throw new PkixCertPathBuilderException(certPathException.Message, certPathException.InnerException); } if (result == null && certPathException == null) { throw new PkixCertPathBuilderException("Unable to find certificate chain."); } return result; } private Exception certPathException; protected virtual PkixCertPathBuilderResult Build( X509Certificate tbvCert, PkixBuilderParameters pkixParams, IList tbvPath) { // If tbvCert is readily present in tbvPath, it indicates having run // into a cycle in the PKI graph. if (tbvPath.Contains(tbvCert)) return null; // step out, the certificate is not allowed to appear in a certification // chain. if (pkixParams.GetExcludedCerts().Contains(tbvCert)) return null; // test if certificate path exceeds maximum length if (pkixParams.MaxPathLength != -1) { if (tbvPath.Count - 1 > pkixParams.MaxPathLength) return null; } tbvPath.Add(tbvCert); // X509CertificateParser certParser = new X509CertificateParser(); PkixCertPathBuilderResult builderResult = null; PkixCertPathValidator validator = new PkixCertPathValidator(); try { // check whether the issuer of <tbvCert> is a TrustAnchor if (PkixCertPathValidatorUtilities.FindTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()) != null) { // exception message from possibly later tried certification // chains PkixCertPath certPath = null; try { certPath = new PkixCertPath(tbvPath); } catch (Exception e) { throw new Exception( "Certification path could not be constructed from certificate list.", e); } PkixCertPathValidatorResult result = null; try { result = (PkixCertPathValidatorResult)validator.Validate( certPath, pkixParams); } catch (Exception e) { throw new Exception( "Certification path could not be validated.", e); } return new PkixCertPathBuilderResult(certPath, result.TrustAnchor, result.PolicyTree, result.SubjectPublicKey); } else { // add additional X.509 stores from locations in certificate try { PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames( tbvCert, pkixParams); } catch (CertificateParsingException e) { throw new Exception( "No additiontal X.509 stores can be added from certificate locations.", e); } // try to get the issuer certificate from one of the stores HashSet issuers = new HashSet(); try { issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams)); } catch (Exception e) { throw new Exception( "Cannot find issuer certificate for certificate in certification path.", e); } if (issuers.IsEmpty) throw new Exception("No issuer certificate for certificate in certification path found."); foreach (X509Certificate issuer in issuers) { builderResult = Build(issuer, pkixParams, tbvPath); if (builderResult != null) break; } } } catch (Exception e) { certPathException = e; } if (builderResult == null) { tbvPath.Remove(tbvCert); } return builderResult; } } }
// 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.Security.Cryptography; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates.Asn1; namespace Internal.Cryptography.Pal { internal class ManagedX509ExtensionProcessor { public virtual byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages) { // The numeric values of X509KeyUsageFlags mean that if we interpret it as a little-endian // ushort it will line up with the flags in the spec. We flip bit order of each byte to get // the KeyUsageFlagsAsn order expected by AsnWriter. KeyUsageFlagsAsn keyUsagesAsn = (KeyUsageFlagsAsn)ReverseBitOrder((byte)keyUsages) | (KeyUsageFlagsAsn)(ReverseBitOrder((byte)(((ushort)keyUsages >> 8))) << 8); // The expected output of this method isn't the SEQUENCE value, but just the payload bytes. using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { writer.WriteNamedBitList(keyUsagesAsn); return writer.Encode(); } } public virtual void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages) { AsnReader reader = new AsnReader(encoded, AsnEncodingRules.BER); KeyUsageFlagsAsn keyUsagesAsn = reader.ReadNamedBitListValue<KeyUsageFlagsAsn>(); reader.ThrowIfNotEmpty(); // DER encodings of BIT_STRING values number the bits as // 01234567 89 (big endian), plus a number saying how many bits of the last byte were padding. // // So digitalSignature (0) doesn't mean 2^0 (0x01), it means the most significant bit // is set in this byte stream. // // BIT_STRING values are compact. So a value of cRLSign (6) | keyEncipherment (2), which // is 0b0010001 => 0b0010 0010 (1 bit padding) => 0x22 encoded is therefore // 0x02 (length remaining) 0x01 (1 bit padding) 0x22. // // We will read that, and return 0x22. 0x22 lines up // exactly with X509KeyUsageFlags.CrlSign (0x20) | X509KeyUsageFlags.KeyEncipherment (0x02) // // Once the decipherOnly (8) bit is added to the mix, the values become: // 0b001000101 => 0b0010 0010 1000 0000 (7 bits padding) // { 0x03 0x07 0x22 0x80 } // And we read new byte[] { 0x22 0x80 } // // The value of X509KeyUsageFlags.DecipherOnly is 0x8000. 0x8000 in a little endian // representation is { 0x00 0x80 }. This means that the DER storage mechanism has effectively // ended up being little-endian for BIT_STRING values. Untwist the bytes, and now the bits all // line up with the existing X509KeyUsageFlags. keyUsages = (X509KeyUsageFlags)ReverseBitOrder((byte)keyUsagesAsn) | (X509KeyUsageFlags)(ReverseBitOrder((byte)(((ushort)keyUsagesAsn >> 8))) << 8); } public virtual byte[] EncodeX509BasicConstraints2Extension( bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) { BasicConstraintsAsn constraints = new BasicConstraintsAsn(); constraints.CA = certificateAuthority; if (hasPathLengthConstraint) constraints.PathLengthConstraint = pathLengthConstraint; using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { constraints.Encode(writer); return writer.Encode(); } } public virtual bool SupportsLegacyBasicConstraintsExtension => false; public virtual void DecodeX509BasicConstraintsExtension( byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { // No RFC nor ITU document describes the layout of the 2.5.29.10 structure, // and OpenSSL doesn't have a decoder for it, either. // // Since it was never published as a standard (2.5.29.19 replaced it before publication) // there shouldn't be too many people upset that we can't decode it for them on Unix. throw new PlatformNotSupportedException(SR.NotSupported_LegacyBasicConstraints); } public virtual void DecodeX509BasicConstraints2Extension( byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { BasicConstraintsAsn constraints = BasicConstraintsAsn.Decode(encoded, AsnEncodingRules.BER); certificateAuthority = constraints.CA; hasPathLengthConstraint = constraints.PathLengthConstraint.HasValue; pathLengthConstraint = constraints.PathLengthConstraint.GetValueOrDefault(); } public virtual byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages) { // https://tools.ietf.org/html/rfc5280#section-4.2.1.12 // // extKeyUsage EXTENSION ::= { // SYNTAX SEQUENCE SIZE(1..MAX) OF KeyPurposeId // IDENTIFIED BY id-ce-extKeyUsage // } // // KeyPurposeId ::= OBJECT IDENTIFIER using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { writer.PushSequence(); foreach (Oid usage in usages) { writer.WriteObjectIdentifier(usage); } writer.PopSequence(); return writer.Encode(); } } public virtual void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { // https://tools.ietf.org/html/rfc5924#section-4.1 // // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId // // KeyPurposeId ::= OBJECT IDENTIFIER AsnReader reader = new AsnReader(encoded, AsnEncodingRules.BER); AsnReader sequenceReader = reader.ReadSequence(); reader.ThrowIfNotEmpty(); usages = new OidCollection(); while (sequenceReader.HasData) { usages.Add(sequenceReader.ReadObjectIdentifier()); } } public virtual byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier) { // https://tools.ietf.org/html/rfc5280#section-4.2.1.2 // // subjectKeyIdentifier EXTENSION ::= { // SYNTAX SubjectKeyIdentifier // IDENTIFIED BY id - ce - subjectKeyIdentifier // } // // SubjectKeyIdentifier::= KeyIdentifier // // KeyIdentifier ::= OCTET STRING using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { writer.WriteOctetString(subjectKeyIdentifier); return writer.Encode(); } } public virtual void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier) { subjectKeyIdentifier = DecodeX509SubjectKeyIdentifierExtension(encoded); } internal static byte[] DecodeX509SubjectKeyIdentifierExtension(byte[] encoded) { AsnReader reader = new AsnReader(encoded, AsnEncodingRules.BER); ReadOnlyMemory<byte> contents; if (!reader.TryReadPrimitiveOctetStringBytes(out contents)) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } reader.ThrowIfNotEmpty(); return contents.ToArray(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 is required for Compat")] public virtual byte[] ComputeCapiSha1OfPublicKey(PublicKey key) { // The CapiSha1 value is the SHA-1 of the SubjectPublicKeyInfo field, inclusive // of the DER structural bytes. SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn(); spki.Algorithm = new AlgorithmIdentifierAsn { Algorithm = key.Oid, Parameters = key.EncodedParameters.RawData }; spki.SubjectPublicKey = key.EncodedKeyValue.RawData; using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) using (SHA1 hash = SHA1.Create()) { spki.Encode(writer); return hash.ComputeHash(writer.Encode()); } } private static byte ReverseBitOrder(byte b) { return (byte)(unchecked(b * 0x0202020202ul & 0x010884422010ul) % 1023); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementSingle0() { var test = new VectorGetAndWithElement__GetAndWithElementSingle0(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementSingle0 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Single[] values = new Single[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSingle(); } Vector64<Single> value = Vector64.Create(values[0], values[1]); bool succeeded = !expectedOutOfRangeException; try { Single result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Single.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Single insertedValue = TestLibrary.Generator.GetSingle(); try { Vector64<Single> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Single.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Single[] values = new Single[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSingle(); } Vector64<Single> value = Vector64.Create(values[0], values[1]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector64) .GetMethod(nameof(Vector64.GetElement)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Single)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Single.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Single insertedValue = TestLibrary.Generator.GetSingle(); try { object result2 = typeof(Vector64) .GetMethod(nameof(Vector64.WithElement)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector64<Single>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Single.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Single result, Single[] values, [CallerMemberName] string method = "") { if (result != values[0]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector64<Single.GetElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector64<Single> result, Single[] values, Single insertedValue, [CallerMemberName] string method = "") { Single[] resultElements = new Single[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Single[] result, Single[] values, Single insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 0) && (result[i] != values[i])) { succeeded = false; break; } } if (result[0] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Single.WithElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
//#define REREAD_STATE_AFTER_WRITE_FAILED using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Xunit; using Xunit.Abstractions; using Orleans; using Orleans.Hosting; using Orleans.Runtime; using Orleans.TestingHost; using Orleans.Providers; using Orleans.Persistence.AzureStorage; using TestExtensions; using TestExtensions.Runners; using UnitTests.GrainInterfaces; // ReSharper disable RedundantAssignment // ReSharper disable UnusedVariable // ReSharper disable InconsistentNaming namespace Tester.AzureUtils.Persistence { /// <summary> /// Base_PersistenceGrainTests - a base class for testing persistence providers /// </summary> public abstract class Base_PersistenceGrainTests_AzureStore : OrleansTestingBase { private readonly ITestOutputHelper output; protected TestCluster HostedCluster { get; private set; } private readonly double timingFactor; protected readonly ILogger logger; private const int LoopIterations_Grain = 1000; private const int BatchSize = 100; private GrainPersistenceTestsRunner basicPersistenceTestsRunner; private const int MaxReadTime = 200; private const int MaxWriteTime = 2000; public class SiloBuilderConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.UseAzureStorageClustering(options => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; options.MaxStorageBusyRetries = 3; }); } } public class ClientBuilderConfigurator : IClientBuilderConfigurator { public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { clientBuilder.UseAzureStorageClustering(gatewayOptions => { gatewayOptions.ConnectionString = TestDefaultConfiguration.DataConnectionString; }); } } public static IProviderConfiguration GetNamedProviderConfigForShardedProvider(IEnumerable<KeyValuePair<string, IProviderConfiguration>> providers, string providerName) { var providerConfig = providers.Where(o => o.Key.Equals(providerName)).Select(o => o.Value); return providerConfig.First(); } public Base_PersistenceGrainTests_AzureStore(ITestOutputHelper output, BaseTestClusterFixture fixture, Guid serviceId) { this.output = output; this.logger = fixture.Logger; HostedCluster = fixture.HostedCluster; GrainFactory = fixture.GrainFactory; timingFactor = TestUtils.CalibrateTimings(); this.basicPersistenceTestsRunner = new GrainPersistenceTestsRunner(output, fixture, serviceId); } public IGrainFactory GrainFactory { get; } protected Task Grain_AzureStore_Delete() { return this.basicPersistenceTestsRunner.Grain_GrainStorage_Delete(); } protected Task Grain_AzureStore_Read() { return this.basicPersistenceTestsRunner.Grain_GrainStorage_Read(); } protected Task Grain_GuidKey_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_GuidKey_GrainStorage_Read_Write(); } protected Task Grain_LongKey_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_LongKey_GrainStorage_Read_Write(); } protected Task Grain_LongKeyExtended_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_LongKeyExtended_GrainStorage_Read_Write(); } protected Task Grain_GuidKeyExtended_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_GuidKeyExtended_GrainStorage_Read_Write(); } protected Task Grain_Generic_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_Generic_GrainStorage_Read_Write(); } protected Task Grain_Generic_AzureStore_DiffTypes() { return this.basicPersistenceTestsRunner.Grain_Generic_GrainStorage_DiffTypes(); } protected Task Grain_AzureStore_SiloRestart() { return this.basicPersistenceTestsRunner.Grain_GrainStorage_SiloRestart(); } protected void Persistence_Perf_Activate() { const string testName = "Persistence_Perf_Activate"; int n = LoopIterations_Grain; TimeSpan target = TimeSpan.FromMilliseconds(MaxReadTime * n); // Timings for Activate RunPerfTest(n, testName, target, grainNoState => grainNoState.PingAsync(), grainMemory => grainMemory.DoSomething(), grainMemoryStore => grainMemoryStore.GetValue(), grainAzureStore => grainAzureStore.GetValue()); } protected void Persistence_Perf_Write() { const string testName = "Persistence_Perf_Write"; int n = LoopIterations_Grain; TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n); // Timings for Write RunPerfTest(n, testName, target, grainNoState => grainNoState.EchoAsync(testName), grainMemory => grainMemory.DoWrite(n), grainMemoryStore => grainMemoryStore.DoWrite(n), grainAzureStore => grainAzureStore.DoWrite(n)); } protected void Persistence_Perf_Write_Reread() { const string testName = "Persistence_Perf_Write_Read"; int n = LoopIterations_Grain; TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n); // Timings for Write RunPerfTest(n, testName + "--Write", target, grainNoState => grainNoState.EchoAsync(testName), grainMemory => grainMemory.DoWrite(n), grainMemoryStore => grainMemoryStore.DoWrite(n), grainAzureStore => grainAzureStore.DoWrite(n)); // Timings for Activate RunPerfTest(n, testName + "--ReRead", target, grainNoState => grainNoState.GetLastEchoAsync(), grainMemory => grainMemory.DoRead(), grainMemoryStore => grainMemoryStore.DoRead(), grainAzureStore => grainAzureStore.DoRead()); } protected async Task Persistence_Silo_StorageProvider_Azure(string providerName) { List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList(); foreach (var silo in silos) { var testHooks = this.HostedCluster.Client.GetTestHooks(silo); List<string> providers = (await testHooks.GetStorageProviderNames()).ToList(); Assert.True(providers.Contains(providerName), $"No storage provider found: {providerName}"); } } #region Utility functions // ---------- Utility functions ---------- protected void RunPerfTest(int n, string testName, TimeSpan target, Func<IEchoTaskGrain, Task> actionNoState, Func<IPersistenceTestGrain, Task> actionMemory, Func<IMemoryStorageTestGrain, Task> actionMemoryStore, Func<IGrainStorageTestGrain, Task> actionAzureTable) { IEchoTaskGrain[] noStateGrains = new IEchoTaskGrain[n]; IPersistenceTestGrain[] memoryGrains = new IPersistenceTestGrain[n]; IGrainStorageTestGrain[] azureStoreGrains = new IGrainStorageTestGrain[n]; IMemoryStorageTestGrain[] memoryStoreGrains = new IMemoryStorageTestGrain[n]; for (int i = 0; i < n; i++) { Guid id = Guid.NewGuid(); noStateGrains[i] = this.GrainFactory.GetGrain<IEchoTaskGrain>(id); memoryGrains[i] = this.GrainFactory.GetGrain<IPersistenceTestGrain>(id); azureStoreGrains[i] = this.GrainFactory.GetGrain<IGrainStorageTestGrain>(id); memoryStoreGrains[i] = this.GrainFactory.GetGrain<IMemoryStorageTestGrain>(id); } TimeSpan baseline, elapsed; elapsed = baseline = TestUtils.TimeRun(n, TimeSpan.Zero, testName + " (No state)", () => RunIterations(testName, n, i => actionNoState(noStateGrains[i]))); elapsed = TestUtils.TimeRun(n, baseline, testName + " (Local Memory Store)", () => RunIterations(testName, n, i => actionMemory(memoryGrains[i]))); elapsed = TestUtils.TimeRun(n, baseline, testName + " (Dev Store Grain Store)", () => RunIterations(testName, n, i => actionMemoryStore(memoryStoreGrains[i]))); elapsed = TestUtils.TimeRun(n, baseline, testName + " (Azure Table Store)", () => RunIterations(testName, n, i => actionAzureTable(azureStoreGrains[i]))); if (elapsed > target.Multiply(timingFactor)) { string msg = string.Format("{0}: Elapsed time {1} exceeds target time {2}", testName, elapsed, target); if (elapsed > target.Multiply(2.0 * timingFactor)) { Assert.True(false, msg); } else { throw new SkipException(msg); } } } private void RunIterations(string testName, int n, Func<int, Task> action) { List<Task> promises = new List<Task>(); Stopwatch sw = Stopwatch.StartNew(); // Fire off requests in batches for (int i = 0; i < n; i++) { var promise = action(i); promises.Add(promise); if ((i % BatchSize) == 0 && i > 0) { Task.WaitAll(promises.ToArray(), AzureTableDefaultPolicies.TableCreationTimeout); promises.Clear(); //output.WriteLine("{0} has done {1} iterations in {2} at {3} RPS", // testName, i, sw.Elapsed, i / sw.Elapsed.TotalSeconds); } } Task.WaitAll(promises.ToArray(), AzureTableDefaultPolicies.TableCreationTimeout); sw.Stop(); output.WriteLine("{0} completed. Did {1} iterations in {2} at {3} RPS", testName, n, sw.Elapsed, n / sw.Elapsed.TotalSeconds); } #endregion } } // ReSharper restore RedundantAssignment // ReSharper restore UnusedVariable // ReSharper restore InconsistentNaming
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using Xunit; namespace System.Globalization.CalendarTests { // GregorianCalendar.ToDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32) public class GregorianCalendarToDateTime { private const int c_DAYS_IN_LEAP_YEAR = 366; private const int c_DAYS_IN_COMMON_YEAR = 365; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private static readonly int[] s_daysInMonth365 = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private static readonly int[] s_daysInMonth366 = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; #region Positive tests // PosTest1: random valid date time [Fact] public void PosTest1() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = this.GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; //value of month between 1 - 12 //value of day between 1 - last day of month int day = (this.IsLeapYear(year)) ? _generator.GetInt32(-55) % s_daysInMonth366[month] + 1 : _generator.GetInt32(-55) % s_daysInMonth365[month] + 1; int hour = _generator.GetInt32(-55) % 24; //value of hour between 0 - 23 int minute = _generator.GetInt32(-55) % 60; //value of minute between 0 - 59 int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecutePosTest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // PosTest2: the mininum valid date time value [Fact] public void PosTest2() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = 1; int month = 1; int day = 1; int hour = 0; int minute = 0; int second = 0; int millisecond = 0; int era = _generator.GetInt32(-55) & 1; ExecutePosTest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // PosTest3: the maximum valid date time value [Fact] public void PosTest3() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = 9999; int month = 12; int day = 31; int hour = 23; int minute = 59; int second = 59; int millisecond = 999; int era = _generator.GetInt32(-55) & 1; ExecutePosTest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } #endregion #region Helper method for positive tests private void ExecutePosTest(Calendar myCalendar, int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { DateTime actualTime, expectedTime; expectedTime = new DateTime(year, month, day, hour, minute, second, millisecond); actualTime = myCalendar.ToDateTime(year, month, day, hour, minute, second, millisecond, era); Assert.Equal(expectedTime, actualTime); } #endregion #region Negtive Tests // NegTest1: year is greater than maximum supported value [Fact] public void NegTest1() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = myCalendar.MaxSupportedDateTime.Year + 1 + _generator.GetInt32(-55) % (int.MaxValue - myCalendar.MaxSupportedDateTime.Year); int month = _generator.GetInt32(-55) % 12 + 1; //value of month between 1 - 12 int day = 1; int hour = _generator.GetInt32(-55) % 24; //value of hour between 0 - 23 int minute = _generator.GetInt32(-55) % 60; //value of minute between 0 - 59 int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest2: year is less than minimum supported value [Fact] public void NegTest2() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = -1 * _generator.GetInt32(-55); int month = _generator.GetInt32(-55) % 12 + 1; //value of month between 1 - 12 int day = 1; int hour = _generator.GetInt32(-55) % 24; //value of hour between 0 - 23 int minute = _generator.GetInt32(-55) % 60; //value of minute between 0 - 59 int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest3: month is greater than maximum supported value [Fact] public void NegTest3() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = 13 + _generator.GetInt32(-55) % (int.MaxValue - 12); int day = 1; int hour = _generator.GetInt32(-55) % 24; //value of hour between 0 - 23 int minute = _generator.GetInt32(-55) % 60; //value of minute between 0 - 59 int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest4: month is less than minimum supported value [Fact] public void NegTest4() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = -1 * _generator.GetInt32(-55); int day = 1; int hour = _generator.GetInt32(-55) % 24; //value of hour between 0 - 23 int minute = _generator.GetInt32(-55) % 60; //value of minute between 0 - 59 int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest5: day is greater than maximum supported value [Fact] public void NegTest5() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = (this.IsLeapYear(year)) ? s_daysInMonth366[month] + 1 + _generator.GetInt32(-55) % (int.MaxValue - s_daysInMonth366[month]) : s_daysInMonth365[month] + 1 + _generator.GetInt32(-55) % (int.MaxValue - s_daysInMonth365[month]); int hour = _generator.GetInt32(-55) % 24; //value of hour between 0 - 23 int minute = _generator.GetInt32(-55) % 60; //value of minute between 0 - 59 int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest6: day is less than minimum supported value [Fact] public void NegTest6() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = -1 * _generator.GetInt32(-55); int hour = _generator.GetInt32(-55) % 24; //value of hour between 0 - 23 int minute = _generator.GetInt32(-55) % 60; //value of minute between 0 - 59 int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest7: hour is greater than maximum supported value [Fact] public void NegTest7() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = 24 + _generator.GetInt32(-55) % (int.MaxValue - 23); int minute = _generator.GetInt32(-55) % 60; //value of minute between 0 - 59 int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest8: hour is greater than maximum supported value [Fact] public void NegTest8() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = -1 * _generator.GetInt32(-55) - 1; int minute = _generator.GetInt32(-55) % 60; //value of minute between 0 - 59 int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest9: minute is greater than maximum supported value [Fact] public void NegTest9() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = _generator.GetInt32(-55) % 24; int minute = 60 + _generator.GetInt32(-55) % (int.MaxValue - 59); int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest10: minute is less than minimum supported value [Fact] public void NegTest10() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = _generator.GetInt32(-55) % 24; int minute = -1 * _generator.GetInt32(-55) - 1; int second = _generator.GetInt32(-55) % 60; //value of second between 0 - 59 int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest11: second is greater than maximum supported value [Fact] public void NegTest11() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = _generator.GetInt32(-55) % 24; int minute = _generator.GetInt32(-55) % 60; int second = 60 + _generator.GetInt32(-55) % (int.MaxValue - 59); int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest12: second is less than minimum supported value [Fact] public void NegTest12() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = _generator.GetInt32(-55) % 24; int minute = _generator.GetInt32(-55) % 60; int second = -1 * _generator.GetInt32(-55) - 1; int millisecond = _generator.GetInt32(-55) % 1000; //value of millisecond between 0 - 999 int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest13: millisecond is greater than maximum supported value [Fact] public void NegTest13() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = _generator.GetInt32(-55) % 24; int minute = _generator.GetInt32(-55) % 60; int second = _generator.GetInt32(-55) % 60; int millisecond = 1000 + _generator.GetInt32(-55) % (int.MaxValue - 999); int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest14: millisecond is less than minimum supported value [Fact] public void NegTest14() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = _generator.GetInt32(-55) % 24; int minute = _generator.GetInt32(-55) % 60; int second = _generator.GetInt32(-55) % 60; int millisecond = -1 * _generator.GetInt32(-55) - 1; int era = _generator.GetInt32(-55) & 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest15: era is greater than maximum supported value [Fact] public void NegTest15() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = _generator.GetInt32(-55) % 24; int minute = _generator.GetInt32(-55) % 60; int second = _generator.GetInt32(-55) % 60; int millisecond = _generator.GetInt32(-55) % 1000; int era = 2 + _generator.GetInt32(-55) % (int.MaxValue - 1); ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } // NegTest16: era is less than minimum supported value [Fact] public void NegTest16() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year = GetAYear(myCalendar); int month = _generator.GetInt32(-55) % 12 + 1; int day = 1; int hour = _generator.GetInt32(-55) % 24; int minute = _generator.GetInt32(-55) % 60; int second = _generator.GetInt32(-55) % 60; int millisecond = _generator.GetInt32(-55) % 1000; int era = -1 * _generator.GetInt32(-55) - 1; ExecuteAOORETest(myCalendar, year, month, day, hour, minute, second, millisecond, era); } #endregion #region Helper methods for negtative tests private void ExecuteAOORETest(Calendar myCalendar, int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { Assert.Throws<ArgumentOutOfRangeException>(() => { myCalendar.ToDateTime(year, month, day, hour, minute, second, millisecond, era); }); } #endregion #region Helper methods for all the tests //Indicate whether the specified year is leap year or not private bool IsLeapYear(int year) { if (0 == year % 400 || (0 != year % 100 && 0 == (year & 0x3))) { return true; } return false; } //Get a random year beween minmum supported year and maximum supported year of the specified calendar private int GetAYear(Calendar calendar) { int retVal; int maxYear, minYear; maxYear = calendar.MaxSupportedDateTime.Year; minYear = calendar.MinSupportedDateTime.Year; retVal = minYear + _generator.GetInt32(-55) % (maxYear + 1 - minYear); return retVal; } //Get a leap year of the specified calendar private int GetALeapYear(Calendar calendar) { int retVal; // A leap year is any year divisible by 4 except for centennial years(those ending in 00) // which are only leap years if they are divisible by 400. retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0 retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400 // if retVal was 100, 200, or 300 the above logic will result in 0 if (0 == retVal) { retVal = 400; } return retVal; } //Get a common year of the specified calendar private int GetACommonYear(Calendar calendar) { int retVal; do { retVal = GetAYear(calendar); } while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400); return retVal; } #endregion } }
// // RuleType.cs.cs // // This file was generated by XMLSPY 2004 Enterprise Edition. // // YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE // OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. // // Refer to the XMLSPY Documentation for further details. // http://www.altova.com/xmlspy // using System; using System.Collections; using System.Xml; using Altova.Types; namespace XMLRules { public class RuleType : Altova.Node { #region Forward constructors public RuleType() : base() { SetCollectionParents(); } public RuleType(XmlDocument doc) : base(doc) { SetCollectionParents(); } public RuleType(XmlNode node) : base(node) { SetCollectionParents(); } public RuleType(Altova.Node node) : base(node) { SetCollectionParents(); } #endregion // Forward constructors public override void AdjustPrefix() { int nCount; nCount = DomChildCount(NodeType.Element, "", "Name"); for (int i = 0; i < nCount; i++) { XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Name", i); InternalAdjustPrefix(DOMNode, true); } nCount = DomChildCount(NodeType.Element, "", "Condition"); for (int i = 0; i < nCount; i++) { XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Condition", i); InternalAdjustPrefix(DOMNode, true); new LogicalExpression(DOMNode).AdjustPrefix(); } nCount = DomChildCount(NodeType.Element, "", "Action"); for (int i = 0; i < nCount; i++) { XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Action", i); InternalAdjustPrefix(DOMNode, true); new ActionType(DOMNode).AdjustPrefix(); } nCount = DomChildCount(NodeType.Element, "", "Priority"); for (int i = 0; i < nCount; i++) { XmlNode DOMNode = GetDomChildAt(NodeType.Element, "", "Priority", i); InternalAdjustPrefix(DOMNode, true); } } #region Name accessor methods public int GetNameMinCount() { return 1; } public int NameMinCount { get { return 1; } } public int GetNameMaxCount() { return 1; } public int NameMaxCount { get { return 1; } } public int GetNameCount() { return DomChildCount(NodeType.Element, "", "Name"); } public int NameCount { get { return DomChildCount(NodeType.Element, "", "Name"); } } public bool HasName() { return HasDomChild(NodeType.Element, "", "Name"); } public SchemaString GetNameAt(int index) { return new SchemaString(GetDomNodeValue(GetDomChildAt(NodeType.Element, "", "Name", index))); } public SchemaString GetName() { return GetNameAt(0); } public SchemaString Name { get { return GetNameAt(0); } } public void RemoveNameAt(int index) { RemoveDomChildAt(NodeType.Element, "", "Name", index); } public void RemoveName() { while (HasName()) RemoveNameAt(0); } public void AddName(SchemaString newValue) { AppendDomChild(NodeType.Element, "", "Name", newValue.ToString()); } public void InsertNameAt(SchemaString newValue, int index) { InsertDomChildAt(NodeType.Element, "", "Name", index, newValue.ToString()); } public void ReplaceNameAt(SchemaString newValue, int index) { ReplaceDomChildAt(NodeType.Element, "", "Name", index, newValue.ToString()); } #endregion // Name accessor methods #region Name collection public NameCollection MyNames = new NameCollection( ); public class NameCollection: IEnumerable { RuleType parent; public RuleType Parent { set { parent = value; } } public NameEnumerator GetEnumerator() { return new NameEnumerator(parent); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class NameEnumerator: IEnumerator { int nIndex; RuleType parent; public NameEnumerator(RuleType par) { parent = par; nIndex = -1; } public void Reset() { nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < parent.NameCount ); } public SchemaString Current { get { return(parent.GetNameAt(nIndex)); } } object IEnumerator.Current { get { return(Current); } } } #endregion // Name collection #region Condition accessor methods public int GetConditionMinCount() { return 1; } public int ConditionMinCount { get { return 1; } } public int GetConditionMaxCount() { return 1; } public int ConditionMaxCount { get { return 1; } } public int GetConditionCount() { return DomChildCount(NodeType.Element, "", "Condition"); } public int ConditionCount { get { return DomChildCount(NodeType.Element, "", "Condition"); } } public bool HasCondition() { return HasDomChild(NodeType.Element, "", "Condition"); } public LogicalExpression GetConditionAt(int index) { return new LogicalExpression(GetDomChildAt(NodeType.Element, "", "Condition", index)); } public LogicalExpression GetCondition() { return GetConditionAt(0); } public LogicalExpression Condition { get { return GetConditionAt(0); } } public void RemoveConditionAt(int index) { RemoveDomChildAt(NodeType.Element, "", "Condition", index); } public void RemoveCondition() { while (HasCondition()) RemoveConditionAt(0); } public void AddCondition(LogicalExpression newValue) { AppendDomElement("", "Condition", newValue); } public void InsertConditionAt(LogicalExpression newValue, int index) { InsertDomElementAt("", "Condition", index, newValue); } public void ReplaceConditionAt(LogicalExpression newValue, int index) { ReplaceDomElementAt("", "Condition", index, newValue); } #endregion // Condition accessor methods #region Condition collection public ConditionCollection MyConditions = new ConditionCollection( ); public class ConditionCollection: IEnumerable { RuleType parent; public RuleType Parent { set { parent = value; } } public ConditionEnumerator GetEnumerator() { return new ConditionEnumerator(parent); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class ConditionEnumerator: IEnumerator { int nIndex; RuleType parent; public ConditionEnumerator(RuleType par) { parent = par; nIndex = -1; } public void Reset() { nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < parent.ConditionCount ); } public LogicalExpression Current { get { return(parent.GetConditionAt(nIndex)); } } object IEnumerator.Current { get { return(Current); } } } #endregion // Condition collection #region Action accessor methods public int GetActionMinCount() { return 1; } public int ActionMinCount { get { return 1; } } public int GetActionMaxCount() { return Int32.MaxValue; } public int ActionMaxCount { get { return Int32.MaxValue; } } public int GetActionCount() { return DomChildCount(NodeType.Element, "", "Action"); } public int ActionCount { get { return DomChildCount(NodeType.Element, "", "Action"); } } public bool HasAction() { return HasDomChild(NodeType.Element, "", "Action"); } public ActionType GetActionAt(int index) { return new ActionType(GetDomChildAt(NodeType.Element, "", "Action", index)); } public ActionType GetAction() { return GetActionAt(0); } public ActionType Action { get { return GetActionAt(0); } } public void RemoveActionAt(int index) { RemoveDomChildAt(NodeType.Element, "", "Action", index); } public void RemoveAction() { while (HasAction()) RemoveActionAt(0); } public void AddAction(ActionType newValue) { AppendDomElement("", "Action", newValue); } public void InsertActionAt(ActionType newValue, int index) { InsertDomElementAt("", "Action", index, newValue); } public void ReplaceActionAt(ActionType newValue, int index) { ReplaceDomElementAt("", "Action", index, newValue); } #endregion // Action accessor methods #region Action collection public ActionCollection MyActions = new ActionCollection( ); public class ActionCollection: IEnumerable { RuleType parent; public RuleType Parent { set { parent = value; } } public ActionEnumerator GetEnumerator() { return new ActionEnumerator(parent); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class ActionEnumerator: IEnumerator { int nIndex; RuleType parent; public ActionEnumerator(RuleType par) { parent = par; nIndex = -1; } public void Reset() { nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < parent.ActionCount ); } public ActionType Current { get { return(parent.GetActionAt(nIndex)); } } object IEnumerator.Current { get { return(Current); } } } #endregion // Action collection #region Priority accessor methods public int GetPriorityMinCount() { return 1; } public int PriorityMinCount { get { return 1; } } public int GetPriorityMaxCount() { return 1; } public int PriorityMaxCount { get { return 1; } } public int GetPriorityCount() { return DomChildCount(NodeType.Element, "", "Priority"); } public int PriorityCount { get { return DomChildCount(NodeType.Element, "", "Priority"); } } public bool HasPriority() { return HasDomChild(NodeType.Element, "", "Priority"); } public SchemaLong GetPriorityAt(int index) { return new SchemaLong(GetDomNodeValue(GetDomChildAt(NodeType.Element, "", "Priority", index))); } public SchemaLong GetPriority() { return GetPriorityAt(0); } public SchemaLong Priority { get { return GetPriorityAt(0); } } public void RemovePriorityAt(int index) { RemoveDomChildAt(NodeType.Element, "", "Priority", index); } public void RemovePriority() { while (HasPriority()) RemovePriorityAt(0); } public void AddPriority(SchemaLong newValue) { AppendDomChild(NodeType.Element, "", "Priority", newValue.ToString()); } public void InsertPriorityAt(SchemaLong newValue, int index) { InsertDomChildAt(NodeType.Element, "", "Priority", index, newValue.ToString()); } public void ReplacePriorityAt(SchemaLong newValue, int index) { ReplaceDomChildAt(NodeType.Element, "", "Priority", index, newValue.ToString()); } #endregion // Priority accessor methods #region Priority collection public PriorityCollection MyPrioritys = new PriorityCollection( ); public class PriorityCollection: IEnumerable { RuleType parent; public RuleType Parent { set { parent = value; } } public PriorityEnumerator GetEnumerator() { return new PriorityEnumerator(parent); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class PriorityEnumerator: IEnumerator { int nIndex; RuleType parent; public PriorityEnumerator(RuleType par) { parent = par; nIndex = -1; } public void Reset() { nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < parent.PriorityCount ); } public SchemaLong Current { get { return(parent.GetPriorityAt(nIndex)); } } object IEnumerator.Current { get { return(Current); } } } #endregion // Priority collection private void SetCollectionParents() { MyNames.Parent = this; MyConditions.Parent = this; MyActions.Parent = this; MyPrioritys.Parent = this; } } }
// 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.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipes.Tests { /// <summary> /// Tests that cover Read and ReadAsync behaviors that are shared between /// AnonymousPipes and NamedPipes /// </summary> public abstract partial class PipeTest_Read : PipeTestBase { [Fact] public void ReadWithNullBuffer_Throws_ArgumentNullException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.readablePipe; Assert.True(pipe.IsConnected); Assert.True(pipe.CanRead); // Null is an invalid Buffer AssertExtensions.Throws<ArgumentNullException>("buffer", () => pipe.Read(null, 0, 1)); AssertExtensions.Throws<ArgumentNullException>("buffer", () => { pipe.ReadAsync(null, 0, 1); }); // Buffer validity is checked before Offset AssertExtensions.Throws<ArgumentNullException>("buffer", () => pipe.Read(null, -1, 1)); AssertExtensions.Throws<ArgumentNullException>("buffer", () => { pipe.ReadAsync(null, -1, 1); }); // Buffer validity is checked before Count AssertExtensions.Throws<ArgumentNullException>("buffer", () => pipe.Read(null, -1, -1)); AssertExtensions.Throws<ArgumentNullException>("buffer", () => { pipe.ReadAsync(null, -1, -1); }); } } [Fact] public void ReadWithNegativeOffset_Throws_ArgumentOutOfRangeException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.readablePipe; Assert.True(pipe.IsConnected); Assert.True(pipe.CanRead); // Offset must be nonnegative AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => pipe.Read(new byte[6], -1, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => { pipe.ReadAsync(new byte[4], -1, 1); }); } } [Fact] public void ReadWithNegativeCount_Throws_ArgumentOutOfRangeException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.readablePipe; Assert.True(pipe.IsConnected); Assert.True(pipe.CanRead); // Count must be nonnegative AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => pipe.Read(new byte[3], 0, -1)); AssertExtensions.Throws<System.ArgumentOutOfRangeException>("count", () => { pipe.ReadAsync(new byte[7], 0, -1); }); } } [Fact] public void ReadWithOutOfBoundsArray_Throws_ArgumentException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.readablePipe; Assert.True(pipe.IsConnected); Assert.True(pipe.CanRead); // offset out of bounds AssertExtensions.Throws<ArgumentException>(null, () => pipe.Read(new byte[1], 1, 1)); // offset out of bounds for 0 count read AssertExtensions.Throws<ArgumentException>(null, () => pipe.Read(new byte[1], 2, 0)); // offset out of bounds even for 0 length buffer AssertExtensions.Throws<ArgumentException>(null, () => pipe.Read(new byte[0], 1, 0)); // combination offset and count out of bounds AssertExtensions.Throws<ArgumentException>(null, () => pipe.Read(new byte[2], 1, 2)); // edges AssertExtensions.Throws<ArgumentException>(null, () => pipe.Read(new byte[0], int.MaxValue, 0)); AssertExtensions.Throws<ArgumentException>(null, () => pipe.Read(new byte[0], int.MaxValue, int.MaxValue)); AssertExtensions.Throws<ArgumentException>(null, () => pipe.Read(new byte[5], 3, 4)); // offset out of bounds AssertExtensions.Throws<ArgumentException>(null, () => { pipe.ReadAsync(new byte[1], 1, 1); }); // offset out of bounds for 0 count read AssertExtensions.Throws<ArgumentException>(null, () => { pipe.ReadAsync(new byte[1], 2, 0); }); // offset out of bounds even for 0 length buffer AssertExtensions.Throws<ArgumentException>(null, () => { pipe.ReadAsync(new byte[0], 1, 0); }); // combination offset and count out of bounds AssertExtensions.Throws<ArgumentException>(null, () => { pipe.ReadAsync(new byte[2], 1, 2); }); // edges AssertExtensions.Throws<ArgumentException>(null, () => { pipe.ReadAsync(new byte[0], int.MaxValue, 0); }); AssertExtensions.Throws<ArgumentException>(null, () => { pipe.ReadAsync(new byte[0], int.MaxValue, int.MaxValue); }); AssertExtensions.Throws<ArgumentException>(null, () => { pipe.ReadAsync(new byte[5], 3, 4); }); } } [Fact] public virtual void WriteToReadOnlyPipe_Throws_NotSupportedException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.readablePipe; Assert.True(pipe.IsConnected); Assert.False(pipe.CanWrite); Assert.False(pipe.CanSeek); Assert.Throws<NotSupportedException>(() => pipe.Write(new byte[5], 0, 5)); Assert.Throws<NotSupportedException>(() => pipe.WriteByte(123)); Assert.Throws<NotSupportedException>(() => pipe.Flush()); Assert.Throws<NotSupportedException>(() => pipe.OutBufferSize); Assert.Throws<NotSupportedException>(() => pipe.WaitForPipeDrain()); Assert.Throws<NotSupportedException>(() => { pipe.WriteAsync(new byte[5], 0, 5); }); } } [Fact] public async Task ReadWithZeroLengthBuffer_Nop() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.readablePipe; var buffer = new byte[] { }; Assert.Equal(0, pipe.Read(buffer, 0, 0)); Task<int> read = pipe.ReadAsync(buffer, 0, 0); Assert.Equal(0, await read); } } [Fact] public void ReadPipeUnsupportedMembers_Throws_NotSupportedException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.readablePipe; Assert.True(pipe.IsConnected); Assert.Throws<NotSupportedException>(() => pipe.Length); Assert.Throws<NotSupportedException>(() => pipe.SetLength(10L)); Assert.Throws<NotSupportedException>(() => pipe.Position); Assert.Throws<NotSupportedException>(() => pipe.Position = 10L); Assert.Throws<NotSupportedException>(() => pipe.Seek(10L, System.IO.SeekOrigin.Begin)); } } [Fact] public void ReadOnDisposedReadablePipe_Throws_ObjectDisposedException() { using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.readablePipe; pipe.Dispose(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<ObjectDisposedException>(() => pipe.Flush()); Assert.Throws<ObjectDisposedException>(() => pipe.Read(buffer, 0, buffer.Length)); Assert.Throws<ObjectDisposedException>(() => pipe.ReadByte()); Assert.Throws<ObjectDisposedException>(() => { pipe.ReadAsync(buffer, 0, buffer.Length); }); Assert.Throws<ObjectDisposedException>(() => pipe.IsMessageComplete); Assert.Throws<ObjectDisposedException>(() => pipe.ReadMode); } } [Fact] public void CopyToAsync_InvalidArgs_Throws() { using (ServerClientPair pair = CreateServerClientPair()) { AssertExtensions.Throws<ArgumentNullException>("destination", () => { pair.readablePipe.CopyToAsync(null); }); AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => { pair.readablePipe.CopyToAsync(new MemoryStream(), 0); }); Assert.Throws<NotSupportedException>(() => { pair.readablePipe.CopyToAsync(new MemoryStream(new byte[1], writable: false)); }); if (!pair.writeablePipe.CanRead) { Assert.Throws<NotSupportedException>(() => { pair.writeablePipe.CopyToAsync(new MemoryStream()); }); } } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "There is a bug in netfx around async read on a broken PipeStream. See #2601 and #2899. This bug is fixed in netcore.")] public virtual async Task ReadFromPipeWithClosedPartner_ReadNoBytes() { using (ServerClientPair pair = CreateServerClientPair()) { pair.writeablePipe.Dispose(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; // The pipe won't be marked as Broken until the first read, so prime it // to test both the case where it's not yet marked as "Broken" and then // where it is. Assert.Equal(0, pair.readablePipe.Read(buffer, 0, buffer.Length)); Assert.Equal(0, pair.readablePipe.Read(buffer, 0, buffer.Length)); Assert.Equal(-1, pair.readablePipe.ReadByte()); Assert.Equal(0, await pair.readablePipe.ReadAsync(buffer, 0, buffer.Length)); } } [Fact] public async Task ValidWriteAsync_ValidReadAsync() { using (ServerClientPair pair = CreateServerClientPair()) { Assert.True(pair.writeablePipe.IsConnected); Assert.True(pair.readablePipe.IsConnected); byte[] sent = new byte[] { 123, 0, 5 }; byte[] received = new byte[] { 0, 0, 0 }; Task write = pair.writeablePipe.WriteAsync(sent, 0, sent.Length); Assert.Equal(sent.Length, await pair.readablePipe.ReadAsync(received, 0, sent.Length)); Assert.Equal(sent, received); await write; } } [Fact] public void ValidWrite_ValidRead() { using (ServerClientPair pair = CreateServerClientPair()) { Assert.True(pair.writeablePipe.IsConnected); Assert.True(pair.readablePipe.IsConnected); byte[] sent = new byte[] { 123, 0, 5 }; byte[] received = new byte[] { 0, 0, 0 }; Task.Run(() => { pair.writeablePipe.Write(sent, 0, sent.Length); }); Assert.Equal(sent.Length, pair.readablePipe.Read(received, 0, sent.Length)); Assert.Equal(sent, received); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // WaitForPipeDrain isn't supported on Unix pair.writeablePipe.WaitForPipeDrain(); } } [Fact] public void ValidWriteByte_ValidReadByte() { using (ServerClientPair pair = CreateServerClientPair()) { Assert.True(pair.writeablePipe.IsConnected); Assert.True(pair.readablePipe.IsConnected); Task.Run(() => pair.writeablePipe.WriteByte(123)); Assert.Equal(123, pair.readablePipe.ReadByte()); } } [Theory] [OuterLoop] [MemberData(nameof(AsyncReadWriteChain_MemberData))] public async Task AsyncReadWriteChain_ReadWrite(int iterations, int writeBufferSize, int readBufferSize, bool cancelableToken) { var writeBuffer = new byte[writeBufferSize]; var readBuffer = new byte[readBufferSize]; var rand = new Random(); var cancellationToken = cancelableToken ? new CancellationTokenSource().Token : CancellationToken.None; using (ServerClientPair pair = CreateServerClientPair()) { // Repeatedly and asynchronously write to the writable pipe and read from the readable pipe, // verifying that the correct data made it through. for (int iter = 0; iter < iterations; iter++) { rand.NextBytes(writeBuffer); Task writerTask = pair.writeablePipe.WriteAsync(writeBuffer, 0, writeBuffer.Length, cancellationToken); int totalRead = 0; while (totalRead < writeBuffer.Length) { int numRead = await pair.readablePipe.ReadAsync(readBuffer, 0, readBuffer.Length, cancellationToken); Assert.True(numRead > 0); Assert.Equal<byte>( new ArraySegment<byte>(writeBuffer, totalRead, numRead), new ArraySegment<byte>(readBuffer, 0, numRead)); totalRead += numRead; } Assert.Equal(writeBuffer.Length, totalRead); await writerTask; } } } [Theory] [OuterLoop] [MemberData(nameof(AsyncReadWriteChain_MemberData))] public async Task AsyncReadWriteChain_CopyToAsync(int iterations, int writeBufferSize, int readBufferSize, bool cancelableToken) { var writeBuffer = new byte[writeBufferSize * iterations]; new Random().NextBytes(writeBuffer); var cancellationToken = cancelableToken ? new CancellationTokenSource().Token : CancellationToken.None; using (ServerClientPair pair = CreateServerClientPair()) { var readData = new MemoryStream(); Task copyTask = pair.readablePipe.CopyToAsync(readData, readBufferSize, cancellationToken); for (int iter = 0; iter < iterations; iter++) { await pair.writeablePipe.WriteAsync(writeBuffer, iter * writeBufferSize, writeBufferSize, cancellationToken); } pair.writeablePipe.Dispose(); await copyTask; Assert.Equal(writeBuffer.Length, readData.Length); Assert.Equal(writeBuffer, readData.ToArray()); } } public static IEnumerable<object[]> AsyncReadWriteChain_MemberData() { foreach (bool cancelableToken in new[] { true, false }) { yield return new object[] { 5000, 1, 1, cancelableToken }; // very small buffers yield return new object[] { 500, 21, 18, cancelableToken }; // lots of iterations, with read buffer smaller than write buffer yield return new object[] { 500, 18, 21, cancelableToken }; // lots of iterations, with write buffer smaller than read buffer yield return new object[] { 5, 128000, 64000, cancelableToken }; // very large buffers } } [Fact] public async Task ValidWriteAsync_ValidReadAsync_APM() { using (ServerClientPair pair = CreateServerClientPair()) { Assert.True(pair.writeablePipe.IsConnected); Assert.True(pair.readablePipe.IsConnected); byte[] sent = new byte[] { 123, 0, 5 }; byte[] received = new byte[] { 0, 0, 0 }; Task write = Task.Factory.FromAsync<byte[], int, int>(pair.writeablePipe.BeginWrite, pair.writeablePipe.EndWrite, sent, 0, sent.Length, null); Task<int> read = Task.Factory.FromAsync<byte[], int, int, int>(pair.readablePipe.BeginRead, pair.readablePipe.EndRead, received, 0, received.Length, null); Assert.Equal(sent.Length, await read); Assert.Equal(sent, received); await write; } } [Theory] [OuterLoop] [MemberData(nameof(AsyncReadWriteChain_MemberData))] public async Task AsyncReadWriteChain_ReadWrite_APM(int iterations, int writeBufferSize, int readBufferSize, bool cancelableToken) { var writeBuffer = new byte[writeBufferSize]; var readBuffer = new byte[readBufferSize]; var rand = new Random(); var cancellationToken = cancelableToken ? new CancellationTokenSource().Token : CancellationToken.None; using (ServerClientPair pair = CreateServerClientPair()) { // Repeatedly and asynchronously write to the writable pipe and read from the readable pipe, // verifying that the correct data made it through. for (int iter = 0; iter < iterations; iter++) { rand.NextBytes(writeBuffer); Task write = Task.Factory.FromAsync<byte[], int, int>(pair.writeablePipe.BeginWrite, pair.writeablePipe.EndWrite, writeBuffer, 0, writeBuffer.Length, null); int totalRead = 0; while (totalRead < writeBuffer.Length) { Task<int> read = Task.Factory.FromAsync<byte[], int, int, int>(pair.readablePipe.BeginRead, pair.readablePipe.EndRead, readBuffer, 0, readBuffer.Length, null); int numRead = await read; Assert.True(numRead > 0); Assert.Equal<byte>( new ArraySegment<byte>(writeBuffer, totalRead, numRead), new ArraySegment<byte>(readBuffer, 0, numRead)); totalRead += numRead; } Assert.Equal(writeBuffer.Length, totalRead); await write; } } } } }
using System; using System.Data; using System.Data.SqlClient; using Rainbow.Framework; using Rainbow.Framework.DataTypes; using Rainbow.Framework.Helpers; using Rainbow.Framework.Services; using Rainbow.Framework.Settings; using Rainbow.Framework.Site.Configuration; using Rainbow.Framework.Users.Data; using Rainbow.Framework.Web.UI; using Rainbow.Framework.Web.UI.WebControls; using History=Rainbow.Framework.History; using Rainbow.Framework.Providers.RainbowMembershipProvider; namespace Rainbow.Content.Web.Modules { /// <summary> /// ServiceItemList /// Written by: Jakob hansen /// This module lists data from another Rainbow based portal or the same portal as where the module resides. /// All fields in result: /// ModuleName, Title, Description, ModuleID, ItemID, /// CreatedByUser, CreatedDate, PageID, TabName, /// ModuleGuidID, ModuleTitle /// </summary> [History("jminond", "2006/02/22", "converted to partial class")] [History("jminond", "2005/03/15", "Changes for moving Tab to Page")] public partial class ServiceItemList : PortalModuleControl { protected ServiceRequestInfo requestInfo; protected bool showImage, showModuleFriendlyName, showTitle, showDescription; protected bool showCreatedByUser, showCreatedDate, showLink, showTabName, showModuleTitle; protected string Target; /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> private void Page_Load(object sender, EventArgs e) { requestInfo = new ServiceRequestInfo(); requestInfo.Type = ServiceType.CommunityWebService; requestInfo.Url = Settings["URL"].ToString(); requestInfo.PortalAlias = Settings["PortalAlias"].ToString(); requestInfo.LocalMode = bool.Parse(Settings["LocalMode"].ToString().ToLower()); /* Jakob says: later... requestInfo.UserName = Settings["UserName"].ToString(); requestInfo.UserPassword = Settings["UserPassword"].ToString(); */ requestInfo.ListType = ServiceListType.Item; requestInfo.ModuleType = Settings["ModuleType"].ToString(); requestInfo.MaxHits = Int32.Parse(Settings["MaxHits"].ToString()); requestInfo.ShowID = bool.Parse(Settings["ShowID"].ToString().ToLower()); requestInfo.SearchString = Settings["SearchString"].ToString(); requestInfo.SearchField = Settings["SearchField"].ToString(); requestInfo.SortField = Settings["SortField"].ToString(); requestInfo.SortDirection = Settings["SortDirection"].ToString(); requestInfo.MobileOnly = bool.Parse(Settings["MobileOnly"].ToString().ToLower()); requestInfo.IDList = Settings["IDList"].ToString(); //requestInfo.IDListType = Settings["IDListType"].ToString(); string par = Settings["IDListType"].ToString(); if (par == ServiceListType.Item.ToString()) requestInfo.IDListType = ServiceListType.Item; if (par == ServiceListType.Module.ToString()) requestInfo.IDListType = ServiceListType.Module; if (par == ServiceListType.Tab.ToString()) requestInfo.IDListType = ServiceListType.Tab; requestInfo.Tag = Int32.Parse(Settings["Tag"].ToString()); //showImage = bool.Parse(Settings["ShowImage"].ToString().ToLower()); showModuleFriendlyName = bool.Parse(Settings["ShowModuleFriendlyName"].ToString().ToLower()); showTitle = bool.Parse(Settings["ShowSearchTitle"].ToString().ToLower()); showDescription = bool.Parse(Settings["ShowDescription"].ToString().ToLower()); showCreatedByUser = bool.Parse(Settings["ShowCreatedByUser"].ToString().ToLower()); showCreatedDate = bool.Parse(Settings["ShowCreatedDate"].ToString().ToLower()); showLink = bool.Parse(Settings["ShowLink"].ToString().ToLower()); showTabName = bool.Parse(Settings["ShowTabName"].ToString().ToLower()); showModuleTitle = bool.Parse(Settings["ShowModuleTitle"].ToString().ToLower()); Target = "_" + Settings["Target"].ToString(); GetItems(); } /// <summary> /// Gets the items. /// </summary> private void GetItems() { string status = "Dialing..."; try { int portalID = portalSettings.PortalID; Guid userID = Guid.Empty; UsersDB u = new UsersDB(); RainbowUser s = u.GetSingleUser(PortalSettings.CurrentUser.Identity.Email); try { userID = (Guid)s.ProviderUserKey; } finally { // s.Close(); //by Manu, fixed bug 807858 } ServiceResponseInfo responseInfo; responseInfo = ServiceHelper.CallService(portalID, userID, Path.ApplicationFullPath, ref requestInfo, (Page) Page); status = responseInfo.ServiceStatus; if (status != "OK") { if (status.IndexOf("404") > 0) lblStatus.Text = status + "<br>" + "URL: " + requestInfo.Url; else lblStatus.Text = "WARNING! Service status: " + status; } DataSet ds = FillPortalDS(ref responseInfo); DataGrid1.DataSource = ds; DataGrid1.DataBind(); } catch (Exception ex) { lblStatus.Text = "FATAL ERROR! Problem: " + ex.Message + ". Service status: " + status; return; } } /// <summary> /// Creates the portal DS. /// </summary> /// <param name="ds">The ds.</param> /// <returns></returns> private DataSet CreatePortalDS(DataSet ds) { ds.Tables.Add("ServiceItemList"); //if (showImage) // ds.Tables[0].Columns.Add("Image"); if (showModuleFriendlyName) ds.Tables[0].Columns.Add("Module"); if (showModuleTitle) ds.Tables[0].Columns.Add("Module Title"); if (showTitle) ds.Tables[0].Columns.Add("Title"); if (showDescription) ds.Tables[0].Columns.Add("Description"); if (showCreatedByUser) ds.Tables[0].Columns.Add("User"); if (showCreatedDate) ds.Tables[0].Columns.Add("Date"); if (showLink) ds.Tables[0].Columns.Add("Link"); if (showTabName) ds.Tables[0].Columns.Add("Tab"); return ds; } /// <summary> /// Fills the portal DS. /// </summary> /// <param name="responseInfo">The response info.</param> /// <returns></returns> private DataSet FillPortalDS(ref ServiceResponseInfo responseInfo) { DataSet ds = new DataSet(); try { ds = CreatePortalDS(ds); string strTmp, strLink, strBaseLink; string strModuleFriendlyName, strModuleID, strItemID; string strTabID, strModuleGuidID, strModuleTitle; string strLocate; DataRow dr; for (int row = 0; row < responseInfo.Items.Count; row++) { dr = ds.Tables["ServiceItemList"].NewRow(); //ServiceResponseInfoItemExt item = (ServiceResponseInfoItemExt) responseInfo.Items[row]; ServiceResponseInfoItem item = (ServiceResponseInfoItem) responseInfo.Items[row]; strModuleFriendlyName = item.FriendlyName; strModuleID = item.ModuleID.ToString(); strItemID = item.ItemID.ToString(); strTabID = item.PageID.ToString(); strModuleGuidID = item.GeneralModDefID.ToString().ToUpper(); strModuleTitle = item.ModuleTitle; strLocate = "mID=" + strModuleID + "&ItemID=" + strItemID; if (requestInfo.ShowID) { strModuleFriendlyName += " (ID=" + strModuleID + ")"; strModuleTitle += " (ID=" + strModuleID + ")"; } if (requestInfo.LocalMode) { strBaseLink = Path.ApplicationRoot + "/"; } else { strBaseLink = requestInfo.Url; } switch (strModuleGuidID) { case "2D86166C-4BDC-4A6F-A028-D17C2BB177C8": //Discussions strLink = strBaseLink + "DesktopModules/Discussion/DiscussionView.aspx?" + strLocate; break; case "2502DB18-B580-4F90-8CB4-C15E6E531012": //Tasks strLink = strBaseLink + "DesktopModules/Tasks/TasksView.aspx?" + strLocate; break; default: strLink = strBaseLink + "DesktopDefault.aspx?tabID=" + strTabID; break; } if (requestInfo.PortalAlias.Length != 0) strLink += "&Alias=" + requestInfo.PortalAlias; //if (showImage) //{ // dr["Image"] = "<a href='" + strLink + "'>" + strModuleGuidID + ".gif" + "</a>"; //} if (showModuleFriendlyName) { dr["Module"] = strModuleFriendlyName; } if (showModuleTitle) { dr["Module Title"] = strModuleTitle; } if (showTitle) { if (strModuleGuidID == "0B113F51-FEA3-499A-98E7-7B83C192FDBB" || //Html Document strModuleGuidID == "2B113F51-FEA3-499A-98E7-7B83C192FDBB") //Html WYSIWYG Edit (V2) { // We use the database field [rb.Modules].[ModuleTitle]: strTmp = strModuleTitle; } else { if (item.Title == string.Empty) strTmp = "missing"; else strTmp = item.Title; } dr["Title"] = "<a href='" + strLink + "' Target='" + Target + "'>" + strTmp + "</a>"; } if (showDescription) { if (item.Description == string.Empty) strTmp = "missing"; else strTmp = item.Description; // Remove any html tags: HTMLText html = SearchHelper.DeleteBeforeBody(Server.HtmlDecode(strTmp)); dr["Description"] = html.InnerText; } if (showCreatedByUser) { if (item.CreatedByUser == string.Empty) strTmp = string.Empty; else strTmp = item.CreatedByUser; // 15/7/2004 added localization by Mario Endara [email protected] if (strTmp == "unknown") { strTmp = General.GetString("UNKNOWN", "unknown"); } dr["User"] = strTmp; } if (showCreatedDate) { try { strTmp = item.CreatedDate.ToShortDateString(); } catch { strTmp = string.Empty; } // If date is an empty string the date "1/1/1900" is returned. if (strTmp == "1/1/1900") strTmp = string.Empty; dr["Date"] = strTmp; } if (showLink) { dr["Link"] = "<a href='" + strLink + "' Target='" + Target + "'>" + strLink + "</a>"; } if (showTabName) { if (item.PageName == string.Empty) strTmp = "missing"; else strTmp = item.PageName; if (requestInfo.ShowID && strTmp != "missing") strTmp = strTmp + "(ID=" + item.PageID + ")"; if (requestInfo.PortalAlias.Length != 0) dr["Tab"] = "<a href='" + strBaseLink + "DesktopDefault.aspx?tabID=" + strTabID + "&Alias=" + requestInfo.PortalAlias + "' Target='" + Target + "'>" + strTmp + "</a>"; else dr["Tab"] = "<a href='" + strBaseLink + "DesktopDefault.aspx?tabID=" + strTabID + "' Target='" + Target + "'>" + strTmp + "</a>"; } ds.Tables["ServiceItemList"].Rows.Add(dr); } } catch (Exception e) { lblStatus.Text = "Error when reading list. Problem: " + e.Message; return null; } return ds; } /// <summary> /// Consturctor where all the module settings are set as base property settings. /// if theye don't exist there defaults are set here. /// </summary> public ServiceItemList() { SettingItem setURL = new SettingItem(new UrlDataType()); setURL.Order = 1; setURL.Required = true; setURL.Value = "http://www.rainbowportal.net/"; _baseSettings.Add("URL", setURL); SettingItem setPortalAlias = new SettingItem(new StringDataType()); setPortalAlias.Order = 2; setPortalAlias.Required = false; setPortalAlias.Value = string.Empty; _baseSettings.Add("PortalAlias", setPortalAlias); SettingItem setLocalMode = new SettingItem(new BooleanDataType()); setLocalMode.Order = 3; setLocalMode.Value = "false"; _baseSettings.Add("LocalMode", setLocalMode); SettingItem setModuleType = new SettingItem( new ListDataType( "All;Announcements;Contacts;Discussion;Events;HtmlModule;Documents;Pictures;Articles;Tasks;FAQs;ComponentModule")); setModuleType.Order = 4; setModuleType.Required = true; setModuleType.Value = "All"; _baseSettings.Add("ModuleType", setModuleType); SettingItem setMaxHits = new SettingItem(new IntegerDataType()); setMaxHits.Order = 5; setMaxHits.Required = true; setMaxHits.Value = "20"; setMaxHits.MinValue = 1; setMaxHits.MaxValue = 1000; _baseSettings.Add("MaxHits", setMaxHits); SettingItem setShowID = new SettingItem(new BooleanDataType()); setShowID.Order = 6; setShowID.Value = "false"; _baseSettings.Add("ShowID", setShowID); SettingItem setSearchString = new SettingItem(new StringDataType()); setSearchString.Order = 7; setSearchString.Required = false; setSearchString.Value = "localization"; _baseSettings.Add("SearchString", setSearchString); SettingItem setSearchField = new SettingItem(new StringDataType()); setSearchField.Order = 8; setSearchField.Required = false; setSearchField.Value = string.Empty; _baseSettings.Add("SearchField", setSearchField); SettingItem setSortField = new SettingItem(new ListDataType("ModuleName;Title;CreatedByUser;CreatedDate;TabName")); setSortField.Order = 9; setSortField.Required = true; setSortField.Value = "ModuleName"; _baseSettings.Add("SortField", setSortField); SettingItem setSortDirection = new SettingItem(new ListDataType("ASC;DESC")); setSortDirection.Order = 10; setSortDirection.Required = true; setSortDirection.Value = "ASC"; _baseSettings.Add("SortDirection", setSortDirection); SettingItem setMobileOnly = new SettingItem(new BooleanDataType()); setMobileOnly.Order = 11; setMobileOnly.Value = "false"; _baseSettings.Add("MobileOnly", setMobileOnly); SettingItem setIDList = new SettingItem(new StringDataType()); setIDList.Order = 12; setIDList.Required = false; setIDList.Value = string.Empty; _baseSettings.Add("IDList", setIDList); SettingItem setIDListType = new SettingItem(new ListDataType("Item;Module;Tab")); setIDListType.Order = 13; setIDListType.Required = true; setIDListType.Value = "Tab"; _baseSettings.Add("IDListType", setIDListType); SettingItem setTag = new SettingItem(new IntegerDataType()); setTag.Order = 14; setTag.Required = true; setTag.Value = "0"; _baseSettings.Add("Tag", setTag); //SettingItem showImage = new SettingItem(new BooleanDataType()); //showImage.Order = 15; //showImage.Value = "True"; //this._baseSettings.Add("ShowImage", showImage); SettingItem setShowModuleFriendlyName = new SettingItem(new BooleanDataType()); setShowModuleFriendlyName.Order = 16; setShowModuleFriendlyName.Value = "true"; _baseSettings.Add("ShowModuleFriendlyName", setShowModuleFriendlyName); SettingItem setShowSearchTitle = new SettingItem(new BooleanDataType()); setShowSearchTitle.Order = 17; setShowSearchTitle.Value = "true"; _baseSettings.Add("ShowSearchTitle", setShowSearchTitle); SettingItem setShowDescription = new SettingItem(new BooleanDataType()); setShowDescription.Order = 18; setShowDescription.Value = "true"; _baseSettings.Add("ShowDescription", setShowDescription); SettingItem setShowCreatedByUser = new SettingItem(new BooleanDataType()); setShowCreatedByUser.Order = 19; setShowCreatedByUser.Value = "true"; _baseSettings.Add("ShowCreatedByUser", setShowCreatedByUser); SettingItem setShowCreatedDate = new SettingItem(new BooleanDataType()); setShowCreatedDate.Order = 20; setShowCreatedDate.Value = "true"; _baseSettings.Add("ShowCreatedDate", setShowCreatedDate); SettingItem setShowLink = new SettingItem(new BooleanDataType()); setShowLink.Order = 21; setShowLink.Value = "false"; _baseSettings.Add("ShowLink", setShowLink); SettingItem setShowTabName = new SettingItem(new BooleanDataType()); setShowTabName.Order = 22; setShowTabName.Value = "true"; _baseSettings.Add("ShowTabName", setShowTabName); SettingItem setShowModuleTitle = new SettingItem(new BooleanDataType()); setShowModuleTitle.Order = 23; setShowModuleTitle.Value = "false"; _baseSettings.Add("ShowModuleTitle", setShowModuleTitle); SettingItem setTarget = new SettingItem(new ListDataType("blank;parent;self;top")); setTarget.Order = 24; setTarget.Required = true; setTarget.Value = "blank"; _baseSettings.Add("Target", setTarget); /* Jakob says: later... SettingItem setUserName = new SettingItem(new StringDataType()); setUserName.Order = 25; setUserName.Required = false; setUserName.Value = string.Empty; this._baseSettings.Add("UserName", setUserName); SettingItem setUserPassword = new SettingItem(new StringDataType()); setUserPassword.Order = 26; setUserPassword.Required = false; setUserPassword.Value = string.Empty; this._baseSettings.Add("UserPassword", setUserPassword); */ } /// <summary> /// GUID of module (mandatory) /// </summary> /// <value></value> public override Guid GuidID { get { return new Guid("{2502DB18-B580-4F90-8CB4-C15E6E531052}"); } } #region Web Form Designer generated code /// <summary> /// Raises Init event /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { this.Load += new EventHandler(this.Page_Load); base.OnInit(e); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.InteropServices { /// <summary> /// Native buffer that deals in char size increments. Dispose to free memory. Allows buffers larger /// than a maximum size string to enable working with very large string arrays. Always makes ordinal /// comparisons. /// /// A more performant replacement for StringBuilder when performing native interop. /// </summary> /// <remarks> /// Suggested use through P/Invoke: define DllImport arguments that take a character buffer as IntPtr. /// NativeStringBuffer has an implicit conversion to IntPtr. /// </remarks> internal class StringBuffer : NativeBuffer { private uint _length; /// <summary> /// Instantiate the buffer with capacity for at least the specified number of characters. Capacity /// includes the trailing null character. /// </summary> public StringBuffer(uint initialCapacity = 0) : base(initialCapacity * (ulong)sizeof(char)) { } /// <summary> /// Instantiate the buffer with a copy of the specified string. /// </summary> public StringBuffer(string initialContents) : base(0) { // We don't pass the count of bytes to the base constructor, appending will // initialize to the correct size for the specified initial contents. if (initialContents != null) { Append(initialContents); } } /// <summary> /// Instantiate the buffer with a copy of the specified StringBuffer. /// </summary> public StringBuffer(StringBuffer initialContents) : base(0) { // We don't pass the count of bytes to the base constructor, appending will // initialize to the correct size for the specified initial contents. if (initialContents != null) { Append(initialContents); } } /// <summary> /// Get/set the character at the given index. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown if attempting to index outside of the buffer length.</exception> public unsafe char this[uint index] { [System.Security.SecuritySafeCritical] get { if (index >= _length) throw new ArgumentOutOfRangeException(nameof(index)); return CharPointer[index]; } [System.Security.SecuritySafeCritical] set { if (index >= _length) throw new ArgumentOutOfRangeException(nameof(index)); CharPointer[index] = value; } } /// <summary> /// Character capacity of the buffer. Includes the count for the trailing null character. /// </summary> public uint CharCapacity { [System.Security.SecuritySafeCritical] get { ulong byteCapacity = ByteCapacity; ulong charCapacity = byteCapacity == 0 ? 0 : byteCapacity / sizeof(char); return charCapacity > uint.MaxValue ? uint.MaxValue : (uint)charCapacity; } } /// <summary> /// Ensure capacity in characters is at least the given minimum. Capacity includes space for the trailing /// null, which is not part of the Length. /// </summary> /// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception> [System.Security.SecuritySafeCritical] public void EnsureCharCapacity(uint minCapacity) { EnsureByteCapacity(minCapacity * (ulong)sizeof(char)); } /// <summary> /// The logical length of the buffer in characters. (Does not include the final null, which is auto appended.) Will automatically attempt to increase capacity. /// This is where the usable data ends. /// </summary> /// <exception cref="OutOfMemoryException">Thrown if unable to allocate memory when setting.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown if the set size in bytes is uint.MaxValue (as space is implicitly reservced for the trailing null).</exception> public unsafe uint Length { get { return _length; } [System.Security.SecuritySafeCritical] set { if (value == uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(Length)); // Null terminate EnsureCharCapacity(value + 1); CharPointer[value] = '\0'; _length = value; } } /// <summary> /// For use when the native api null terminates but doesn't return a length. /// If no null is found, the length will not be changed. /// </summary> [System.Security.SecuritySafeCritical] public unsafe void SetLengthToFirstNull() { char* buffer = CharPointer; uint capacity = CharCapacity; for (uint i = 0; i < capacity; i++) { if (buffer[i] == '\0') { _length = i; break; } } } internal unsafe char* CharPointer { [System.Security.SecurityCritical] get { return (char*)VoidPointer; } } /// <summary> /// True if the buffer contains the given character. /// </summary> [System.Security.SecurityCritical] public unsafe bool Contains(char value) { char* start = CharPointer; uint length = _length; for (uint i = 0; i < length; i++) { if (*start++ == value) return true; } return false; } /// <summary> /// Returns true if the buffer starts with the given string. /// </summary> [System.Security.SecuritySafeCritical] public bool StartsWith(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (_length < (uint)value.Length) return false; return SubstringEquals(value, startIndex: 0, count: value.Length); } /// <summary> /// Returns true if the specified StringBuffer substring equals the given value. /// </summary> /// <param name="value">The value to compare against the specified substring.</param> /// <param name="startIndex">Start index of the sub string.</param> /// <param name="count">Length of the substring, or -1 to check all remaining.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range /// of the buffer's length. /// </exception> [System.Security.SecuritySafeCritical] public unsafe bool SubstringEquals(string value, uint startIndex = 0, int count = -1) { if (value == null) return false; if (count < -1) throw new ArgumentOutOfRangeException(nameof(count)); if (startIndex > _length) throw new ArgumentOutOfRangeException(nameof(startIndex)); uint realCount = count == -1 ? _length - startIndex : (uint)count; if (checked(startIndex + realCount) > _length) throw new ArgumentOutOfRangeException(nameof(count)); int length = value.Length; // Check the substring length against the input length if (realCount != (uint)length) return false; fixed (char* valueStart = value) { char* bufferStart = CharPointer + startIndex; for (int i = 0; i < length; i++) { // Note that indexing in this case generates faster code than trying to copy the pointer and increment it if (*bufferStart++ != valueStart[i]) return false; } } return true; } /// <summary> /// Append the given string. /// </summary> /// <param name="value">The string to append.</param> /// <param name="startIndex">The index in the input string to start appending from.</param> /// <param name="count">The count of characters to copy from the input string, or -1 for all remaining.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range /// of <paramref name="value"/> characters. /// </exception> [System.Security.SecuritySafeCritical] public void Append(string value, int startIndex = 0, int count = -1) { CopyFrom( bufferIndex: _length, source: value, sourceIndex: startIndex, count: count); } /// <summary> /// Append the given buffer. /// </summary> /// <param name="value">The buffer to append.</param> /// <param name="startIndex">The index in the input buffer to start appending from.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="startIndex"/> is outside the range of <paramref name="value"/> characters. /// </exception> public void Append(StringBuffer value, uint startIndex = 0) { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.Length == 0) return; value.CopyTo( bufferIndex: startIndex, destination: this, destinationIndex: _length, count: value.Length); } /// <summary> /// Append the given buffer. /// </summary> /// <param name="value">The buffer to append.</param> /// <param name="startIndex">The index in the input buffer to start appending from.</param> /// <param name="count">The count of characters to copy from the buffer string.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range /// of <paramref name="value"/> characters. /// </exception> public void Append(StringBuffer value, uint startIndex, uint count) { if (value == null) throw new ArgumentNullException(nameof(value)); if (count == 0) return; value.CopyTo( bufferIndex: startIndex, destination: this, destinationIndex: _length, count: count); } /// <summary> /// Copy contents to the specified buffer. Destination index must be within current destination length. /// Will grow the destination buffer if needed. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="bufferIndex"/> or <paramref name="destinationIndex"/> or <paramref name="count"/> are outside the range /// of <paramref name="value"/> characters. /// </exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="destination"/> is null.</exception> [System.Security.SecuritySafeCritical] public unsafe void CopyTo(uint bufferIndex, StringBuffer destination, uint destinationIndex, uint count) { if (destination == null) throw new ArgumentNullException(nameof(destination)); if (destinationIndex > destination._length) throw new ArgumentOutOfRangeException(nameof(destinationIndex)); if (bufferIndex >= _length) throw new ArgumentOutOfRangeException(nameof(bufferIndex)); if (_length < checked(bufferIndex + count)) throw new ArgumentOutOfRangeException(nameof(count)); if (count == 0) return; uint lastIndex = checked(destinationIndex + count); if (destination._length < lastIndex) destination.Length = lastIndex; Buffer.MemoryCopy( source: CharPointer + bufferIndex, destination: destination.CharPointer + destinationIndex, destinationSizeInBytes: checked((long)(destination.ByteCapacity - (destinationIndex * sizeof(char)))), sourceBytesToCopy: checked((long)count * sizeof(char))); } /// <summary> /// Copy contents from the specified string into the buffer at the given index. Start index must be within the current length of /// the buffer, will grow as necessary. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="bufferIndex"/> or <paramref name="sourceIndex"/> or <paramref name="count"/> are outside the range /// of <paramref name="value"/> characters. /// </exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="source"/> is null.</exception> [System.Security.SecuritySafeCritical] public unsafe void CopyFrom(uint bufferIndex, string source, int sourceIndex = 0, int count = -1) { if (source == null) throw new ArgumentNullException(nameof(source)); if (bufferIndex > _length) throw new ArgumentOutOfRangeException(nameof(bufferIndex)); if (sourceIndex < 0 || sourceIndex >= source.Length) throw new ArgumentOutOfRangeException(nameof(sourceIndex)); if (count == -1) count = source.Length - sourceIndex; if (count < 0 || source.Length - count < sourceIndex) throw new ArgumentOutOfRangeException(nameof(count)); if (count == 0) return; uint lastIndex = bufferIndex + (uint)count; if (_length < lastIndex) Length = lastIndex; fixed (char* content = source) { Buffer.MemoryCopy( source: content + sourceIndex, destination: CharPointer + bufferIndex, destinationSizeInBytes: checked((long)(ByteCapacity - (bufferIndex * sizeof(char)))), sourceBytesToCopy: (long)count * sizeof(char)); } } /// <summary> /// Trim the specified values from the end of the buffer. If nothing is specified, nothing is trimmed. /// </summary> [System.Security.SecuritySafeCritical] public unsafe void TrimEnd(char[] values) { if (values == null || values.Length == 0 || _length == 0) return; char* end = CharPointer + _length - 1; while (_length > 0 && Array.IndexOf(values, *end) >= 0) { Length = _length - 1; end--; } } /// <summary> /// String representation of the entire buffer. If the buffer is larger than the maximum size string (int.MaxValue) this will throw. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the buffer is too big to fit into a string.</exception> [System.Security.SecuritySafeCritical] public unsafe override string ToString() { if (_length == 0) return string.Empty; if (_length > int.MaxValue) throw new InvalidOperationException(); return new string(CharPointer, startIndex: 0, length: (int)_length); } /// <summary> /// Get the given substring in the buffer. /// </summary> /// <param name="count">Count of characters to take, or remaining characters from <paramref name="startIndex"/> if -1.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="startIndex"/> or <paramref name="count"/> are outside the range of the buffer's length /// or count is greater than the maximum string size (int.MaxValue). /// </exception> [System.Security.SecuritySafeCritical] public unsafe string Substring(uint startIndex, int count = -1) { if (startIndex > (_length == 0 ? 0 : _length - 1)) throw new ArgumentOutOfRangeException(nameof(startIndex)); if (count < -1) throw new ArgumentOutOfRangeException(nameof(count)); uint realCount = count == -1 ? _length - startIndex : (uint)count; if (realCount > int.MaxValue || checked(startIndex + realCount) > _length) throw new ArgumentOutOfRangeException(nameof(count)); if (realCount == 0) return string.Empty; // The buffer could be bigger than will fit into a string, but the substring might fit. As the starting // index might be bigger than int we need to index ourselves. return new string(value: CharPointer + startIndex, startIndex: 0, length: (int)realCount); } [System.Security.SecuritySafeCritical] public override void Free() { base.Free(); _length = 0; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using proto = Google.Protobuf; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.TextToSpeech.V1Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTextToSpeechClientTest { [xunit::FactAttribute] public void ListVoicesRequestObject() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); ListVoicesRequest request = new ListVoicesRequest { LanguageCode = "language_code2f6c7160", }; ListVoicesResponse expectedResponse = new ListVoicesResponse { Voices = { new Voice(), }, }; mockGrpcClient.Setup(x => x.ListVoices(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); ListVoicesResponse response = client.ListVoices(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ListVoicesRequestObjectAsync() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); ListVoicesRequest request = new ListVoicesRequest { LanguageCode = "language_code2f6c7160", }; ListVoicesResponse expectedResponse = new ListVoicesResponse { Voices = { new Voice(), }, }; mockGrpcClient.Setup(x => x.ListVoicesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListVoicesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); ListVoicesResponse responseCallSettings = await client.ListVoicesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ListVoicesResponse responseCancellationToken = await client.ListVoicesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ListVoices() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); ListVoicesRequest request = new ListVoicesRequest { LanguageCode = "language_code2f6c7160", }; ListVoicesResponse expectedResponse = new ListVoicesResponse { Voices = { new Voice(), }, }; mockGrpcClient.Setup(x => x.ListVoices(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); ListVoicesResponse response = client.ListVoices(request.LanguageCode); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ListVoicesAsync() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); ListVoicesRequest request = new ListVoicesRequest { LanguageCode = "language_code2f6c7160", }; ListVoicesResponse expectedResponse = new ListVoicesResponse { Voices = { new Voice(), }, }; mockGrpcClient.Setup(x => x.ListVoicesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListVoicesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); ListVoicesResponse responseCallSettings = await client.ListVoicesAsync(request.LanguageCode, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ListVoicesResponse responseCancellationToken = await client.ListVoicesAsync(request.LanguageCode, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SynthesizeSpeechRequestObject() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); SynthesizeSpeechRequest request = new SynthesizeSpeechRequest { Input = new SynthesisInput(), Voice = new VoiceSelectionParams(), AudioConfig = new AudioConfig(), EnableTimePointing = { SynthesizeSpeechRequest.Types.TimepointType.Unspecified, }, }; SynthesizeSpeechResponse expectedResponse = new SynthesizeSpeechResponse { AudioContent = proto::ByteString.CopyFromUtf8("audio_content20992f23"), Timepoints = { new Timepoint(), }, AudioConfig = new AudioConfig(), }; mockGrpcClient.Setup(x => x.SynthesizeSpeech(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); SynthesizeSpeechResponse response = client.SynthesizeSpeech(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SynthesizeSpeechRequestObjectAsync() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); SynthesizeSpeechRequest request = new SynthesizeSpeechRequest { Input = new SynthesisInput(), Voice = new VoiceSelectionParams(), AudioConfig = new AudioConfig(), EnableTimePointing = { SynthesizeSpeechRequest.Types.TimepointType.Unspecified, }, }; SynthesizeSpeechResponse expectedResponse = new SynthesizeSpeechResponse { AudioContent = proto::ByteString.CopyFromUtf8("audio_content20992f23"), Timepoints = { new Timepoint(), }, AudioConfig = new AudioConfig(), }; mockGrpcClient.Setup(x => x.SynthesizeSpeechAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SynthesizeSpeechResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); SynthesizeSpeechResponse responseCallSettings = await client.SynthesizeSpeechAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SynthesizeSpeechResponse responseCancellationToken = await client.SynthesizeSpeechAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SynthesizeSpeech() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); SynthesizeSpeechRequest request = new SynthesizeSpeechRequest { Input = new SynthesisInput(), Voice = new VoiceSelectionParams(), AudioConfig = new AudioConfig(), }; SynthesizeSpeechResponse expectedResponse = new SynthesizeSpeechResponse { AudioContent = proto::ByteString.CopyFromUtf8("audio_content20992f23"), Timepoints = { new Timepoint(), }, AudioConfig = new AudioConfig(), }; mockGrpcClient.Setup(x => x.SynthesizeSpeech(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); SynthesizeSpeechResponse response = client.SynthesizeSpeech(request.Input, request.Voice, request.AudioConfig); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SynthesizeSpeechAsync() { moq::Mock<TextToSpeech.TextToSpeechClient> mockGrpcClient = new moq::Mock<TextToSpeech.TextToSpeechClient>(moq::MockBehavior.Strict); SynthesizeSpeechRequest request = new SynthesizeSpeechRequest { Input = new SynthesisInput(), Voice = new VoiceSelectionParams(), AudioConfig = new AudioConfig(), }; SynthesizeSpeechResponse expectedResponse = new SynthesizeSpeechResponse { AudioContent = proto::ByteString.CopyFromUtf8("audio_content20992f23"), Timepoints = { new Timepoint(), }, AudioConfig = new AudioConfig(), }; mockGrpcClient.Setup(x => x.SynthesizeSpeechAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SynthesizeSpeechResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TextToSpeechClient client = new TextToSpeechClientImpl(mockGrpcClient.Object, null); SynthesizeSpeechResponse responseCallSettings = await client.SynthesizeSpeechAsync(request.Input, request.Voice, request.AudioConfig, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SynthesizeSpeechResponse responseCancellationToken = await client.SynthesizeSpeechAsync(request.Input, request.Voice, request.AudioConfig, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using NUnit.Framework; using QuantConnect.Api; using QuantConnect.Optimizer; using QuantConnect.Optimizer.Objectives; using QuantConnect.Optimizer.Parameters; using QuantConnect.Statistics; using QuantConnect.Util; namespace QuantConnect.Tests.API { /// <summary> /// Tests API account and optimizations endpoints /// </summary> [TestFixture, Explicit("Requires configured api access")] public class OptimizationTests : ApiTestBase { private int testProjectId = 1; // "EnterProjectHere"; private string testOptimizationId = "EnterOptimizationHere"; private string _validSerialization = "{\"optimizationId\":\"myOptimizationId\",\"name\":\"myOptimizationName\",\"runtimeStatistics\":{\"Completed\":\"1\"},"+ "\"constraints\":[{\"target\":\"TotalPerformance.PortfolioStatistics.SharpeRatio\",\"operator\":\"GreaterOrEqual\",\"target-value\":1}],"+ "\"parameters\":[{\"name\":\"myParamName\",\"min\":2,\"max\":4,\"step\":1}],\"nodeType\":\"O2-8\",\"parallelNodes\":12,\"projectId\":1234567,\"status\":\"completed\","+ "\"backtests\":{\"myBacktestKey\":{\"name\":\"myBacktestName\",\"id\":\"myBacktestId\",\"progress\":1,\"exitCode\":0,"+ "\"statistics\":[0.374,0.217,0.047,-4.51,2.86,-0.664,52.602,17.800,6300000.00,0.196,1.571,27.0,123.888,77.188,0.63,1.707,1390.49,180.0,0.233,-0.558,73.0]," + "\"parameterSet\":{\"myParamName\":\"2\"},\"equity\":[]}},\"strategy\":\"QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy\"," + "\"requested\":\"2021-12-16 00:51:58\",\"criterion\":{\"extremum\":\"max\",\"target\":\"TotalPerformance.PortfolioStatistics.SharpeRatio\",\"targetValue\":null}}"; private string _validEstimateSerialization = "{\"estimateId\":\"myEstimateId\",\"time\":26,\"balance\":500}"; [Test] public void Deserialization() { var deserialized = JsonConvert.DeserializeObject<Optimization>(_validSerialization); Assert.IsNotNull(deserialized); Assert.AreEqual("myOptimizationId", deserialized.OptimizationId); Assert.AreEqual("myOptimizationName", deserialized.Name); Assert.IsTrue(deserialized.RuntimeStatistics.Count == 1); Assert.IsTrue(deserialized.RuntimeStatistics["Completed"] == "1"); Assert.IsTrue(deserialized.Constraints.Count == 1); Assert.AreEqual("['TotalPerformance'].['PortfolioStatistics'].['SharpeRatio']", deserialized.Constraints[0].Target); Assert.IsTrue(deserialized.Constraints[0].Operator == ComparisonOperatorTypes.GreaterOrEqual); Assert.IsTrue(deserialized.Constraints[0].TargetValue == 1); Assert.IsTrue(deserialized.Parameters.Count == 1); var stepParam = deserialized.Parameters.First().ConvertInvariant<OptimizationStepParameter>(); Assert.IsTrue(stepParam.Name == "myParamName"); Assert.IsTrue(stepParam.MinValue == 2); Assert.IsTrue(stepParam.MaxValue == 4); Assert.IsTrue(stepParam.Step == 1); Assert.AreEqual(OptimizationNodes.O2_8, deserialized.NodeType); Assert.AreEqual(12, deserialized.ParallelNodes); Assert.AreEqual(1234567, deserialized.ProjectId); Assert.AreEqual(OptimizationStatus.Completed, deserialized.Status); Assert.IsTrue(deserialized.Backtests.Count == 1); Assert.IsTrue(deserialized.Backtests["myBacktestKey"].BacktestId == "myBacktestId"); Assert.IsTrue(deserialized.Backtests["myBacktestKey"].Name == "myBacktestName"); Assert.IsTrue(deserialized.Backtests["myBacktestKey"].ParameterSet.Value["myParamName"] == "2"); Assert.IsTrue(deserialized.Backtests["myBacktestKey"].Statistics[PerformanceMetrics.ProbabilisticSharpeRatio] == "77.188"); Assert.AreEqual("QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy", deserialized.Strategy); Assert.AreEqual(new DateTime(2021, 12, 16, 00, 51, 58), deserialized.Requested); Assert.AreEqual("['TotalPerformance'].['PortfolioStatistics'].['SharpeRatio']", deserialized.Criterion.Target); Assert.IsInstanceOf<Maximization>(deserialized.Criterion.Extremum); Assert.IsNull(deserialized.Criterion.TargetValue); } [Test] public void EstimateDeserialization() { var deserialized = JsonConvert.DeserializeObject<Estimate>(_validEstimateSerialization); Assert.AreEqual("myEstimateId", deserialized.EstimateId); Assert.AreEqual(26, deserialized.Time); Assert.AreEqual(500, deserialized.Balance); } [Test] public void EstimateOptimization() { var compile = ApiClient.CreateCompile(testProjectId); var estimate = ApiClient.EstimateOptimization( projectId: testProjectId, name: "My Testable Optimization", target: "TotalPerformance.PortfolioStatistics.SharpeRatio", targetTo: "max", targetValue: null, strategy: "QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy", compileId: compile.CompileId, parameters: new HashSet<OptimizationParameter> { new OptimizationStepParameter("atrRatioTP", 4, 5, 1, 1) // Replace params with valid optimization parameter data for test project }, constraints: new List<Constraint> { new Constraint("TotalPerformance.PortfolioStatistics.SharpeRatio", ComparisonOperatorTypes.GreaterOrEqual, 1) } ); Assert.IsNotNull(estimate); Assert.IsNotEmpty(estimate.EstimateId); Assert.GreaterOrEqual(estimate.Time, 0); Assert.GreaterOrEqual(estimate.Balance, 0); } [Test] public void CreateOptimization() { var compile = ApiClient.CreateCompile(testProjectId); var optimization = ApiClient.CreateOptimization( projectId: testProjectId, name: "My Testable Optimization", target: "TotalPerformance.PortfolioStatistics.SharpeRatio", targetTo: "max", targetValue: null, strategy: "QuantConnect.Optimizer.Strategies.GridSearchOptimizationStrategy", compileId: compile.CompileId, parameters: new HashSet<OptimizationParameter> { new OptimizationStepParameter("atrRatioTP", 4, 5, 1, 1) // Replace params with valid optimization parameter data for test project }, constraints: new List<Constraint> { new Constraint("TotalPerformance.PortfolioStatistics.SharpeRatio", ComparisonOperatorTypes.GreaterOrEqual, 1) }, estimatedCost: 0.06m, nodeType: OptimizationNodes.O2_8, parallelNodes: 12 ); TestBaseOptimization(optimization); } [Test] public void ListOptimizations() { var optimizations = ApiClient.ListOptimizations(testProjectId); Assert.IsNotNull(optimizations); Assert.IsTrue(optimizations.Any()); TestBaseOptimization(optimizations.First()); } [Test] public void ReadOptimization() { var optimization = ApiClient.ReadOptimization(testOptimizationId); TestBaseOptimization(optimization); Assert.IsTrue(optimization.RuntimeStatistics.Any()); Assert.IsTrue(optimization.Constraints.Any()); Assert.IsTrue(optimization.Parameters.Any()); Assert.Positive(optimization.ParallelNodes); Assert.IsTrue(optimization.Backtests.Any()); Assert.IsNotEmpty(optimization.Strategy); Assert.AreNotEqual(default(DateTime), optimization.Requested); } [Test] public void AbortOptimization() { var response = ApiClient.AbortOptimization(testOptimizationId); Assert.IsTrue(response.Success); } [Test] public void UpdateOptimization() { var response = ApiClient.UpdateOptimization(testOptimizationId, "Alert Yellow Submarine"); Assert.IsTrue(response.Success); } [Test] public void DeleteOptimization() { var response = ApiClient.DeleteOptimization(testOptimizationId); Assert.IsTrue(response.Success); } private void TestBaseOptimization(BaseOptimization optimization) { Assert.IsNotNull(optimization); Assert.IsNotEmpty(optimization.OptimizationId); Assert.Positive(optimization.ProjectId); Assert.IsNotEmpty(optimization.Name); Assert.IsInstanceOf<OptimizationStatus>(optimization.Status); Assert.IsNotEmpty(optimization.NodeType); Assert.IsNotNull(optimization.Criterion); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Collections; using System.IO; using System.Text; using NPOI.Util; using NPOI.SS.Util; using System.Collections.Generic; /** * Title: Bound Sheet Record (aka BundleSheet) * Description: Defines a sheet within a workbook. Basically stores the sheetname * and tells where the Beginning of file record Is within the HSSF * file. * REFERENCE: PG 291 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2) * @author Andrew C. Oliver (acoliver at apache dot org) * @author Sergei Kozello (sergeikozello at mail.ru) */ internal class BoundSheetRecord : StandardRecord { public const short sid = 0x85; private static BitField hiddenFlag = BitFieldFactory.GetInstance(0x01); private static BitField veryHiddenFlag = BitFieldFactory.GetInstance(0x02); private int field_1_position_of_BOF; private int field_2_option_flags; private int field_4_isMultibyteUnicode; private String field_5_sheetname; public BoundSheetRecord(String sheetname) { field_2_option_flags = 0; this.Sheetname=sheetname; } /** * Constructs a BoundSheetRecord and Sets its fields appropriately * * @param in the RecordInputstream to Read the record from */ public BoundSheetRecord(RecordInputStream in1) { field_1_position_of_BOF = in1.ReadInt(); // bof field_2_option_flags = in1.ReadShort(); // flags int field_3_sheetname_length = in1.ReadUByte(); // len(str) field_4_isMultibyteUnicode = (byte)in1.ReadByte(); // Unicode if (this.IsMultibyte) { field_5_sheetname = in1.ReadUnicodeLEString(field_3_sheetname_length); } else { field_5_sheetname = in1.ReadCompressedUnicode(field_3_sheetname_length); } } /** * Get the offset in bytes of the Beginning of File Marker within the HSSF Stream part of the POIFS file * * @return offset in bytes */ public int PositionOfBof { get { return field_1_position_of_BOF; } set { field_1_position_of_BOF = value; } } /** * Is the sheet very hidden? Different from (normal) hidden */ public bool IsVeryHidden { get { return veryHiddenFlag.IsSet(field_2_option_flags); } set { field_2_option_flags = veryHiddenFlag.SetBoolean(field_2_option_flags, value); } } /** * Get the sheetname for this sheet. (this appears in the tabs at the bottom) * @return sheetname the name of the sheet */ public String Sheetname { get { return field_5_sheetname; } set { WorkbookUtil.ValidateSheetName(value); field_5_sheetname = value; field_4_isMultibyteUnicode = (StringUtil.HasMultibyte(value) ? (byte)1 : (byte)0); } } private bool IsMultibyte { get { return (field_4_isMultibyteUnicode & 0x01) != 0; } } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[BOUNDSHEET]\n"); buffer.Append(" .bof = ").Append(HexDump.IntToHex(PositionOfBof)).Append("\n"); buffer.Append(" .options = ").Append(HexDump.ShortToHex(field_2_option_flags)).Append("\n"); buffer.Append(" .unicodeflag= ").Append(HexDump.ByteToHex(field_4_isMultibyteUnicode)).Append("\n"); buffer.Append(" .sheetname = ").Append(field_5_sheetname).Append("\n"); buffer.Append("[/BOUNDSHEET]\n"); return buffer.ToString(); } protected override int DataSize { get { return 8 + field_5_sheetname.Length * (IsMultibyte ? 2 : 1); } } public override void Serialize(ILittleEndianOutput out1) { out1.WriteInt(PositionOfBof); out1.WriteShort(field_2_option_flags); String name = field_5_sheetname; out1.WriteByte(name.Length); out1.WriteByte(field_4_isMultibyteUnicode); if (IsMultibyte) { StringUtil.PutUnicodeLE(name, out1); } else { StringUtil.PutCompressedUnicode(name, out1); } } public override short Sid { get { return sid; } } public bool IsHidden { get { return hiddenFlag.IsSet(field_2_option_flags); } set { field_2_option_flags = hiddenFlag.SetBoolean(field_2_option_flags, value); } } /** * Converts a List of {@link BoundSheetRecord}s to an array and sorts by the position of their * BOFs. */ public static BoundSheetRecord[] OrderByBofPosition(List<BoundSheetRecord> boundSheetRecords) { BoundSheetRecord[] bsrs = boundSheetRecords.ToArray(); Array.Sort(bsrs, new BOFComparator()); return bsrs; } private class BOFComparator : IComparer<BoundSheetRecord> { public int Compare(BoundSheetRecord bsr1, BoundSheetRecord bsr2) { return bsr1.PositionOfBof - bsr2.PositionOfBof; } }; } }
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Umbraco.Cms.Core.Mapping; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Web.Common.DependencyInjection; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Security { /// <summary> /// A custom user store that uses Umbraco member data /// </summary> public class MemberUserStore : UmbracoUserStore<MemberIdentityUser, UmbracoIdentityRole>, IMemberUserStore { private const string GenericIdentityErrorCode = "IdentityErrorUserStore"; private readonly IMemberService _memberService; private readonly IUmbracoMapper _mapper; private readonly IScopeProvider _scopeProvider; private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor; private readonly IExternalLoginWithKeyService _externalLoginService; private readonly ITwoFactorLoginService _twoFactorLoginService; /// <summary> /// Initializes a new instance of the <see cref="MemberUserStore"/> class for the members identity store /// </summary> /// <param name="memberService">The member service</param> /// <param name="mapper">The mapper for properties</param> /// <param name="scopeProvider">The scope provider</param> /// <param name="describer">The error describer</param> /// <param name="publishedSnapshotAccessor">The published snapshot accessor</param> /// <param name="externalLoginService">The external login service</param> /// <param name="twoFactorLoginService">The two factor login service</param> [ActivatorUtilitiesConstructor] public MemberUserStore( IMemberService memberService, IUmbracoMapper mapper, IScopeProvider scopeProvider, IdentityErrorDescriber describer, IPublishedSnapshotAccessor publishedSnapshotAccessor, IExternalLoginWithKeyService externalLoginService, ITwoFactorLoginService twoFactorLoginService ) : base(describer) { _memberService = memberService ?? throw new ArgumentNullException(nameof(memberService)); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); _scopeProvider = scopeProvider ?? throw new ArgumentNullException(nameof(scopeProvider)); _publishedSnapshotAccessor = publishedSnapshotAccessor; _externalLoginService = externalLoginService; _twoFactorLoginService = twoFactorLoginService; } [Obsolete("Use ctor with IExternalLoginWithKeyService and ITwoFactorLoginService param")] public MemberUserStore( IMemberService memberService, IUmbracoMapper mapper, IScopeProvider scopeProvider, IdentityErrorDescriber describer, IPublishedSnapshotAccessor publishedSnapshotAccessor, IExternalLoginService externalLoginService) : this(memberService, mapper, scopeProvider, describer, publishedSnapshotAccessor, StaticServiceProvider.Instance.GetRequiredService<IExternalLoginWithKeyService>(), StaticServiceProvider.Instance.GetRequiredService<ITwoFactorLoginService>()) { } [Obsolete("Use ctor with IExternalLoginWithKeyService and ITwoFactorLoginService param")] public MemberUserStore( IMemberService memberService, IUmbracoMapper mapper, IScopeProvider scopeProvider, IdentityErrorDescriber describer, IPublishedSnapshotAccessor publishedSnapshotAccessor) : this(memberService, mapper, scopeProvider, describer, publishedSnapshotAccessor, StaticServiceProvider.Instance.GetRequiredService<IExternalLoginWithKeyService>(), StaticServiceProvider.Instance.GetRequiredService<ITwoFactorLoginService>()) { } /// <inheritdoc /> public override Task<IdentityResult> CreateAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { try { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } using IScope scope = _scopeProvider.CreateScope(autoComplete: true); // create member IMember memberEntity = _memberService.CreateMember( user.UserName, user.Email, user.Name.IsNullOrWhiteSpace() ? user.UserName : user.Name, user.MemberTypeAlias.IsNullOrWhiteSpace() ? Constants.Security.DefaultMemberTypeAlias : user.MemberTypeAlias); UpdateMemberProperties(memberEntity, user); // create the member _memberService.Save(memberEntity); //We need to add roles now that the member has an Id. It do not work implicit in UpdateMemberProperties _memberService.AssignRoles(new[] { memberEntity.Id }, user.Roles.Select(x => x.RoleId).ToArray()); if (!memberEntity.HasIdentity) { throw new DataException("Could not create the member, check logs for details"); } // re-assign id user.Id = UserIdToString(memberEntity.Id); user.Key = memberEntity.Key; // we have to remember whether Logins property is dirty, since the UpdateMemberProperties will reset it. var isLoginsPropertyDirty = user.IsPropertyDirty(nameof(MemberIdentityUser.Logins)); var isTokensPropertyDirty = user.IsPropertyDirty(nameof(MemberIdentityUser.LoginTokens)); if (isLoginsPropertyDirty) { _externalLoginService.Save( memberEntity.Key, user.Logins.Select(x => new ExternalLogin( x.LoginProvider, x.ProviderKey, x.UserData))); } if (isTokensPropertyDirty) { _externalLoginService.Save( memberEntity.Key, user.LoginTokens.Select(x => new ExternalLoginToken( x.LoginProvider, x.Name, x.Value))); } return Task.FromResult(IdentityResult.Success); } catch (Exception ex) { return Task.FromResult(IdentityResult.Failed(new IdentityError { Code = GenericIdentityErrorCode, Description = ex.Message })); } } /// <inheritdoc /> public override Task<IdentityResult> UpdateAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { try { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (!int.TryParse(user.Id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var asInt)) { //TODO: should this be thrown, or an identity result? throw new InvalidOperationException("The user id must be an integer to work with the Umbraco"); } using IScope scope = _scopeProvider.CreateScope(autoComplete: true); IMember found = _memberService.GetById(asInt); if (found != null) { // we have to remember whether Logins property is dirty, since the UpdateMemberProperties will reset it. var isLoginsPropertyDirty = user.IsPropertyDirty(nameof(MemberIdentityUser.Logins)); MemberDataChangeType memberChangeType = UpdateMemberProperties(found, user); if (memberChangeType == MemberDataChangeType.FullSave) { _memberService.Save(found); } else if (memberChangeType == MemberDataChangeType.LoginOnly) { // If the member is only logging in, just issue that command without // any write locks so we are creating a bottleneck. _memberService.SetLastLogin(found.Username, DateTime.Now); } if (isLoginsPropertyDirty) { _externalLoginService.Save( found.Key, user.Logins.Select(x => new ExternalLogin( x.LoginProvider, x.ProviderKey, x.UserData))); } } return Task.FromResult(IdentityResult.Success); } catch (Exception ex) { return Task.FromResult(IdentityResult.Failed(new IdentityError { Code = GenericIdentityErrorCode, Description = ex.Message })); } } /// <inheritdoc /> public override Task<IdentityResult> DeleteAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { try { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } IMember found = _memberService.GetById(UserIdToInt(user.Id)); if (found != null) { _memberService.Delete(found); } _externalLoginService.DeleteUserLogins(user.Key); return Task.FromResult(IdentityResult.Success); } catch (Exception ex) { return Task.FromResult(IdentityResult.Failed(new IdentityError { Code = GenericIdentityErrorCode, Description = ex.Message })); } } /// <inheritdoc /> protected override Task<MemberIdentityUser> FindUserAsync(string userId, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(userId)) { throw new ArgumentNullException(nameof(userId)); } IMember user = Guid.TryParse(userId, out var key) ? _memberService.GetByKey(key) : _memberService.GetById(UserIdToInt(userId)); if (user == null) { return Task.FromResult((MemberIdentityUser)null); } return Task.FromResult(AssignLoginsCallback(_mapper.Map<MemberIdentityUser>(user))); } /// <inheritdoc /> public override Task<MemberIdentityUser> FindByNameAsync(string userName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); IMember user = _memberService.GetByUsername(userName); if (user == null) { return Task.FromResult((MemberIdentityUser)null); } MemberIdentityUser result = AssignLoginsCallback(_mapper.Map<MemberIdentityUser>(user)); return Task.FromResult(result); } /// <inheritdoc /> public override Task<MemberIdentityUser> FindByEmailAsync(string email, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); IMember member = _memberService.GetByEmail(email); MemberIdentityUser result = member == null ? null : _mapper.Map<MemberIdentityUser>(member); return Task.FromResult(AssignLoginsCallback(result)); } /// <inheritdoc /> public override Task AddLoginAsync(MemberIdentityUser user, UserLoginInfo login, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (login == null) { throw new ArgumentNullException(nameof(login)); } if (string.IsNullOrWhiteSpace(login.LoginProvider)) { throw new ArgumentNullException(nameof(login.LoginProvider)); } if (string.IsNullOrWhiteSpace(login.ProviderKey)) { throw new ArgumentNullException(nameof(login.ProviderKey)); } ICollection<IIdentityUserLogin> logins = user.Logins; var instance = new IdentityUserLogin( login.LoginProvider, login.ProviderKey, user.Id.ToString()); IdentityUserLogin userLogin = instance; logins.Add(userLogin); return Task.CompletedTask; } /// <inheritdoc /> public override Task RemoveLoginAsync(MemberIdentityUser user, string loginProvider, string providerKey, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrWhiteSpace(loginProvider)) { throw new ArgumentNullException(nameof(loginProvider)); } if (string.IsNullOrWhiteSpace(providerKey)) { throw new ArgumentNullException(nameof(providerKey)); } IIdentityUserLogin userLogin = user.Logins.SingleOrDefault(l => l.LoginProvider == loginProvider && l.ProviderKey == providerKey); if (userLogin != null) { user.Logins.Remove(userLogin); } return Task.CompletedTask; } /// <inheritdoc /> public override Task<IList<UserLoginInfo>> GetLoginsAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult((IList<UserLoginInfo>)user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey, l.LoginProvider)).ToList()); } /// <inheritdoc /> protected override async Task<IdentityUserLogin<string>> FindUserLoginAsync(string userId, string loginProvider, string providerKey, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(loginProvider)) { throw new ArgumentNullException(nameof(loginProvider)); } if (string.IsNullOrWhiteSpace(providerKey)) { throw new ArgumentNullException(nameof(providerKey)); } MemberIdentityUser user = await FindUserAsync(userId, cancellationToken); if (user == null) { return await Task.FromResult((IdentityUserLogin<string>)null); } IList<UserLoginInfo> logins = await GetLoginsAsync(user, cancellationToken); UserLoginInfo found = logins.FirstOrDefault(x => x.ProviderKey == providerKey && x.LoginProvider == loginProvider); if (found == null) { return await Task.FromResult((IdentityUserLogin<string>)null); } return new IdentityUserLogin<string> { LoginProvider = found.LoginProvider, ProviderKey = found.ProviderKey, // TODO: We don't store this value so it will be null ProviderDisplayName = found.ProviderDisplayName, UserId = user.Id }; } /// <inheritdoc /> protected override Task<IdentityUserLogin<string>> FindUserLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(loginProvider)) { throw new ArgumentNullException(nameof(loginProvider)); } if (string.IsNullOrWhiteSpace(providerKey)) { throw new ArgumentNullException(nameof(providerKey)); } var logins = _externalLoginService.Find(loginProvider, providerKey).ToList(); if (logins.Count == 0) { return Task.FromResult((IdentityUserLogin<string>)null); } IIdentityUserLogin found = logins[0]; return Task.FromResult(new IdentityUserLogin<string> { LoginProvider = found.LoginProvider, ProviderKey = found.ProviderKey, // TODO: We don't store this value so it will be null ProviderDisplayName = null, UserId = found.UserId }); } /// <summary> /// Gets a list of role names the specified user belongs to. /// </summary> /// <remarks> /// This lazy loads the roles for the member /// </remarks> public override Task<IList<string>> GetRolesAsync(MemberIdentityUser user, CancellationToken cancellationToken = default) { EnsureRoles(user); return base.GetRolesAsync(user, cancellationToken); } private void EnsureRoles(MemberIdentityUser user) { if (user.Roles.Count == 0) { // if there are no roles, they either haven't been loaded since we don't eagerly // load for members, or they just have no roles. IEnumerable<string> currentRoles = _memberService.GetAllRoles(user.UserName); ICollection<IdentityUserRole<string>> roles = currentRoles.Select(role => new IdentityUserRole<string> { RoleId = role, UserId = user.Id }).ToList(); user.Roles = roles; } } /// <summary> /// Returns true if a user is in the role /// </summary> public override Task<bool> IsInRoleAsync(MemberIdentityUser user, string roleName, CancellationToken cancellationToken = default) { EnsureRoles(user); return base.IsInRoleAsync(user, roleName, cancellationToken); } /// <summary> /// Lists all users of a given role. /// </summary> public override Task<IList<MemberIdentityUser>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(roleName)) { throw new ArgumentNullException(nameof(roleName)); } IEnumerable<IMember> members = _memberService.GetMembersByMemberType(roleName); IList<MemberIdentityUser> membersIdentityUsers = members.Select(x => _mapper.Map<MemberIdentityUser>(x)).ToList(); return Task.FromResult(membersIdentityUsers); } /// <inheritdoc/> protected override Task<UmbracoIdentityRole> FindRoleAsync(string roleName, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(roleName)) { throw new ArgumentNullException(nameof(roleName)); } IMemberGroup group = _memberService.GetAllRoles().SingleOrDefault(x => x.Name == roleName); if (group == null) { return Task.FromResult((UmbracoIdentityRole)null); } return Task.FromResult(new UmbracoIdentityRole(group.Name) { //TODO: what should the alias be? Id = group.Id.ToString() }); } /// <inheritdoc/> protected override async Task<IdentityUserRole<string>> FindUserRoleAsync(string userId, string roleId, CancellationToken cancellationToken) { MemberIdentityUser user = await FindUserAsync(userId, cancellationToken); if (user == null) { return null; } IdentityUserRole<string> found = user.Roles.FirstOrDefault(x => x.RoleId.InvariantEquals(roleId)); return found; } private MemberIdentityUser AssignLoginsCallback(MemberIdentityUser user) { if (user != null) { user.SetLoginsCallback(new Lazy<IEnumerable<IIdentityUserLogin>>(() => _externalLoginService.GetExternalLogins(user.Key))); user.SetTokensCallback(new Lazy<IEnumerable<IIdentityUserToken>>(() => _externalLoginService.GetExternalLoginTokens(user.Key))); } return user; } private MemberDataChangeType UpdateMemberProperties(IMember member, MemberIdentityUser identityUser) { MemberDataChangeType changeType = MemberDataChangeType.None; // don't assign anything if nothing has changed as this will trigger the track changes of the model if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastLoginDateUtc)) || (member.LastLoginDate != default && identityUser.LastLoginDateUtc.HasValue == false) || (identityUser.LastLoginDateUtc.HasValue && member.LastLoginDate.ToUniversalTime() != identityUser.LastLoginDateUtc.Value)) { changeType = MemberDataChangeType.LoginOnly; // if the LastLoginDate is being set to MinValue, don't convert it ToLocalTime DateTime dt = identityUser.LastLoginDateUtc == DateTime.MinValue ? DateTime.MinValue : identityUser.LastLoginDateUtc.Value.ToLocalTime(); member.LastLoginDate = dt; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.LastPasswordChangeDateUtc)) || (member.LastPasswordChangeDate != default && identityUser.LastPasswordChangeDateUtc.HasValue == false) || (identityUser.LastPasswordChangeDateUtc.HasValue && member.LastPasswordChangeDate.ToUniversalTime() != identityUser.LastPasswordChangeDateUtc.Value)) { changeType = MemberDataChangeType.FullSave; member.LastPasswordChangeDate = identityUser.LastPasswordChangeDateUtc.Value.ToLocalTime(); } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Comments)) && member.Comments != identityUser.Comments && identityUser.Comments.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.Comments = identityUser.Comments; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.EmailConfirmed)) || (member.EmailConfirmedDate.HasValue && member.EmailConfirmedDate.Value != default && identityUser.EmailConfirmed == false) || ((member.EmailConfirmedDate.HasValue == false || member.EmailConfirmedDate.Value == default) && identityUser.EmailConfirmed)) { changeType = MemberDataChangeType.FullSave; member.EmailConfirmedDate = identityUser.EmailConfirmed ? (DateTime?)DateTime.Now : null; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Name)) && member.Name != identityUser.Name && identityUser.Name.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.Name = identityUser.Name; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Email)) && member.Email != identityUser.Email && identityUser.Email.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.Email = identityUser.Email; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.AccessFailedCount)) && member.FailedPasswordAttempts != identityUser.AccessFailedCount) { changeType = MemberDataChangeType.FullSave; member.FailedPasswordAttempts = identityUser.AccessFailedCount; } if (member.IsLockedOut != identityUser.IsLockedOut) { changeType = MemberDataChangeType.FullSave; member.IsLockedOut = identityUser.IsLockedOut; if (member.IsLockedOut) { // need to set the last lockout date member.LastLockoutDate = DateTime.Now; } } if (member.IsApproved != identityUser.IsApproved) { changeType = MemberDataChangeType.FullSave; member.IsApproved = identityUser.IsApproved; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.UserName)) && member.Username != identityUser.UserName && identityUser.UserName.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.Username = identityUser.UserName; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.PasswordHash)) && member.RawPasswordValue != identityUser.PasswordHash && identityUser.PasswordHash.IsNullOrWhiteSpace() == false) { changeType = MemberDataChangeType.FullSave; member.RawPasswordValue = identityUser.PasswordHash; member.PasswordConfiguration = identityUser.PasswordConfig; } if (member.PasswordConfiguration != identityUser.PasswordConfig) { changeType = MemberDataChangeType.FullSave; member.PasswordConfiguration = identityUser.PasswordConfig; } if (member.SecurityStamp != identityUser.SecurityStamp) { changeType = MemberDataChangeType.FullSave; member.SecurityStamp = identityUser.SecurityStamp; } if (identityUser.IsPropertyDirty(nameof(MemberIdentityUser.Roles))) { changeType = MemberDataChangeType.FullSave; var identityUserRoles = identityUser.Roles.Select(x => x.RoleId).ToArray(); _memberService.ReplaceRoles(new[] { member.Id }, identityUserRoles); } // reset all changes identityUser.ResetDirtyProperties(false); return changeType; } public IPublishedContent GetPublishedMember(MemberIdentityUser user) { if (user == null) { return null; } IMember member = _memberService.GetByKey(user.Key); if (member == null) { return null; } var publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot(); return publishedSnapshot.Members.Get(member); } private enum MemberDataChangeType { None, LoginOnly, FullSave } /// <summary> /// Overridden to support Umbraco's own data storage requirements /// </summary> /// <remarks> /// The base class's implementation of this calls into FindTokenAsync, RemoveUserTokenAsync and AddUserTokenAsync, both methods will only work with ORMs that are change /// tracking ORMs like EFCore. /// </remarks> /// <inheritdoc /> public override Task<string> GetTokenAsync(MemberIdentityUser user, string loginProvider, string name, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } IIdentityUserToken token = user.LoginTokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(loginProvider) && x.Name.InvariantEquals(name)); return Task.FromResult(token?.Value); } /// <inheritdoc /> public override async Task<bool> GetTwoFactorEnabledAsync(MemberIdentityUser user, CancellationToken cancellationToken = default(CancellationToken)) { return await _twoFactorLoginService.IsTwoFactorEnabledAsync(user.Key); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading; namespace System.Collections.Generic.Internal { /// <summary> /// HashSet; Dictionary without Value /// 1. Deriving from DictionaryBase to share common code /// 2. Hashing/bucket moved to DictionaryBase /// 3. No interface implementation. You pay for the methods called /// 4. Support FindFirstKey/FindNextKey, hash code based search (returning key to caller for key comparison) /// 5. Support GetNext for simple enumeration of items /// 6. No comparer, no interface dispatching calls /// </summary> /// <typeparam name="TKey"></typeparam> internal class HashSet<TKey> : DictionaryBase where TKey : IEquatable<TKey> { const int MinimalSize = 11; // Have non-zero minimal size so that we do not need to check for null entries private TKey[] keyArray; private Lock m_lock; public HashSet(int capacity) : this(capacity, false) { } public HashSet(int capacity, bool sync) { if (capacity < MinimalSize) { capacity = MinimalSize; } if (sync) { m_lock = new Lock(); } Initialize(capacity); } public void LockAcquire() { Debug.Assert(m_lock != null); m_lock.Acquire(); } public void LockRelease() { Debug.Assert(m_lock != null); m_lock.Release(); } public void Clear() { if (count > 0) { ClearBase(); Array.Clear(keyArray, 0, count); } } public bool ContainsKey(TKey key, int hashCode) { return FindEntry(key, hashCode) >= 0; } private int FindEntry(TKey key, int hashCode) { hashCode = hashCode & 0x7FFFFFFF; for (int i = entries[ModLength(hashCode)].bucket; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && key.Equals(keyArray[i])) { return i; } } return -1; } /// <summary> /// First first matching entry, returning index, update key /// </summary> /// <param name="key"></param> /// <returns></returns> public int FindFirstKey(ref TKey key, int hashCode) { int entry = FindFirstEntry(hashCode & 0x7FFFFFFF); if (entry >= 0) { key = keyArray[entry]; } return entry; } /// <summary> /// Find next matching entry, returning index, update key /// </summary> /// <param name="key"></param> /// <param name="entry"></param> /// <returns></returns> public int FindNextKey(ref TKey key, int entry) { entry = FindNextEntry(entry); if (entry >= 0) { key = keyArray[entry]; } return entry; } /// <summary> /// Enumeration of items /// </summary> [System.Runtime.InteropServices.GCCallback] internal bool GetNext(ref TKey key, ref int index) { for (int i = index + 1; i < this.count; i++) { if (entries[i].hashCode >= 0) { key = keyArray[i]; index = i; return true; } } return false; } [MethodImpl(MethodImplOptions.NoInlining)] private void Initialize(int capacity) { int size = InitializeBase(capacity); keyArray = new TKey[size]; } public KeyCollection Keys { get { Contract.Ensures(Contract.Result<KeyCollection>() != null); return new KeyCollection(this); } } public bool Add(TKey key, int hashCode) { hashCode = hashCode & 0x7FFFFFFF; int targetBucket = ModLength(hashCode); for (int i = entries[targetBucket].bucket; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && key.Equals(keyArray[i])) { return true; } } int index; if (freeCount > 0) { index = freeList; freeList = entries[index].next; freeCount--; } else { if (count == entries.Length) { Resize(); targetBucket = ModLength(hashCode); } index = count; count++; } entries[index].hashCode = hashCode; entries[index].next = entries[targetBucket].bucket; keyArray[index] = key; entries[targetBucket].bucket = index; return false; } private void Resize() { Resize(HashHelpers.ExpandPrime(count)); } private void Resize(int newSize) { #if !RHTESTCL Contract.Assert(newSize >= entries.Length); #endif Entry[] newEntries = ResizeBase1(newSize); TKey[] newKeys = new TKey[newSize]; Array.Copy(keyArray, 0, newKeys, 0, count); ResizeBase2(newEntries, newSize); keyArray = newKeys; } public bool Remove(TKey key, int hashCode) { hashCode = hashCode & 0x7FFFFFFF; int bucket = ModLength(hashCode); int last = -1; for (int i = entries[bucket].bucket; i >= 0; last = i, i = entries[i].next) { if (entries[i].hashCode == hashCode && key.Equals(keyArray[i])) { if (last < 0) { entries[bucket].bucket = entries[i].next; } else { entries[last].next = entries[i].next; } entries[i].hashCode = -1; entries[i].next = freeList; keyArray[i] = default(TKey); freeList = i; freeCount++; return true; } } return false; } public sealed class KeyCollection : ICollection<TKey>, ICollection { private HashSet<TKey> m_hashSet; public KeyCollection(HashSet<TKey> hashSet) { if (hashSet == null) { throw new ArgumentNullException("hashSet"); } this.m_hashSet = hashSet; } public Enumerator GetEnumerator() { return new Enumerator(m_hashSet); } public void CopyTo(TKey[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < m_hashSet.Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } int count = m_hashSet.count; TKey[] keys = m_hashSet.keyArray; Entry[] entries = m_hashSet.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = keys[i]; } } } public int Count { get { return m_hashSet.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } void ICollection<TKey>.Add(TKey item) { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear() { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Contains(TKey item) { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Remove(TKey item) { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return new Enumerator(m_hashSet); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(m_hashSet); } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < m_hashSet.Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } TKey[] keys = array as TKey[]; if (keys != null) { CopyTo(keys, index); } else { object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType); } int count = m_hashSet.count; Entry[] entries = m_hashSet.entries; TKey[] ks = m_hashSet.keyArray; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { objects[index++] = ks[i]; } } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)m_hashSet).SyncRoot; } } public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private HashSet<TKey> hashSet; private int index; private TKey currentKey; internal Enumerator(HashSet<TKey> _hashSet) { this.hashSet = _hashSet; index = 0; currentKey = default(TKey); } public void Dispose() { } public bool MoveNext() { while ((uint)index < (uint)hashSet.count) { if (hashSet.entries[index].hashCode >= 0) { currentKey = hashSet.keyArray[index]; index++; return true; } index++; } index = hashSet.count + 1; currentKey = default(TKey); return false; } public TKey Current { get { return currentKey; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || (index == hashSet.count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return currentKey; } } void System.Collections.IEnumerator.Reset() { index = 0; currentKey = default(TKey); } } } } }
using System; using System.IO; using System.Text; using NUnit.Framework; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests { [TestFixture] public class PgpPbeTest : SimpleTest { private static readonly DateTime TestDateTime = new DateTime(2003, 8, 29, 23, 35, 11, 0); private static readonly byte[] enc1 = Base64.Decode( "jA0EAwMC5M5wWBP2HBZgySvUwWFAmMRLn7dWiZN6AkQMvpE3b6qwN3SSun7zInw2" + "hxxdgFzVGfbjuB8w"); // private static readonly byte[] enc1crc = Base64.Decode("H66L"); private static readonly char[] pass = "hello world".ToCharArray(); /** * Message with both PBE and symmetric */ private static readonly byte[] testPBEAsym = Base64.Decode( "hQIOA/ZlQEFWB5vuEAf/covEUaBve7NlWWdiO5NZubdtTHGElEXzG9hyBycp9At8" + "nZGi27xOZtEGFQo7pfz4JySRc3O0s6w7PpjJSonFJyNSxuze2LuqRwFWBYYcbS8/" + "7YcjB6PqutrT939OWsozfNqivI9/QyZCjBvFU89pp7dtUngiZ6MVv81ds2I+vcvk" + "GlIFcxcE1XoCIB3EvbqWNaoOotgEPT60unnB2BeDV1KD3lDRouMIYHfZ3SzBwOOI" + "6aK39sWnY5sAK7JjFvnDAMBdueOiI0Fy+gxbFD/zFDt4cWAVSAGTC4w371iqppmT" + "25TM7zAtCgpiq5IsELPlUZZnXKmnYQ7OCeysF0eeVwf+OFB9fyvCEv/zVQocJCg8" + "fWxfCBlIVFNeNQpeGygn/ZmRaILvB7IXDWP0oOw7/F2Ym66IdYYIp2HeEZv+jFwa" + "l41w5W4BH/gtbwGjFQ6CvF/m+lfUv6ZZdzsMIeEOwhP5g7rXBxrbcnGBaU+PXbho" + "gjDqaYzAWGlrmAd6aPSj51AGeYXkb2T1T/yoJ++M3GvhH4C4hvitamDkksh/qRnM" + "M/s8Nku6z1+RXO3M6p5QC1nlAVqieU8esT43945eSoC77K8WyujDNbysDyUCUTzt" + "p/aoQwe/HgkeOTJNelKR9y2W3xinZLFzep0SqpNI/e468yB/2/LGsykIyQa7JX6r" + "BYwuBAIDAkOKfv5rK8v0YDfnN+eFqwhTcrfBj5rDH7hER6nW3lNWcMataUiHEaMg" + "o6Q0OO1vptIGxW8jClTD4N1sCNwNu9vKny8dKYDDHbCjE06DNTv7XYVW3+JqTL5E" + "BnidvGgOmA=="); /** * decrypt the passed in message stream */ private byte[] DecryptMessage( byte[] message) { PgpObjectFactory pgpF = new PgpObjectFactory(message); PgpEncryptedDataList enc = (PgpEncryptedDataList) pgpF.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[0]; Stream clear = pbe.GetDataStream(pass); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData) pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt") && !ld.FileName.Equals("_CONSOLE")) { Fail("wrong filename in packet"); } if (!ld.ModificationTime.Equals(TestDateTime)) { Fail("wrong modification time in packet: " + ld.ModificationTime + " vs " + TestDateTime); } Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (pbe.IsIntegrityProtected() && !pbe.Verify()) { Fail("integrity check failed"); } return bytes; } private byte[] DecryptMessageBuffered( byte[] message) { PgpObjectFactory pgpF = new PgpObjectFactory(message); PgpEncryptedDataList enc = (PgpEncryptedDataList) pgpF.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[0]; Stream clear = pbe.GetDataStream(pass); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData) pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); MemoryStream bOut = new MemoryStream(); if (!ld.FileName.Equals("test.txt") && !ld.FileName.Equals("_CONSOLE")) { Fail("wrong filename in packet"); } if (!ld.ModificationTime.Equals(TestDateTime)) { Fail("wrong modification time in packet: " + ld.ModificationTime.Ticks + " " + TestDateTime.Ticks); } Stream unc = ld.GetInputStream(); byte[] buf = new byte[1024]; int len; while ((len = unc.Read(buf, 0, buf.Length)) > 0) { bOut.Write(buf, 0, len); } if (pbe.IsIntegrityProtected() && !pbe.Verify()) { Fail("integrity check failed"); } return bOut.ToArray(); } public override void PerformTest() { byte[] data = DecryptMessage(enc1); if (data[0] != 'h' || data[1] != 'e' || data[2] != 'l') { Fail("wrong plain text in packet"); } // // create a PBE encrypted message and read it back. // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); // // encryption step - convert to literal data, compress, encode. // MemoryStream bOut = new UncloseableMemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream comOut = comData.Open(new UncloseableStream(bOut)); Stream ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, text.Length, TestDateTime); ldOut.Write(text, 0, text.Length); ldOut.Close(); comOut.Close(); // // encrypt - with stream close // MemoryStream cbOut = new UncloseableMemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass); byte[] bOutData = bOut.ToArray(); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - with generator close // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass); bOutData = bOut.ToArray(); cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - partial packet style. // SecureRandom rand = new SecureRandom(); byte[] test = new byte[1233]; rand.NextBytes(test); bOut = new UncloseableMemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); comOut = comData.Open(new UncloseableStream(bOut)); lData = new PgpLiteralDataGenerator(); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, TestDateTime, new byte[16]); ldOut.Write(test, 0, test.Length); lData.Close(); comData.Close(); cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, rand); cPk.AddMethod(pass); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); { byte[] tmp = bOut.ToArray(); cOut.Write(tmp, 0, tmp.Length); } cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // with integrity packet // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); bOutData = bOut.ToArray(); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, test)) { Fail("wrong plain text in buffer generated packet"); } // // sample message // PgpObjectFactory pgpFact = new PgpObjectFactory(testPBEAsym); PgpEncryptedDataList enc = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[1]; Stream clear = pbe.GetDataStream("password".ToCharArray()); pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (!AreEqual(bytes, Hex.Decode("5361742031302e30322e30370d0a"))) { Fail("data mismatch on combined PBE"); } // // with integrity packet - one byte message // byte[] msg = new byte[1]; bOut = new MemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); lData = new PgpLiteralDataGenerator(); comOut = comData.Open(new UncloseableStream(bOut)); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, msg.Length, TestDateTime); ldOut.Write(msg, 0, msg.Length); ldOut.Close(); comOut.Close(); cbOut = new MemoryStream(); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); data = bOut.ToArray(); cOut.Write(data, 0, data.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in buffer generated packet"); } } private class UncloseableMemoryStream : MemoryStream { public override void Close() { throw new Exception("Close() called on underlying stream"); } } public override string Name { get { return "PGPPBETest"; } } public static void Main( string[] args) { RunTest(new PgpPbeTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// 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.Azure.AcceptanceTestsAzureResource { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Resource Flattening for AutoRest /// </summary> public partial class AutoRestResourceFlatteningTestService : ServiceClient<AutoRestResourceFlatteningTestService>, IAutoRestResourceFlatteningTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.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> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestResourceFlatteningTestService(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService 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> protected AutoRestResourceFlatteningTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService 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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestResourceFlatteningTestService(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService 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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestResourceFlatteningTestService(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestResourceFlatteningTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestResourceFlatteningTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestResourceFlatteningTestService(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestResourceFlatteningTestService(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { BaseUri = new System.Uri("http://localhost"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Put External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutArrayWithHttpMessagesAsync(IList<Resource> resourceArray = default(IList<Resource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceArray", resourceArray); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutArray", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(resourceArray != null) { _requestContent = SafeJsonConvert.SerializeObject(resourceArray, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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, 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 AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IList<FlattenedProductInner>>> GetArrayWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetArray", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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, 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 AzureOperationResponse<IList<FlattenedProductInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IList<FlattenedProductInner>>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutDictionaryWithHttpMessagesAsync(IDictionary<string, FlattenedProductInner> resourceDictionary = default(IDictionary<string, FlattenedProductInner>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceDictionary", resourceDictionary); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutDictionary", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(resourceDictionary != null) { _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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, 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 AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IDictionary<string, FlattenedProductInner>>> GetDictionaryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetDictionary", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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, 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 AzureOperationResponse<IDictionary<string, FlattenedProductInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, FlattenedProductInner>>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceComplexObject", resourceComplexObject); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutResourceCollection", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(resourceComplexObject != null) { _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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, 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 AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetResourceCollection", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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, 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 AzureOperationResponse<ResourceCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<ResourceCollection>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using ConsoleToolkit.ConsoleIO; using ConsoleToolkit.ConsoleIO.Internal; namespace ConsoleToolkit.Testing { /// <summary> /// This class implements the <see cref="IConsoleOutInterface"/> and captures the console output in a format that facilitates /// examination of console output in a unit test. /// </summary> public class ConsoleInterfaceForTesting : IConsoleInterface { private readonly List<string> _buffer = new List<string>(); private readonly List<string> _foregroundColourMap = new List<string>(); private readonly List<string> _backgroundColourMap = new List<string>(); /// <summary> /// The current cursor position. /// </summary> private int _cursorTop; /// <summary> /// The current cursor position. /// </summary> private int _cursorLeft; /// <summary> /// The curent foreground colour. /// </summary> private ConsoleColor _foreground; /// <summary> /// The current background colour. /// </summary> private ConsoleColor _background; /// <summary> /// The console encoding. /// </summary> private Encoding _encoding; /// <summary> /// The colour code for the current foreground colour. /// </summary> private char _fgCode; /// <summary> /// The colour code for the current background colour. /// </summary> private char _bgCode; /// <summary> /// The original background colour to which all lines should be initialised. /// </summary> private char _initialBg; /// <summary> /// The original foreground colour to which all lines should be initialised. /// </summary> private char _initialFg; /// <summary> /// The input stream supplying input for the console. /// </summary> private TextReader _inputStream; /// <summary> /// The maximum number of lines the buffer may contain. Zero or less means no limit. /// </summary> private int _lengthLimit; /// <summary> /// The current foreground colour. This property keeps <see cref="_fgCode"/> aligned with the actual console colour. /// </summary> public ConsoleColor Foreground { get { return _foreground; } set { _foreground = value; _fgCode = ColourConverter.Convert(_foreground); } } /// <summary> /// The current background colour. This property keeps <see cref="_bgCode"/> aligned with the actual console colour. /// </summary> public ConsoleColor Background { get { return _background; } set { _background = value; _bgCode = ColourConverter.Convert(_background); } } /// <summary> /// The width of the window. This is the visible part of the display. It is possible for this to be less than the width of the buffer. /// </summary> public int WindowWidth { get; set; } /// <summary> /// The width of the buffer. This is the width of the data in the console window and can be wider than the actual window itself. /// </summary> public int BufferWidth { get; set; } /// <summary> /// The current cursor position. /// </summary> public int CursorLeft { get { return _cursorLeft; } set { _cursorLeft = value; } } /// <summary> /// The current cursor position. /// </summary> public int CursorTop { get { return _cursorTop; } set { _cursorTop = value; } } public Encoding Encoding { get { return _encoding; } } /// <summary> /// The constructor sets default values for various console properties and allows an encoding to be specified. /// </summary> public ConsoleInterfaceForTesting(Encoding encoding = null) { _encoding = encoding ?? Encoding.Default; Foreground = ConsoleColor.DarkGray; Background = ConsoleColor.Black; _initialBg = _bgCode; _initialFg = _fgCode; WindowWidth = 40; BufferWidth = 60; CreateBufferTo(0); //ensure that the buffer contains the first line. } /// <summary> /// Write some text to the console buffer. Does not add a line feed. /// </summary> /// <param name="data">The text data to write. This must not contain colour instructions.</param> public void Write(string data) { while (data.Contains(Environment.NewLine) || (data.Length + _cursorLeft > BufferWidth)) { string nextData; var usableLength = BufferWidth - _cursorLeft; var newlinePos = data.IndexOf(Environment.NewLine, StringComparison.Ordinal); if (newlinePos >= 0 && newlinePos < usableLength) { nextData = data.Substring(0, newlinePos); data = data.Substring(newlinePos + Environment.NewLine.Length); Write(nextData); NewLine(); } else { nextData = data.Substring(0, usableLength); data = data.Substring(usableLength); Write(nextData); } } CreateBufferTo(_cursorTop); var fgColorData = new string(_fgCode, data.Length); var bgColorData = new string(_bgCode, data.Length); OverWrite(_buffer, _cursorTop, _cursorLeft, data); OverWrite(_foregroundColourMap, _cursorTop, _cursorLeft, fgColorData); OverWrite(_backgroundColourMap, _cursorTop, _cursorLeft, bgColorData); _cursorLeft += data.Length; if (_cursorLeft >= BufferWidth) { _cursorTop++; _cursorLeft = 0; CreateBufferTo(_cursorTop); } } /// <summary> /// Overlay some text in an existing buffer. The method will discard any data that would overflow the buffer width. /// </summary> /// <param name="buffer">The buffer line array.</param> /// <param name="lineIndex">The index of the line to overwrite</param> /// <param name="overwritePosition">The position within the line to overwrite.</param> /// <param name="data">The text to place in the buffer at the specified position.</param> private void OverWrite(IList<string> buffer, int lineIndex, int overwritePosition, string data) { var line = buffer[lineIndex]; if (overwritePosition >= line.Length) return; var newLine = overwritePosition > 0 ? line.Substring(0, overwritePosition) : string.Empty; newLine += data; if (newLine.Length < line.Length) newLine += line.Substring(newLine.Length); //copy the remainder of the line from the original data if (newLine.Length > BufferWidth) newLine = newLine.Substring(0, BufferWidth); else if (newLine.Length < BufferWidth) newLine += new string(' ', BufferWidth - newLine.Length); buffer[lineIndex] = newLine; } /// <summary> /// Ensure that the buffer contains the specified line. /// </summary> /// <param name="ix">The zero based index of the line that must exist.</param> private void CreateBufferTo(int ix) { // ReSharper disable once LoopVariableIsNeverChangedInsideLoop while (ix >= _buffer.Count) { _buffer.Add(new string(' ', BufferWidth)); _foregroundColourMap.Add(new string(_initialFg, BufferWidth)); _backgroundColourMap.Add(new string(_initialBg, BufferWidth)); } if (_lengthLimit > 0) { while (_buffer.Count > _lengthLimit) { _buffer.RemoveAt(0); _foregroundColourMap.RemoveAt(0); _backgroundColourMap.RemoveAt(0); } if (CursorTop >= _lengthLimit) CursorTop = _lengthLimit - 1; } } /// <summary> /// Write a newline to the buffer. /// </summary> public void NewLine() { _cursorTop++; _cursorLeft = 0; CreateBufferTo(_cursorTop); } /// <summary> /// Return the entire buffer for testing purposes. It is possible to get just the text, just the colour information or all of the data. /// </summary> /// <param name="format">Enumeration value that specifies what should be returned.</param> /// <returns>A large string containing the requested data.</returns> public string GetBuffer(ConsoleBufferFormat format = ConsoleBufferFormat.TextOnly) { if (format == ConsoleBufferFormat.TextOnly) return string.Join(Environment.NewLine, _buffer); var allLines = _buffer.Where(b => format != ConsoleBufferFormat.ColourOnly) .Select((b, i) => new {Key = string.Format("{0:0000}C", i), Text = "+" + b}) .Concat(_foregroundColourMap.Select((b, i) => new {Key = string.Format("{0:0000}A", i), Text = "F" + b})) .Concat(_backgroundColourMap.Select((b, i) => new {Key = string.Format("{0:0000}B", i), Text = "B" + b})) .OrderBy(l => l.Key) .Select(l => l.Text); return string.Join(Environment.NewLine, allLines); } /// <summary> /// Indicate whether console input is redirected or not. This will effect the handling of invalid /// input on the stream. /// </summary> public bool InputIsRedirected { get; set; } /// <summary> /// Read a line of text from the console. The data for this operation is provided using the <see cref="SetInputStream"/> method. /// </summary> /// <returns>The next line of text.</returns> public string ReadLine() { CheckInputStream(); var readLine = _inputStream.ReadLine(); if (readLine != null) { Write(readLine); NewLine(); } return readLine; } private void CheckInputStream() { if (_inputStream == null) throw new NoInputStreamSet(); } /// <summary> /// Provide a text stream to provide the data for the console input stream. /// </summary> /// <param name="stream">The stream to use.</param> public void SetInputStream(TextReader stream) { _inputStream = stream; } private class NoInputStreamSet : Exception { } public void LimitBuffer(int maxLines) { _lengthLimit = maxLines; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.POIFS.FileSystem { using System.IO; using NPOI.Util; /** * This class provides methods to read a DocumentEntry managed by a * {@link POIFSFileSystem} or {@link NPOIFSFileSystem} instance. * It Creates the appropriate one, and delegates, allowing us to * work transparently with the two. */ public class DocumentInputStream : ByteArrayInputStream, ILittleEndianInput { /** returned by read operations if we're at end of document */ protected static int EOF = -1; protected static int SIZE_SHORT = 2; protected static int SIZE_INT = 4; protected static int SIZE_LONG = 8; private DocumentInputStream delegate1; /** For use by downstream implementations */ protected DocumentInputStream() { } /** * Create an InputStream from the specified DocumentEntry * * @param document the DocumentEntry to be read * * @exception IOException if the DocumentEntry cannot be opened (like, maybe it has * been deleted?) */ public DocumentInputStream(DocumentEntry document) { if (!(document is DocumentNode)) { throw new IOException("Cannot open internal document storage"); } DocumentNode documentNode = (DocumentNode)document; DirectoryNode parentNode = (DirectoryNode)document.Parent; if (documentNode.Document != null) { delegate1 = new ODocumentInputStream(document); } else if (parentNode.OFileSystem != null) { delegate1 = new ODocumentInputStream(document); } else if (parentNode.NFileSystem != null) { delegate1 = new NDocumentInputStream(document); } else { throw new IOException("No FileSystem bound on the parent, can't read contents"); } } public override long Seek(long offset, SeekOrigin origin) { return delegate1.Seek(offset, origin); } public override long Length { get { return delegate1.Length; } } public override long Position { get { return delegate1.Position; } set { delegate1.Position = value; } } /** * Create an InputStream from the specified Document * * @param document the Document to be read */ public DocumentInputStream(OPOIFSDocument document) { delegate1 = new ODocumentInputStream(document); } /** * Create an InputStream from the specified Document * * @param document the Document to be read */ public DocumentInputStream(NPOIFSDocument document) { delegate1 = new NDocumentInputStream(document); } public override int Available() { return delegate1.Available(); } public override void Close() { delegate1.Close(); } public override void Mark(int ignoredReadlimit) { delegate1.Mark(ignoredReadlimit); } /** * Tests if this input stream supports the mark and reset methods. * * @return <code>true</code> always */ public override bool MarkSupported() { return true; } public override int Read() { return delegate1.Read(); } public override int Read(byte[] b) { return Read(b, 0, b.Length); } public override int Read(byte[] b, int off, int len) { return delegate1.Read(b, off, len); } /** * Repositions this stream to the position at the time the mark() method was * last called on this input stream. If mark() has not been called this * method repositions the stream to its beginning. */ public override void Reset() { delegate1.Reset(); } public virtual long Skip(long n) { return delegate1.Skip(n); } public override int ReadByte() { return delegate1.ReadByte(); } public virtual double ReadDouble() { return delegate1.ReadDouble(); } public virtual short ReadShort() { return (short)ReadUShort(); } public virtual void ReadFully(byte[] buf) { ReadFully(buf, 0, buf.Length); } public virtual void ReadFully(byte[] buf, int off, int len) { delegate1.ReadFully(buf, off, len); } public virtual long ReadLong() { return delegate1.ReadLong(); } public virtual int ReadInt() { return delegate1.ReadInt(); } public virtual int ReadUShort() { return delegate1.ReadUShort(); } public virtual int ReadUByte() { return delegate1.ReadUByte(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Dhgms.JobHelper.ApiWebSite.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
//------------------------------------------------------------------------------ // Symbooglix // // // Copyright 2014-2017 Daniel Liew // // This file is licensed under the MIT license. // See LICENSE.txt for details. //------------------------------------------------------------------------------ using System; using Microsoft.Boogie; using System.IO; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Symbooglix { public class SMTLIBQueryPrinter : IExprVisitor { private HashSet<SymbolicVariable> symbolicsToDeclare = null; private HashSet<Microsoft.Boogie.Function> functionsToDeclare = null; private HashSet<Microsoft.Boogie.TypeCtorDecl> sortsToDeclare = null; private FindSymbolicsVisitor FSV = null; private FindUinterpretedFunctionsVisitor FFV = null; private TextWriter TW = null; private Traverser TheTraverser = null; public bool HumanReadable; private int Indent; // Tweaks to annotations public bool AnnotateVariableUses = true; public bool AnnotateAssertsWithNames = true; private int AssertCounter = 0; // Used for :named attributed expressions private static readonly string BindingPrefix = "N"; private int NamedAttributeCounter = 0; private Dictionary<Expr, int> Bindings; private bool UseNamedAttributeBindings; private bool NamedBindingsDisabledInQuantifierExpr; private ExprCountingVisitor BindingsFinder; private bool PrintTriggers; public SMTLIBQueryPrinter(TextWriter TW, bool useNamedAttributeBindings, bool humanReadable, bool printTriggers = true, int indent=2) { this.HumanReadable = humanReadable; // Must be set before output is set ChangeOutput(TW); this.Indent = indent; // FIXME: These declarations are broken. Declarations are part of the push-and-pop stack but we // are treating them globally here. This is a mess. symbolicsToDeclare = new HashSet<SymbolicVariable>(); functionsToDeclare = new HashSet<Function>(); sortsToDeclare = new HashSet<TypeCtorDecl>(); FSV = new FindSymbolicsVisitor(symbolicsToDeclare); // Have the visitor use our container FFV = new FindUinterpretedFunctionsVisitor(functionsToDeclare); // Have the visitor use our container BindingsFinder = new ExprCountingVisitor(); // FIXME: This is a hack. Boogie's GetHashCode() is very expensive // so we just check for reference equality instead Bindings = new Dictionary<Expr, int>( new ExprReferenceCompare()); this.UseNamedAttributeBindings = useNamedAttributeBindings; this.NamedBindingsDisabledInQuantifierExpr = false; PrintTriggers = printTriggers; TheTraverser = new SMTLIBTraverser(this); } private class SMTLIBTraverser : Traverser { public SMTLIBTraverser(IExprVisitor visitor) : base(visitor) {} public override Expr Traverse(Expr root) { return Visit(root); } } // Eurgh this level of indirection... This needs rethinking public void PrintExpr(Expr root) { // We never want to use bindings for these if (!UseNamedAttributeBindings || NamedBindingsDisabledInQuantifierExpr || root is LiteralExpr || root is IdentifierExpr) { TheTraverser.Traverse(root); return; } int numberOfOccurances = BindingsFinder.ExpressionCount[root]; if (numberOfOccurances < 2) { TheTraverser.Traverse(root); return; } Debug.Assert(numberOfOccurances >= 2); try { // Use the Binding assigned to this Expr if it's available. int BindingNumber = Bindings[root]; TW.Write(BindingPrefix + Bindings[root].ToString()); return; } catch (KeyNotFoundException) { // The binding hasn't been made yet so print it // Print the Expr and give it a binding int bindingNumber = NamedAttributeCounter; var binding = BindingPrefix + bindingNumber.ToString(); ++NamedAttributeCounter; // Increment for next user. TW.Write("(!"); PrintSeperator(); PushIndent(); // Inside a Quantified Expr :named attributes are not allowed // to contain free variables. We may miss opportunities here to // add bindings but it is safer to just completly disable adding bindings // inside a Quantified Expr if (root is QuantifierExpr) NamedBindingsDisabledInQuantifierExpr = true; TheTraverser.Traverse(root); // Now we are outside a quantifier bindings can be allowed again if (root is QuantifierExpr) NamedBindingsDisabledInQuantifierExpr = false; PrintSeperator(); TW.Write(":named " + binding); PopIndent(); PrintSeperator(); TW.Write(")"); // Save the binding Bindings[root] = bindingNumber; } } public void ClearDeclarations() { symbolicsToDeclare.Clear(); functionsToDeclare.Clear(); sortsToDeclare.Clear(); if (UseNamedAttributeBindings) { // FIXME: These don't really belong here BindingsFinder.Clear(); Bindings.Clear(); NamedAttributeCounter = 0; } } // For this verion of AddDeclarations we already know what variables // and uninterpreted functions are used. public void AddDeclarations(Constraint c) { // Add variables used in Constraint foreach (var usedVariable in c.UsedVariables) { symbolicsToDeclare.Add(usedVariable); } // Add uninterpreted functions used in Constraint foreach (var usedUninterpretedFunction in c.UsedUninterpretedFunctions) { functionsToDeclare.Add(usedUninterpretedFunction); } if (UseNamedAttributeBindings) BindingsFinder.Visit(c.Condition); } public void AddDeclarations(Expr e) { FSV.Visit(e); // We don't know what variables are used here so find them by traversing the Expr FFV.Visit(e); // We don't know what uninterpreted functions are sued here so find them by traversing Expr if (UseNamedAttributeBindings) BindingsFinder.Visit(e); } public enum Logic { DO_NOT_SET, /* Special Value that won't be printed */ QF_BV, QF_ABV, QF_AUFBV, // Quantifier free, arrays, uninterpreted functions and bitvectors ALL_SUPPORTED // CVC4 specific } public void ChangeOutput(TextWriter newTW) { Debug.Assert(newTW != null, "New output cannot be null!"); if (HumanReadable) { this.TW = new IndentedTextWriter(newTW," "); } else this.TW = newTW; } public void PrintVariableDeclarations() { if (HumanReadable) PrintCommentLine("Start variable declarations"); foreach (var symbolic in symbolicsToDeclare) { TW.Write("(declare-fun " + symbolic.Name + " () " + GetSMTLIBType(symbolic.TypedIdent.Type)); TW.Write(")"); if (HumanReadable) PrintCommentLine("Origin: " + symbolic.Origin, false); TW.Write(TW.NewLine); } if (HumanReadable) PrintCommentLine("End variable declarations"); } private void AddSort(Microsoft.Boogie.Type typ) { if (typ.IsCtor) { var typAsCtor = typ.AsCtor; if (typAsCtor.Arguments.Count > 0) throw new NotSupportedException("Can't handle constructor types with arguments"); sortsToDeclare.Add(typ.AsCtor.Decl); } else if (typ.IsMap) { // Maps might use constructor types var typAsMap = typ.AsMap; foreach (var arg in typAsMap.Arguments) { AddSort(arg); } AddSort(typAsMap.Result); } } private static string GetCustomSortName(Microsoft.Boogie.TypeCtorDecl typeDecl) { // FIXME: Do proper mangling to avoid name clashes return "@" + typeDecl.Name; } public void PrintSortDeclarations() { if (HumanReadable) PrintCommentLine("Start custom sort declarations"); // Compute sorts used (we assume all AddDeclaration(...) calls have been made) foreach (var v in symbolicsToDeclare) { AddSort(v.TypedIdent.Type); } foreach (var f in functionsToDeclare) { foreach (var arg in f.InParams.Concat(f.OutParams)) { AddSort(arg.TypedIdent.Type); } } // FIXME: We probably need to check free variables too! foreach (var sort in sortsToDeclare) { TW.WriteLine("(declare-sort " + GetCustomSortName(sort) + ")"); } if (HumanReadable) PrintCommentLine("End custom sort declarations"); } public void PrintFunctionDeclarations() { if (HumanReadable) PrintCommentLine("Start function declarations"); foreach (var function in functionsToDeclare) { if (function.Body != null) throw new NotSupportedException("Hit function that should of been inlined!"); TW.Write("(declare-fun " + function.Name + " ("); foreach (var type in function.InParams.Select( x => x.TypedIdent.Type )) { TW.Write(GetSMTLIBType(type) + " "); } TW.Write(") "); if (function.OutParams.Count != 1) throw new NotSupportedException("Only single parameters are supported!"); TW.Write(GetSMTLIBType(function.OutParams[0].TypedIdent.Type) + ")"); TW.Write(TW.NewLine); } if (HumanReadable) PrintCommentLine("End function declarations"); } public void PrintCommentLine(string comment, bool AddEndOfLineCharacter = true) { if (HumanReadable) { TW.Write("; " + comment); if (AddEndOfLineCharacter) TW.WriteLine(""); } } public static string GetSMTLIBType(Microsoft.Boogie.Type T) { Microsoft.Boogie.Type theType = null; // Handle type synonyms. E.g. ``type arrayId = bv2`` // Perhaps we should run a pass in the program to remove // type synonyms? theType = T; while (theType is TypeSynonymAnnotation) { theType = ( theType as TypeSynonymAnnotation ).ExpandedType; } if (theType is BvType) { var BVT = theType as BvType; return "(_ BitVec " + BVT.Bits + ")"; } else if (theType is BasicType) { var ST = ( theType as BasicType ).T; switch (ST) { case SimpleType.Bool: return "Bool"; case SimpleType.Int: return "Int"; case SimpleType.Real: return "Real"; default: throw new NotImplementedException("Unsupported SimpleType " + ST.ToString()); } } else if (theType is MapType) { var MT = theType as MapType; // We are using Z3's Native ArrayTheory (allows for Arrays of Arrays) here. I don't know if other Solvers support this. Debug.Assert(MT.Arguments.Count >= 1, "MapType has too few arguments"); string mapTypeAsString = ""; foreach (var domainType in MT.Arguments) { mapTypeAsString += "(Array " + GetSMTLIBType(domainType) + " "; } // Now print the final result from the map (the codomain) mapTypeAsString += GetSMTLIBType(MT.Result) + " "; // Now add closing braces for (int index = 0; index < MT.Arguments.Count; ++index) { mapTypeAsString += ")"; } return mapTypeAsString; } else if (theType is CtorType) { var CT = theType as CtorType; return GetCustomSortName(CT.Decl); } else { throw new NotImplementedException("The type " + theType.ToString() + " is not supported"); } } public void PrintSetLogic(Logic L) { if ( L != Logic.DO_NOT_SET) TW.WriteLine("(set-logic " + L.ToString() + " )"); } public void PrintPushDeclStack(int count) { if (count < 1) throw new ArgumentException("count must be > 0"); // FIXME: We should be keeping our decls in a stack so we can push and pop them TW.WriteLine("(push {0})", count); } public void PrintPopDeclStack(int count) { if (count < 1) throw new ArgumentException("count must be > 0"); // FIXME: We should be keeping our decls in a stack so we can push and pop them TW.WriteLine("(pop {0})", count); } public void PrintAssert(Expr e) { TW.Write("(assert"); PushIndent(); if (HumanReadable && AnnotateAssertsWithNames) { PrintSeperator(); TW.Write("(!"); PushIndent(); } PrintSeperator(); PrintExpr(e); PopIndent(); if (HumanReadable && AnnotateAssertsWithNames) { PrintSeperator(); TW.Write(":named assert" + AssertCounter.ToString()); PrintSeperator(); TW.Write(")"); PopIndent(); } PrintSeperator(); TW.WriteLine(")"); ++AssertCounter; } public void PrintCheckSat() { TW.WriteLine("(check-sat)"); TW.Flush(); } public void PrintGetModel() { TW.WriteLine("(get-model)"); TW.Flush(); } public void PrintGetUnsatCore() { TW.WriteLine("(get-unsat-core)"); TW.Flush(); } public void PrintExit() { TW.WriteLine("(exit)"); Reset(); } public void Reset() { TW.Flush(); AssertCounter = 0; ClearDeclarations(); } public void PrintReset() { TW.WriteLine("(reset)"); Reset(); } // FIXME: This API is gross. Use enums instead public void PrintSetOption(string option, string value) { TW.WriteLine("(set-option :" + option + " " + value + ")"); } private void PushIndent() { if (HumanReadable) { var IDT = this.TW as IndentedTextWriter; IDT.Indent += this.Indent; } } private void PrintSeperator() { if (HumanReadable) TW.WriteLine(""); else TW.Write(" "); } private void PopIndent() { if (HumanReadable) { var IDT = this.TW as IndentedTextWriter; IDT.Indent -= this.Indent; } } public Expr VisitLiteralExpr(LiteralExpr e) { if (e.isBool) { if (e.IsTrue) TW.Write("true"); else TW.Write("false"); } else if (e.isBvConst) { // FIXME: Support other bit vector literal printing modes TW.Write(string.Format("(_ bv{0} {1})", e.asBvConst.Value, e.asBvConst.Bits)); } else if (e.isBigNum) { // Int TW.Write(e.asBigNum); } else if (e.isBigDec) { // Real TW.Write(e.asBigDec.ToDecimalString()); } else { throw new NotImplementedException("LiteralExpr type not handled"); } return e; } public Expr VisitIdentifierExpr(IdentifierExpr e) { // Should we make this check better by recording what variables are currently bound? if (!( ( e.Decl is SymbolicVariable ) || (e.Decl is BoundVariable ))) throw new InvalidDataException("non symbolic/BoundVariable found in Expr"); //FIXME: Add our own Expr types TW.Write(e.Name); if (HumanReadable && AnnotateVariableUses && e.Decl is SymbolicVariable) { TW.Write(" ;" + ( e.Decl as SymbolicVariable ).Origin.ToString()); } return e; } public Expr VisitOldExpr(OldExpr e) { throw new NotImplementedException (); } public Expr VisitCodeExpr(CodeExpr e) { throw new NotImplementedException (); } public Expr VisitBvExtractExpr(BvExtractExpr e) { // SMTLIBv2 semantics // ((_ extract i j) (_ BitVec m) (_ BitVec n)) // - extraction of bits i down to j from a bitvector of size m to yield a // new bitvector of size n, where n = i - j + 1 // Boogie semantics // ABitVector[<end>:<start>] // This operation selects bits starting at <start> to <end> but not including <end> Debug.Assert(( e.End - 1 ) >= ( e.Start ), "Wrong extract bits for BvExtractExpr"); TW.Write("((_ extract " + (e.End -1) + " " + e.Start + ")"); PushIndent(); PrintSeperator(); PrintExpr(e.Bitvector); PopIndent(); PrintSeperator(); TW.Write(")"); return e; } public Expr VisitBvConcatExpr(BvConcatExpr e) { TW.Write("(concat"); PushIndent(); PrintSeperator(); PrintExpr(e.E0); PrintSeperator(); PrintExpr(e.E1); PopIndent(); PrintSeperator(); TW.Write(")"); return e; } public Expr VisitForallExpr(ForallExpr e) { return PrintQuantifierExpr(e); } public Expr VisitExistExpr(ExistsExpr e) { return PrintQuantifierExpr(e); } private Expr PrintQuantifierExpr(QuantifierExpr QE) { if (QE is ExistsExpr) TW.Write("(exists"); else if (QE is ForallExpr) TW.Write("(forall"); else throw new NotSupportedException("Unsupported quantifier expr"); PushIndent(); PrintSeperator(); TW.Write("("); PushIndent(); PrintSeperator(); foreach (var boundVar in QE.Dummies) { PrintSeperator(); TW.Write("(" + boundVar.Name + " " + GetSMTLIBType(boundVar.TypedIdent.Type) + ")"); } PopIndent(); PrintSeperator(); TW.Write(")"); PrintSeperator(); // Handle Triggers if (QE.Triggers == null || !PrintTriggers) { PrintExpr(QE.Body); } else { TW.Write("(!"); PushIndent(); PrintSeperator(); PrintExpr(QE.Body); PrintSeperator(); // fixme: pos! // Print triggers var trigger = QE.Triggers; if (trigger.Pos) { while (trigger != null) { // list of expressions TW.Write(":pattern ("); PushIndent(); PrintSeperator(); foreach (var triggerExpr in trigger.Tr) { PrintExpr(triggerExpr); PrintSeperator(); } PopIndent(); TW.Write(")"); trigger = trigger.Next; } } else { if (trigger.Tr.Count != 1) throw new InvalidDataException("Negative trigger is malformed"); // no-pattern takes an expression rather than a list of expressions TW.Write(":no-pattern"); PushIndent(); PrintSeperator(); PrintExpr(trigger.Tr[0]); PopIndent(); } PopIndent(); PrintSeperator(); TW.Write(")"); } PopIndent(); PrintSeperator(); TW.Write(")"); return QE; } public Expr VisitLambdaExpr(LambdaExpr e) { throw new NotImplementedException (); } public Expr VisitNot(NAryExpr e) { return PrintUnaryOperator("not", e); } public Expr VisitNeg(NAryExpr e) { return PrintUnaryOperator("-", e); } public Expr VisitAdd(NAryExpr e) { return PrintBinaryOperator("+", e); } public Expr VisitSub(NAryExpr e) { return PrintBinaryOperator("-", e); } public Expr VisitMul(NAryExpr e) { return PrintBinaryOperator("*", e); } public Expr VisitDiv(NAryExpr e) { Debug.Assert(( e.Args[0] as Expr ).Type.IsInt && ( e.Args[1] as Expr ).Type.IsInt, "wrong types given to div!"); return PrintBinaryOperator("div", e); } public Expr VisitRem(NAryExpr e) { // FIXME: This is a Z3 extension, we need to emit something different for other solvers Debug.Assert(( e.Args[0] as Expr ).Type.IsInt && ( e.Args[1] as Expr ).Type.IsInt, "wrong types given to rem"); return PrintBinaryOperator("rem", e); } public Expr VisitMod(NAryExpr e) { return PrintBinaryOperator("mod", e); } public Expr VisitRealDiv(NAryExpr e) { Debug.Assert(( e.Args[0] as Expr ).Type.IsReal && ( e.Args[1] as Expr ).Type.IsReal, "wrong types given to div!"); return PrintBinaryOperator("/", e); } public Expr VisitPow(NAryExpr e) { throw new NotImplementedException(); } public Expr VisitEq(NAryExpr e) { return PrintBinaryOperator("=", e); } public Expr VisitNeq(NAryExpr e) { return PrintBinaryOperator("distinct", e); } public Expr VisitGt(NAryExpr e) { return PrintBinaryOperator(">", e); } public Expr VisitGe(NAryExpr e) { return PrintBinaryOperator(">=", e); } public Expr VisitLt(NAryExpr e) { return PrintBinaryOperator("<", e); } public Expr VisitLe(NAryExpr e) { return PrintBinaryOperator("<=", e); } public Expr VisitAnd (NAryExpr e) { return PrintBinaryOperator("and", e); } public Expr VisitOr(NAryExpr e) { return PrintBinaryOperator("or", e); } public Expr VisitImp(NAryExpr e) { return PrintBinaryOperator("=>", e); } public Expr VisitIff(NAryExpr e) { // There is not <==> operator in SMTLIBv2 so print its equivalent // We cannot construct the equivalent and then print that because that would // break the binding as we'd be introducing Expr that haven't been seen before. TW.Write("(and"); PushIndent(); PrintSeperator(); TW.Write("(=>"); PushIndent(); PrintSeperator(); PrintExpr(e.Args[0]); PrintSeperator(); PrintExpr(e.Args[1]); PopIndent(); PrintSeperator(); TW.Write(")"); PrintSeperator(); TW.Write("(=>"); PushIndent(); PrintSeperator(); PrintExpr(e.Args[1]); PrintSeperator(); PrintExpr(e.Args[0]); PopIndent(); PrintSeperator(); TW.Write(")"); PopIndent(); PrintSeperator(); TW.Write(")"); return e; } public Expr VisitSubType(NAryExpr e) { throw new NotImplementedException (); } public Expr VisitMapStore(NAryExpr e) { // FIXME: Can we assert that we match the SMT-LIB order of args? return PrintTernaryOperator("store", e); } public Expr VisitMapSelect(NAryExpr e) { return PrintBinaryOperator("select", e); } public Expr VisitIfThenElse(NAryExpr e) { return PrintTernaryOperator("ite", e); } public Expr VisitFunctionCall(NAryExpr e) { var FC = e.Fun as FunctionCall; if (e.Args.Count == 0) { // A function with argments does not need parentheses TW.WriteLine(FC.Func.Name); return e; } TW.Write("(" + FC.Func.Name); PushIndent(); PrintSeperator(); foreach (var param in e.Args) { PrintExpr(param); PrintSeperator(); // FIXME: There shouldn't be one on the last param } PopIndent(); PrintSeperator(); TW.Write(")"); return e; } public Expr VisitTypeCoercion(NAryExpr e) { Debug.Assert(e.Args.Count == 1); var typeCoercion = e.Fun as TypeCoercion; if (!typeCoercion.Type.Equals(e.Args[0].Type)) throw new NotSupportedException("Non trivial type coercion used"); // Completly ignore the type coercion PrintExpr(e.Args[0]); return e; } public Expr VisitArithmeticCoercion(NAryExpr e) { Debug.Assert(e.Args.Count == 1); Debug.Assert(e.Fun is ArithmeticCoercion); var arithmeticCoercion = e.Fun as ArithmeticCoercion; switch (arithmeticCoercion.Coercion) { case ArithmeticCoercion.CoercionType.ToInt: return PrintUnaryOperator("to_int", e); case ArithmeticCoercion.CoercionType.ToReal: return PrintUnaryOperator("to_real", e); default: throw new NotSupportedException("Arithmetic coercion type " + arithmeticCoercion.Coercion + " not supported"); } } public Expr VisitDistinct(NAryExpr e) { TW.Write("(distinct"); PushIndent(); PrintSeperator(); for (int index = 0; index < e.Args.Count; ++index) { PrintExpr(e.Args[index]); if (index < (e.Args.Count -1)) PrintSeperator(); } PopIndent(); PrintSeperator(); TW.Write(")");; return e; } public Expr Visit_bvadd(NAryExpr e) { return PrintBinaryOperator("bvadd", e); } public Expr Visit_bvsub(NAryExpr e) { return PrintBinaryOperator("bvsub", e); } public Expr Visit_bvmul(NAryExpr e) { return PrintBinaryOperator("bvmul", e); } public Expr Visit_bvudiv(NAryExpr e) { return PrintBinaryOperator("bvudiv", e); } public Expr Visit_bvurem(NAryExpr e) { return PrintBinaryOperator("bvurem", e); } public Expr Visit_bvsdiv(NAryExpr e) { return PrintBinaryOperator("bvsdiv", e); } public Expr Visit_bvsrem(NAryExpr e) { return PrintBinaryOperator("bvsrem", e); } public Expr Visit_bvsmod(NAryExpr e) { return PrintBinaryOperator("bvsmod", e); } public Expr Visit_sign_extend(NAryExpr e) { return PrintSignExtend(e, "sign_extend"); } public Expr Visit_zero_extend(NAryExpr e) { // ((_ zero_extend i) (_ BitVec m) (_ BitVec m+i)) // ((_ zero_extend i) x) means extend x with zeroes to the (unsigned) // equivalent bitvector of size m+i return PrintSignExtend(e, "zero_extend"); } private Expr PrintSignExtend(NAryExpr e, string extensionType) { Debug.Assert(extensionType == "zero_extend" || extensionType == "sign_extend"); Debug.Assert(e.Args.Count == 1); Debug.Assert(e.Args[0].Type.IsBv, "Not a bitvector!"); Debug.Assert(e.Type.IsBv, "Out is not a bitvector!"); // Work out extension amount int numberOfBitsToAdd = ( e.Type.BvBits - e.Args[0].Type.BvBits ); Debug.Assert(numberOfBitsToAdd >= 0, "Number of bits to add calculation is incorrect"); // FIXME: Throw exception instead return PrintUnaryOperator("(_ " + extensionType + " " + numberOfBitsToAdd + ")", e); } public Expr Visit_bvneg(NAryExpr e) { return PrintUnaryOperator("bvneg", e); } public Expr Visit_bvand(NAryExpr e) { return PrintBinaryOperator("bvand", e); } public Expr Visit_bvor(NAryExpr e) { return PrintBinaryOperator("bvor", e); } public Expr Visit_bvnot(NAryExpr e) { return PrintUnaryOperator("bvnot", e); } public Expr Visit_bvxor(NAryExpr e) { return PrintBinaryOperator("bvxor", e); } public Expr Visit_bvshl (NAryExpr e) { return PrintBinaryOperator("bvshl", e); } public Expr Visit_bvlshr(NAryExpr e) { return PrintBinaryOperator("bvlshr", e); } public Expr Visit_bvashr(NAryExpr e) { return PrintBinaryOperator("bvashr", e); } public Expr Visit_bvult(NAryExpr e) { return PrintBinaryOperator("bvult", e); } public Expr Visit_bvule(NAryExpr e) { return PrintBinaryOperator("bvule", e); } public Expr Visit_bvugt(NAryExpr e) { return PrintBinaryOperator("bvugt", e); } public Expr Visit_bvuge(NAryExpr e) { return PrintBinaryOperator("bvuge", e); } public Expr Visit_bvslt(NAryExpr e) { return PrintBinaryOperator("bvslt", e); } public Expr Visit_bvsle(NAryExpr e) { return PrintBinaryOperator("bvsle", e); } public Expr Visit_bvsgt (NAryExpr e) { return PrintBinaryOperator("bvsgt", e); } public Expr Visit_bvsge(NAryExpr e) { return PrintBinaryOperator("bvsge", e); } // We go to a lot of effort in the Traverser to read the // string bvbuiltin to call the right method in IExprVisitor // but then we delegate back a single function for printing // binary operators using only the string name. // A bit inefficient... private Expr PrintBinaryOperator(string name, NAryExpr e) { Debug.Assert(e.Args.Count == 2, "Incorrect number of arguments"); TW.Write("(" + name); PushIndent(); PrintSeperator(); PrintExpr(e.Args[0]); PrintSeperator(); PrintExpr(e.Args[1]); PopIndent(); PrintSeperator(); TW.Write(")"); return e; } private Expr PrintUnaryOperator(string name, NAryExpr e) { Debug.Assert(e.Args.Count == 1, "Incorrect number of arguments"); TW.Write("(" + name); PushIndent(); PrintSeperator(); PrintExpr(e.Args[0]); PopIndent(); PrintSeperator(); TW.Write(")"); return e; } private Expr PrintTernaryOperator(string name, NAryExpr e) { Debug.Assert(e.Args.Count == 3, "Incorrect number of arguments"); TW.Write("(" + name); PushIndent(); PrintSeperator(); PrintExpr(e.Args[0]); PrintSeperator(); PrintExpr(e.Args[1]); PrintSeperator(); PrintExpr(e.Args[2]); PopIndent(); PrintSeperator(); TW.Write(")"); return e; } } // FIXME: This is not specific to the SMTLIBQueryPrinter and does not count all nodes. // This should be made internal to the printer. public class ExprCountingVisitor : ReadOnlyVisitor { public Dictionary<Expr, int> ExpressionCount; public void Clear() { ExpressionCount.Clear(); } public ExprCountingVisitor() { // FIXME: This is a hack. Boogie's GetHashCode() is very expensive // so we just check for reference equality instead this.ExpressionCount = new Dictionary<Expr, int>(new ExprReferenceCompare()); } public override Expr VisitExpr(Expr node) { // This avoids recording the same node twice // as VisitExpr() can call VisitNAryExpr() and VisitQuantifier() if (node is NAryExpr || node is QuantifierExpr) return base.VisitExpr(node); // We don't want to record anything for these if (node is LiteralExpr || node is IdentifierExpr) return base.VisitExpr(node); // We don't need to visit a nodes children if it // was already seen before because that means it will // get abbreviated in the printer. If we visit the children again we will over // count because when the abbreviation happens in the printer // the children won't be printed again. bool goDeeper = CountExpr(node); if (goDeeper) return base.VisitExpr(node); else return node; } // This is necessary because the root of a tree might // be an NAryExpr so the double dispatch won't call // VisitExpr() but instead will call VisitNAryExpr public override Expr VisitNAryExpr(NAryExpr node) { bool goDeeper = CountExpr(node); if (goDeeper) return base.VisitNAryExpr(node); else return node; } // This is necessary because the root of the Tree might be a QuantifierExpr public override QuantifierExpr VisitQuantifierExpr(QuantifierExpr node) { bool goDeeper = CountExpr(node); if (goDeeper) return base.VisitQuantifierExpr(node); else return node; } // Return true iff the node has not been seen before, otherwise false private bool CountExpr(Expr node) { try { int currentCount = ExpressionCount[node]; ExpressionCount[node] = currentCount +1; return false; } catch (KeyNotFoundException ) { ExpressionCount[node] = 1; 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.Collections; using System.Collections.Generic; using System.Threading; using Apache.NMS.Stomp.Commands; using Apache.NMS.Stomp.State; using Apache.NMS.Stomp.Threads; using Apache.NMS.Util; namespace Apache.NMS.Stomp.Transport.Failover { /// <summary> /// A Transport that is made reliable by being able to fail over to another /// transport when a transport failure is detected. /// </summary> public class FailoverTransport : ICompositeTransport, IComparable { private static int idCounter = 0; private readonly int id; private bool disposed; private bool connected; private readonly List<Uri> uris = new List<Uri>(); private CommandHandler commandHandler; private ExceptionHandler exceptionHandler; private InterruptedHandler interruptedHandler; private ResumedHandler resumedHandler; private readonly Mutex reconnectMutex = new Mutex(); private readonly Mutex sleepMutex = new Mutex(); private readonly ConnectionStateTracker stateTracker = new ConnectionStateTracker(); private readonly Dictionary<int, Command> requestMap = new Dictionary<int, Command>(); private Uri connectedTransportURI; private Uri failedConnectTransportURI; private readonly AtomicReference<ITransport> connectedTransport = new AtomicReference<ITransport>(null); private TaskRunner reconnectTask = null; private bool started; private int timeout = -1; private int asyncTimeout = 45000; private int initialReconnectDelay = 10; private int maxReconnectDelay = 1000 * 30; private int backOffMultiplier = 2; private bool useExponentialBackOff = true; private bool randomize = true; private int maxReconnectAttempts; private int startupMaxReconnectAttempts; private int connectFailures; private int reconnectDelay = 10; private Exception connectionFailure; private bool firstConnection = true; private volatile Exception failure; private readonly object mutex = new object(); public FailoverTransport() { id = idCounter++; } ~FailoverTransport() { Dispose(false); } #region FailoverTask private class FailoverTask : Task { private readonly FailoverTransport parent; public FailoverTask(FailoverTransport p) { parent = p; } public bool Iterate() { bool result = false; bool doReconnect = !parent.disposed && parent.connectionFailure == null; try { if(parent.ConnectedTransport == null && doReconnect) { result = parent.DoConnect(); } } finally { } return result; } } #endregion #region Property Accessors public CommandHandler Command { get { return commandHandler; } set { commandHandler = value; } } public ExceptionHandler Exception { get { return exceptionHandler; } set { exceptionHandler = value; } } public InterruptedHandler Interrupted { get { return interruptedHandler; } set { this.interruptedHandler = value; } } public ResumedHandler Resumed { get { return resumedHandler; } set { this.resumedHandler = value; } } internal Exception Failure { get{ return failure; } set { lock(mutex) { failure = value; } } } public int Timeout { get { return this.timeout; } set { this.timeout = value; } } public int InitialReconnectDelay { get { return initialReconnectDelay; } set { initialReconnectDelay = value; } } public int MaxReconnectDelay { get { return maxReconnectDelay; } set { maxReconnectDelay = value; } } public int ReconnectDelay { get { return reconnectDelay; } set { reconnectDelay = value; } } public int ReconnectDelayExponent { get { return backOffMultiplier; } set { backOffMultiplier = value; } } public ITransport ConnectedTransport { get { return connectedTransport.Value; } set { connectedTransport.Value = value; } } public Uri ConnectedTransportURI { get { return connectedTransportURI; } set { connectedTransportURI = value; } } public int MaxReconnectAttempts { get { return maxReconnectAttempts; } set { maxReconnectAttempts = value; } } public int StartupMaxReconnectAttempts { get { return startupMaxReconnectAttempts; } set { startupMaxReconnectAttempts = value; } } public bool Randomize { get { return randomize; } set { randomize = value; } } public bool UseExponentialBackOff { get { return useExponentialBackOff; } set { useExponentialBackOff = value; } } #endregion /// <summary> /// If doing an asynchronous connect, the milliseconds before timing out if no connection can be made /// </summary> /// <value>The async timeout.</value> public int AsyncTimeout { get { return asyncTimeout; } set { asyncTimeout = value; } } public bool IsFaultTolerant { get { return true; } } public bool IsDisposed { get { return disposed; } } public bool IsConnected { get { return connected; } } public bool IsStarted { get { return started; } } /// <summary> /// </summary> /// <param name="command"></param> /// <returns>Returns true if the command is one sent when a connection is being closed.</returns> private static bool IsShutdownCommand(Command command) { return (command != null && (command.IsShutdownInfo || command is RemoveInfo)); } public void OnException(ITransport sender, Exception error) { try { HandleTransportFailure(error); } catch(Exception e) { e.GetType(); // What to do here? } } public void disposedOnCommand(ITransport sender, Command c) { } public void disposedOnException(ITransport sender, Exception e) { } public void HandleTransportFailure(Exception e) { ITransport transport = connectedTransport.GetAndSet(null); if(transport != null) { transport.Command = new CommandHandler(disposedOnCommand); transport.Exception = new ExceptionHandler(disposedOnException); try { transport.Stop(); } catch(Exception ex) { ex.GetType(); // Ignore errors but this lets us see the error during debugging } lock(reconnectMutex) { bool reconnectOk = false; if(started) { Tracer.WarnFormat("Transport failed to {0}, attempting to automatically reconnect due to: {1}", ConnectedTransportURI.ToString(), e.Message); reconnectOk = true; } failedConnectTransportURI = ConnectedTransportURI; ConnectedTransportURI = null; connected = false; if(reconnectOk) { reconnectTask.Wakeup(); } } if(this.Interrupted != null) { this.Interrupted(transport); } } } public void Start() { lock(reconnectMutex) { if(started) { Tracer.Debug("FailoverTransport Already Started."); return; } Tracer.Debug("FailoverTransport Started."); started = true; if(ConnectedTransport != null) { stateTracker.DoRestore(ConnectedTransport); } else { Reconnect(); } } } public virtual void Stop() { ITransport transportToStop = null; lock(reconnectMutex) { if(!started) { Tracer.Debug("FailoverTransport Already Stopped."); return; } Tracer.Debug("FailoverTransport Stopped."); started = false; disposed = true; connected = false; if(ConnectedTransport != null) { transportToStop = connectedTransport.GetAndSet(null); } } try { sleepMutex.WaitOne(); } finally { sleepMutex.ReleaseMutex(); } if(reconnectTask != null) { reconnectTask.Shutdown(); } if(transportToStop != null) { transportToStop.Stop(); } } public FutureResponse AsyncRequest(Command command) { throw new ApplicationException("FailoverTransport does not implement AsyncRequest(Command)"); } public Response Request(Command command) { throw new ApplicationException("FailoverTransport does not implement Request(Command)"); } public Response Request(Command command, TimeSpan ts) { throw new ApplicationException("FailoverTransport does not implement Request(Command, TimeSpan)"); } public void OnCommand(ITransport sender, Command command) { if(command != null) { if(command.IsResponse) { Object oo = null; lock(((ICollection) requestMap).SyncRoot) { int v = ((Response) command).CorrelationId; try { if(requestMap.ContainsKey(v)) { oo = requestMap[v]; requestMap.Remove(v); } } catch { } } Tracked t = oo as Tracked; if(t != null) { t.onResponses(); } } } this.Command(sender, command); } public void Oneway(Command command) { Exception error = null; lock(reconnectMutex) { if(IsShutdownCommand(command) && ConnectedTransport == null) { if(command.IsShutdownInfo) { // Skipping send of ShutdownInfo command when not connected. return; } if(command.IsRemoveInfo) { stateTracker.track(command); // Simulate response to RemoveInfo command Response response = new Response(); response.CorrelationId = command.CommandId; OnCommand(this, response); return; } } // Keep trying until the message is sent. for(int i = 0; !disposed; i++) { try { // Wait for transport to be connected. ITransport transport = ConnectedTransport; DateTime start = DateTime.Now; bool timedout = false; while(transport == null && !disposed && connectionFailure == null) { int elapsed = (int)(DateTime.Now - start).TotalMilliseconds; if( this.timeout > 0 && elapsed > timeout ) { timedout = true; Tracer.DebugFormat("FailoverTransport.oneway - timed out after {0} mills", elapsed ); break; } // Release so that the reconnect task can run try { // This is a bit of a hack, what should be happening is that when // there's a reconnect the reconnectTask should signal the Monitor // or some other event object to indicate that we can wakeup right // away here, instead of performing the full wait. Monitor.Exit(reconnectMutex); Thread.Sleep(100); Monitor.Enter(reconnectMutex); } catch(Exception e) { Tracer.DebugFormat("Interrupted: {0}", e.Message); } transport = ConnectedTransport; } if(transport == null) { // Previous loop may have exited due to use being disposed. if(disposed) { error = new IOException("Transport disposed."); } else if(connectionFailure != null) { error = connectionFailure; } else if(timedout) { error = new IOException("Failover oneway timed out after "+ timeout +" milliseconds."); } else { error = new IOException("Unexpected failure."); } break; } // If it was a request and it was not being tracked by // the state tracker, then hold it in the requestMap so // that we can replay it later. Tracked tracked = stateTracker.track(command); lock(((ICollection) requestMap).SyncRoot) { if(tracked != null && tracked.WaitingForResponse) { requestMap.Add(command.CommandId, tracked); } else if(tracked == null && command.ResponseRequired) { requestMap.Add(command.CommandId, command); } } // Send the message. try { transport.Oneway(command); stateTracker.trackBack(command); } catch(Exception e) { // If the command was not tracked.. we will retry in // this method if(tracked == null) { // since we will retry in this method.. take it // out of the request map so that it is not // sent 2 times on recovery if(command.ResponseRequired) { lock(((ICollection) requestMap).SyncRoot) { requestMap.Remove(command.CommandId); } } // Rethrow the exception so it will handled by // the outer catch throw e; } } return; } catch(Exception e) { Tracer.DebugFormat("Send Oneway attempt: {0} failed: Message = {1}", i, e.Message); Tracer.DebugFormat("Failed Message Was: {0}", command); HandleTransportFailure(e); } } } if(!disposed) { if(error != null) { throw error; } } } public void Add(Uri[] u) { lock(uris) { for(int i = 0; i < u.Length; i++) { if(!uris.Contains(u[i])) { uris.Add(u[i]); } } } Reconnect(); } public void Remove(Uri[] u) { lock(uris) { for(int i = 0; i < u.Length; i++) { uris.Remove(u[i]); } } Reconnect(); } public void Add(String u) { try { Uri uri = new Uri(u); lock(uris) { if(!uris.Contains(uri)) { uris.Add(uri); } } Reconnect(); } catch(Exception e) { Tracer.ErrorFormat("Failed to parse URI '{0}': {1}", u, e.Message); } } public void Reconnect(Uri uri) { Add(new Uri[] { uri }); } public void Reconnect() { lock(reconnectMutex) { if(started) { if(reconnectTask == null) { Tracer.Debug("Creating reconnect task"); reconnectTask = new DedicatedTaskRunner(new FailoverTask(this)); } Tracer.Debug("Waking up reconnect task"); try { reconnectTask.Wakeup(); } catch(Exception) { } } else { Tracer.Debug("Reconnect was triggered but transport is not started yet. Wait for start to connect the transport."); } } } private List<Uri> ConnectList { get { List<Uri> l = new List<Uri>(uris); bool removed = false; if(failedConnectTransportURI != null) { removed = l.Remove(failedConnectTransportURI); } if(Randomize) { // Randomly, reorder the list by random swapping Random r = new Random(DateTime.Now.Millisecond); for(int i = 0; i < l.Count; i++) { int p = r.Next(l.Count); Uri t = l[p]; l[p] = l[i]; l[i] = t; } } if(removed) { l.Add(failedConnectTransportURI); } return l; } } protected void RestoreTransport(ITransport t) { Tracer.Info("Restoring previous transport connection."); t.Start(); stateTracker.DoRestore(t); Tracer.Info("Sending queued commands..."); Dictionary<int, Command> tmpMap = null; lock(((ICollection) requestMap).SyncRoot) { tmpMap = new Dictionary<int, Command>(requestMap); } foreach(Command command in tmpMap.Values) { t.Oneway(command); } } public Uri RemoteAddress { get { if(ConnectedTransport != null) { return ConnectedTransport.RemoteAddress; } return null; } } public Object Narrow(Type type) { if(this.GetType().Equals(type)) { return this; } else if(ConnectedTransport != null) { return ConnectedTransport.Narrow(type); } return null; } private bool DoConnect() { lock(reconnectMutex) { if(ConnectedTransport != null || disposed || connectionFailure != null) { return false; } else { List<Uri> connectList = ConnectList; if(connectList.Count == 0) { Failure = new NMSConnectionException("No URIs available for connection."); } else { if(!UseExponentialBackOff) { ReconnectDelay = InitialReconnectDelay; } ITransport transport = null; Uri chosenUri = null; try { foreach(Uri uri in connectList) { if(ConnectedTransport != null || disposed) { break; } Tracer.DebugFormat("Attempting connect to: {0}", uri); // synchronous connect try { Tracer.DebugFormat("Attempting connect to: {0}", uri.ToString()); transport = TransportFactory.CompositeConnect(uri); chosenUri = transport.RemoteAddress; break; } catch(Exception e) { Failure = e; Tracer.DebugFormat("Connect fail to: {0}, reason: {1}", uri, e.Message); } } if(transport != null) { transport.Command = new CommandHandler(OnCommand); transport.Exception = new ExceptionHandler(OnException); transport.Start(); if(started) { RestoreTransport(transport); } if(this.Resumed != null) { this.Resumed(transport); } Tracer.Debug("Connection established"); ReconnectDelay = InitialReconnectDelay; ConnectedTransportURI = chosenUri; ConnectedTransport = transport; connectFailures = 0; connected = true; if(firstConnection) { firstConnection = false; Tracer.InfoFormat("Successfully connected to: {0}", chosenUri.ToString()); } else { Tracer.InfoFormat("Successfully reconnected to: {0}", chosenUri.ToString()); } return false; } } catch(Exception e) { Failure = e; Tracer.DebugFormat("Connect attempt failed. Reason: {0}", e.Message); } } int maxAttempts = 0; if( firstConnection ) { if( StartupMaxReconnectAttempts != 0 ) { maxAttempts = StartupMaxReconnectAttempts; } } if( maxAttempts == 0 ) { maxAttempts = MaxReconnectAttempts; } if(maxAttempts > 0 && ++connectFailures >= maxAttempts) { Tracer.ErrorFormat("Failed to connect to transport after {0} attempt(s)", connectFailures); connectionFailure = Failure; this.Exception(this, connectionFailure); return false; } } } if(!disposed) { Tracer.DebugFormat("Waiting {0}ms before attempting connection.", ReconnectDelay); lock(sleepMutex) { try { Thread.Sleep(ReconnectDelay); } catch(Exception) { } } if(UseExponentialBackOff) { // Exponential increment of reconnect delay. ReconnectDelay *= ReconnectDelayExponent; if(ReconnectDelay > MaxReconnectDelay) { ReconnectDelay = MaxReconnectDelay; } } } return !disposed; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose(bool disposing) { if(disposing) { // get rid of unmanaged stuff } disposed = true; } public int CompareTo(Object o) { if(o is FailoverTransport) { FailoverTransport oo = o as FailoverTransport; return this.id - oo.id; } else { throw new ArgumentException(); } } public override String ToString() { return ConnectedTransportURI == null ? "unconnected" : ConnectedTransportURI.ToString(); } } }
using Coalesce.Web.Models; using IntelliTect.Coalesce; using IntelliTect.Coalesce.Api; using IntelliTect.Coalesce.Api.Controllers; using IntelliTect.Coalesce.Api.DataSources; using IntelliTect.Coalesce.Mapping; using IntelliTect.Coalesce.Mapping.IncludeTrees; using IntelliTect.Coalesce.Models; using IntelliTect.Coalesce.TypeDefinition; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Net; using System.Threading.Tasks; namespace Coalesce.Web.Api { [Route("api/Person")] [Authorize] [ServiceFilter(typeof(IApiActionFilter))] public partial class PersonController : BaseApiController<Coalesce.Domain.Person, PersonDtoGen, Coalesce.Domain.AppDbContext> { public PersonController(Coalesce.Domain.AppDbContext db) : base(db) { GeneratedForClassViewModel = ReflectionRepository.Global.GetClassViewModel<Coalesce.Domain.Person>(); } [HttpGet("get/{id}")] [AllowAnonymous] public virtual Task<ItemResult<PersonDtoGen>> Get( int id, DataSourceParameters parameters, IDataSource<Coalesce.Domain.Person> dataSource) => GetImplementation(id, parameters, dataSource); [HttpGet("list")] [AllowAnonymous] public virtual Task<ListResult<PersonDtoGen>> List( ListParameters parameters, IDataSource<Coalesce.Domain.Person> dataSource) => ListImplementation(parameters, dataSource); [HttpGet("count")] [AllowAnonymous] public virtual Task<ItemResult<int>> Count( FilterParameters parameters, IDataSource<Coalesce.Domain.Person> dataSource) => CountImplementation(parameters, dataSource); [HttpPost("save")] [AllowAnonymous] public virtual Task<ItemResult<PersonDtoGen>> Save( PersonDtoGen dto, [FromQuery] DataSourceParameters parameters, IDataSource<Coalesce.Domain.Person> dataSource, IBehaviors<Coalesce.Domain.Person> behaviors) => SaveImplementation(dto, parameters, dataSource, behaviors); [HttpPost("delete/{id}")] [Authorize] public virtual Task<ItemResult<PersonDtoGen>> Delete( int id, IBehaviors<Coalesce.Domain.Person> behaviors, IDataSource<Coalesce.Domain.Person> dataSource) => DeleteImplementation(id, new DataSourceParameters(), dataSource, behaviors); // Methods from data class exposed through API Controller. /// <summary> /// Method: Rename /// </summary> [HttpPost("Rename")] [Authorize] public virtual async Task<ItemResult<PersonDtoGen>> Rename([FromServices] IDataSourceFactory dataSourceFactory, int id, string name) { var dataSource = dataSourceFactory.GetDataSource<Coalesce.Domain.Person, Coalesce.Domain.Person>("Default"); var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) { return new ItemResult<PersonDtoGen>(itemResult); } var item = itemResult.Object; IncludeTree includeTree = null; var _mappingContext = new MappingContext(User); var _methodResult = item.Rename(name, out includeTree); await Db.SaveChangesAsync(); var _result = new ItemResult<PersonDtoGen>(); _result.Object = Mapper.MapToDto<Coalesce.Domain.Person, PersonDtoGen>(_methodResult, _mappingContext, includeTree); return _result; } /// <summary> /// Method: ChangeSpacesToDashesInName /// </summary> [HttpPost("ChangeSpacesToDashesInName")] [Authorize] public virtual async Task<ItemResult> ChangeSpacesToDashesInName([FromServices] IDataSourceFactory dataSourceFactory, int id) { var dataSource = dataSourceFactory.GetDataSource<Coalesce.Domain.Person, Coalesce.Domain.Person>("WithoutCases"); var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) { return new ItemResult(itemResult); } var item = itemResult.Object; var _methodResult = item.ChangeSpacesToDashesInName(); await Db.SaveChangesAsync(); var _result = new ItemResult(_methodResult); return _result; } /// <summary> /// Method: Add /// </summary> [HttpPost("Add")] [Authorize] public virtual ItemResult<int> Add(int numberOne, int numberTwo) { var _methodResult = Coalesce.Domain.Person.Add(numberOne, numberTwo); var _result = new ItemResult<int>(_methodResult); _result.Object = _methodResult.Object; return _result; } /// <summary> /// Method: GetUser /// </summary> [HttpPost("GetUser")] [Authorize(Roles = "Admin")] public virtual ItemResult<string> GetUser() { var _methodResult = Coalesce.Domain.Person.GetUser(User); var _result = new ItemResult<string>(); _result.Object = _methodResult; return _result; } /// <summary> /// Method: GetBirthdate /// </summary> [HttpPost("GetBirthdate")] [Authorize] public virtual async Task<ItemResult<System.DateTime>> GetBirthdate([FromServices] IDataSourceFactory dataSourceFactory, int id) { var dataSource = dataSourceFactory.GetDataSource<Coalesce.Domain.Person, Coalesce.Domain.Person>("Default"); var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) { return new ItemResult<System.DateTime>(itemResult); } var item = itemResult.Object; var _methodResult = item.GetBirthdate(); await Db.SaveChangesAsync(); var _result = new ItemResult<System.DateTime>(); _result.Object = _methodResult; return _result; } /// <summary> /// Method: PersonCount /// </summary> [HttpGet("PersonCount")] [Authorize] public virtual ItemResult<long> PersonCount(string lastNameStartsWith = "") { var _methodResult = Coalesce.Domain.Person.PersonCount(Db, lastNameStartsWith); var _result = new ItemResult<long>(); _result.Object = _methodResult; return _result; } /// <summary> /// Method: FullNameAndAge /// </summary> [HttpGet("FullNameAndAge")] [Authorize] public virtual async Task<ItemResult<string>> FullNameAndAge([FromServices] IDataSourceFactory dataSourceFactory, int id) { var dataSource = dataSourceFactory.GetDataSource<Coalesce.Domain.Person, Coalesce.Domain.Person>("Default"); var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) { return new ItemResult<string>(itemResult); } var item = itemResult.Object; var _methodResult = item.FullNameAndAge(Db); await Db.SaveChangesAsync(); var _result = new ItemResult<string>(); _result.Object = _methodResult; return _result; } /// <summary> /// Method: RemovePersonById /// </summary> [HttpDelete("RemovePersonById")] [Authorize] public virtual ItemResult<bool> RemovePersonById(int id) { var _methodResult = Coalesce.Domain.Person.RemovePersonById(Db, id); var _result = new ItemResult<bool>(); _result.Object = _methodResult; return _result; } /// <summary> /// Method: ObfuscateEmail /// </summary> [HttpPut("ObfuscateEmail")] [Authorize] public virtual async Task<ItemResult<string>> ObfuscateEmail([FromServices] IDataSourceFactory dataSourceFactory, int id) { var dataSource = dataSourceFactory.GetDataSource<Coalesce.Domain.Person, Coalesce.Domain.Person>("Default"); var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) { return new ItemResult<string>(itemResult); } var item = itemResult.Object; var _methodResult = item.ObfuscateEmail(Db); await Db.SaveChangesAsync(); var _result = new ItemResult<string>(); _result.Object = _methodResult; return _result; } /// <summary> /// Method: ChangeFirstName /// </summary> [HttpPatch("ChangeFirstName")] [Authorize] public virtual async Task<ItemResult<PersonDtoGen>> ChangeFirstName([FromServices] IDataSourceFactory dataSourceFactory, int id, string firstName, Coalesce.Domain.Person.Titles? title) { var dataSource = dataSourceFactory.GetDataSource<Coalesce.Domain.Person, Coalesce.Domain.Person>("Default"); var (itemResult, _) = await dataSource.GetItemAsync(id, new ListParameters()); if (!itemResult.WasSuccessful) { return new ItemResult<PersonDtoGen>(itemResult); } var item = itemResult.Object; IncludeTree includeTree = null; var _mappingContext = new MappingContext(User); var _methodResult = item.ChangeFirstName(firstName, title); await Db.SaveChangesAsync(); var _result = new ItemResult<PersonDtoGen>(); _result.Object = Mapper.MapToDto<Coalesce.Domain.Person, PersonDtoGen>(_methodResult, _mappingContext, includeTree); return _result; } /// <summary> /// Method: GetUserPublic /// </summary> [HttpPost("GetUserPublic")] [Authorize] public virtual ItemResult<string> GetUserPublic() { var _methodResult = Coalesce.Domain.Person.GetUserPublic(User); var _result = new ItemResult<string>(); _result.Object = _methodResult; return _result; } /// <summary> /// Method: NamesStartingWith /// </summary> [HttpPost("NamesStartingWith")] [Authorize] public virtual ItemResult<System.Collections.Generic.ICollection<string>> NamesStartingWith(string characters) { var _methodResult = Coalesce.Domain.Person.NamesStartingWith(Db, characters); var _result = new ItemResult<System.Collections.Generic.ICollection<string>>(); _result.Object = _methodResult?.ToList(); return _result; } /// <summary> /// Method: MethodWithEntityParameter /// </summary> [HttpPost("MethodWithEntityParameter")] [Authorize] public virtual ItemResult<PersonDtoGen> MethodWithEntityParameter(PersonDtoGen person) { IncludeTree includeTree = null; var _mappingContext = new MappingContext(User); var _methodResult = Coalesce.Domain.Person.MethodWithEntityParameter(Db, person.MapToModel(new Coalesce.Domain.Person(), _mappingContext)); var _result = new ItemResult<PersonDtoGen>(); _result.Object = Mapper.MapToDto<Coalesce.Domain.Person, PersonDtoGen>(_methodResult, _mappingContext, includeTree); return _result; } /// <summary> /// Method: SearchPeople /// </summary> [HttpPost("SearchPeople")] [Authorize] public virtual ListResult<PersonDtoGen> SearchPeople(PersonCriteriaDtoGen criteria, int page) { IncludeTree includeTree = null; var _mappingContext = new MappingContext(User); var _methodResult = Coalesce.Domain.Person.SearchPeople(Db, criteria.MapToModel(new Coalesce.Domain.PersonCriteria(), _mappingContext), page); var _result = new ListResult<PersonDtoGen>(_methodResult); _result.List = _methodResult.List?.ToList().Select(o => Mapper.MapToDto<Coalesce.Domain.Person, PersonDtoGen>(o, _mappingContext, includeTree)).ToList(); return _result; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmLangImport { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmLangImport() : base() { //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.TextBox Text1; private System.Windows.Forms.Button withEventsField_Command1; public System.Windows.Forms.Button Command1 { get { return withEventsField_Command1; } set { if (withEventsField_Command1 != null) { withEventsField_Command1.Click -= Command1_Click; } withEventsField_Command1 = value; if (withEventsField_Command1 != null) { withEventsField_Command1.Click += Command1_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.ProgressBar prgUpdate; private System.Windows.Forms.Button withEventsField_Command3; public System.Windows.Forms.Button Command3 { get { return withEventsField_Command3; } set { if (withEventsField_Command3 != null) { withEventsField_Command3.Click -= Command3_Click; } withEventsField_Command3 = value; if (withEventsField_Command3 != null) { withEventsField_Command3.Click += Command3_Click; } } } public System.Windows.Forms.TextBox txtFile; public System.Windows.Forms.OpenFileDialog cmdDlgOpen; public System.Windows.Forms.Label Label3; public System.Windows.Forms.Label Label1; public Microsoft.VisualBasic.PowerPacks.LineShape Line2; public System.Windows.Forms.Label lblHeading; public Microsoft.VisualBasic.PowerPacks.LineShape Line1; public System.Windows.Forms.Label Label2; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.Line2 = new Microsoft.VisualBasic.PowerPacks.LineShape(); this.Line1 = new Microsoft.VisualBasic.PowerPacks.LineShape(); this.Text1 = new System.Windows.Forms.TextBox(); this.Command1 = new System.Windows.Forms.Button(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdClose = new System.Windows.Forms.Button(); this.prgUpdate = new System.Windows.Forms.ProgressBar(); this.Command3 = new System.Windows.Forms.Button(); this.txtFile = new System.Windows.Forms.TextBox(); this.cmdDlgOpen = new System.Windows.Forms.OpenFileDialog(); this.Label3 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.lblHeading = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); this.picButtons.SuspendLayout(); this.SuspendLayout(); // //ShapeContainer1 // this.ShapeContainer1.Location = new System.Drawing.Point(0, 0); this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0); this.ShapeContainer1.Name = "ShapeContainer1"; this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this.Line2, this.Line1 }); this.ShapeContainer1.Size = new System.Drawing.Size(512, 234); this.ShapeContainer1.TabIndex = 11; this.ShapeContainer1.TabStop = false; // //Line2 // this.Line2.BorderColor = System.Drawing.SystemColors.WindowText; this.Line2.BorderWidth = 2; this.Line2.Name = "Line2"; this.Line2.X1 = 8; this.Line2.X2 = 508; this.Line2.Y1 = 156; this.Line2.Y2 = 156; // //Line1 // this.Line1.BorderColor = System.Drawing.SystemColors.WindowText; this.Line1.BorderWidth = 2; this.Line1.Name = "Line1"; this.Line1.X1 = 4; this.Line1.X2 = 504; this.Line1.Y1 = 76; this.Line1.Y2 = 76; // //Text1 // this.Text1.AcceptsReturn = true; this.Text1.BackColor = System.Drawing.SystemColors.Window; this.Text1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.Text1.Cursor = System.Windows.Forms.Cursors.IBeam; this.Text1.ForeColor = System.Drawing.SystemColors.WindowText; this.Text1.Location = new System.Drawing.Point(88, 160); this.Text1.MaxLength = 0; this.Text1.Name = "Text1"; this.Text1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Text1.Size = new System.Drawing.Size(371, 17); this.Text1.TabIndex = 8; // //Command1 // this.Command1.BackColor = System.Drawing.SystemColors.Control; this.Command1.Cursor = System.Windows.Forms.Cursors.Default; this.Command1.ForeColor = System.Drawing.SystemColors.ControlText; this.Command1.Location = new System.Drawing.Point(476, 164); this.Command1.Name = "Command1"; this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Command1.Size = new System.Drawing.Size(35, 15); this.Command1.TabIndex = 7; this.Command1.Text = "..."; this.Command1.UseVisualStyleBackColor = false; // //picButtons // this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Controls.Add(this.cmdClose); this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.Name = "picButtons"; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Size = new System.Drawing.Size(512, 38); this.picButtons.TabIndex = 4; // //cmdClose // this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Location = new System.Drawing.Point(432, 2); this.cmdClose.Name = "cmdClose"; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.TabIndex = 5; this.cmdClose.TabStop = false; this.cmdClose.Text = "E&xit"; this.cmdClose.UseVisualStyleBackColor = false; // //prgUpdate // this.prgUpdate.Location = new System.Drawing.Point(84, 192); this.prgUpdate.Maximum = 1; this.prgUpdate.Name = "prgUpdate"; this.prgUpdate.Size = new System.Drawing.Size(373, 33); this.prgUpdate.TabIndex = 3; // //Command3 // this.Command3.BackColor = System.Drawing.SystemColors.Control; this.Command3.Cursor = System.Windows.Forms.Cursors.Default; this.Command3.ForeColor = System.Drawing.SystemColors.ControlText; this.Command3.Location = new System.Drawing.Point(472, 84); this.Command3.Name = "Command3"; this.Command3.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Command3.Size = new System.Drawing.Size(35, 15); this.Command3.TabIndex = 2; this.Command3.Text = "..."; this.Command3.UseVisualStyleBackColor = false; // //txtFile // this.txtFile.AcceptsReturn = true; this.txtFile.BackColor = System.Drawing.SystemColors.Window; this.txtFile.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtFile.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtFile.ForeColor = System.Drawing.SystemColors.WindowText; this.txtFile.Location = new System.Drawing.Point(84, 80); this.txtFile.MaxLength = 0; this.txtFile.Name = "txtFile"; this.txtFile.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtFile.Size = new System.Drawing.Size(371, 17); this.txtFile.TabIndex = 0; // //Label3 // this.Label3.BackColor = System.Drawing.Color.Transparent; this.Label3.Cursor = System.Windows.Forms.Cursors.Default; this.Label3.ForeColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(0)), Convert.ToInt32(Convert.ToByte(0)), Convert.ToInt32(Convert.ToByte(128))); this.Label3.Location = new System.Drawing.Point(12, 128); this.Label3.Name = "Label3"; this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label3.Size = new System.Drawing.Size(495, 21); this.Label3.TabIndex = 10; this.Label3.Text = "Menu Translation - CSV file layout: ( MenuNo | Description )"; // //Label1 // this.Label1.BackColor = System.Drawing.SystemColors.Control; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Location = new System.Drawing.Point(12, 162); this.Label1.Name = "Label1"; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.Size = new System.Drawing.Size(65, 15); this.Label1.TabIndex = 9; this.Label1.Text = "File path"; // //lblHeading // this.lblHeading.BackColor = System.Drawing.Color.Transparent; this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default; this.lblHeading.ForeColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(0)), Convert.ToInt32(Convert.ToByte(0)), Convert.ToInt32(Convert.ToByte(128))); this.lblHeading.Location = new System.Drawing.Point(8, 48); this.lblHeading.Name = "lblHeading"; this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblHeading.Size = new System.Drawing.Size(495, 21); this.lblHeading.TabIndex = 6; this.lblHeading.Text = "Main Translation - CSV file layout: ( LanguageNo | Description )"; // //Label2 // this.Label2.BackColor = System.Drawing.SystemColors.Control; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Location = new System.Drawing.Point(8, 82); this.Label2.Name = "Label2"; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.Size = new System.Drawing.Size(65, 15); this.Label2.TabIndex = 1; this.Label2.Text = "File path"; // //frmLangImport // this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.ClientSize = new System.Drawing.Size(512, 234); this.ControlBox = false; this.Controls.Add(this.Text1); this.Controls.Add(this.Command1); this.Controls.Add(this.picButtons); this.Controls.Add(this.prgUpdate); this.Controls.Add(this.Command3); this.Controls.Add(this.txtFile); this.Controls.Add(this.Label3); this.Controls.Add(this.Label1); this.Controls.Add(this.lblHeading); this.Controls.Add(this.Label2); this.Controls.Add(this.ShapeContainer1); this.Cursor = System.Windows.Forms.Cursors.Default; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Location = new System.Drawing.Point(3, 22); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmLangImport"; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Import Language Translation"; this.picButtons.ResumeLayout(false); this.ResumeLayout(false); } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.POIFS.FileSystem { using System; using System.IO; using NPOI.Util; using System.Text; /** * Represents an Ole10Native record which is wrapped around certain binary * files being embedded in OLE2 documents. * * @author Rainer Schwarze */ public class Ole10Native { public static String OLE10_NATIVE = "\x0001Ole10Native"; protected static String ISO1 = "ISO-8859-1"; // (the fields as they appear in the raw record:) private int totalSize; // 4 bytes, total size of record not including this field private short flags1 = 2; // 2 bytes, unknown, mostly [02 00] private String label; // ASCIIZ, stored in this field without the terminating zero private String fileName; // ASCIIZ, stored in this field without the terminating zero private short flags2 = 0; // 2 bytes, unknown, mostly [00 00] private short unknown1 = 3; // see below private String command; // ASCIIZ, stored in this field without the terminating zero private byte[] dataBuffer; // varying size, the actual native data private short flags3 = 0; // some final flags? or zero terminators?, sometimes not there /** * the field encoding mode - merely a try-and-error guess ... **/ private enum EncodingMode { /** * the data is stored in parsed format - including label, command, etc. */ parsed, /** * the data is stored raw after the length field */ unparsed, /** * the data is stored raw after the length field and the flags1 field */ compact } private EncodingMode mode; /// <summary> /// Creates an instance of this class from an embedded OLE Object. The OLE Object is expected /// to include a stream &quot;{01}Ole10Native&quot; which Contains the actual /// data relevant for this class. /// </summary> /// <param name="poifs">poifs POI Filesystem object</param> /// <returns>Returns an instance of this class</returns> public static Ole10Native CreateFromEmbeddedOleObject(POIFSFileSystem poifs) { return CreateFromEmbeddedOleObject(poifs.Root); } /// <summary> /// Creates an instance of this class from an embedded OLE Object. The OLE Object is expected /// to include a stream &quot;{01}Ole10Native&quot; which contains the actual /// data relevant for this class. /// </summary> /// <param name="directory">directory POI Filesystem object</param> /// <returns>Returns an instance of this class</returns> public static Ole10Native CreateFromEmbeddedOleObject(DirectoryNode directory) { DocumentEntry nativeEntry = (DocumentEntry)directory.GetEntry(OLE10_NATIVE); byte[] data = new byte[nativeEntry.Size]; directory.CreateDocumentInputStream(nativeEntry).Read(data); return new Ole10Native(data, 0); } /** * Creates an instance and fills the fields based on ... the fields */ public Ole10Native(String label, String filename, String command, byte[] data) { Label=(label); FileName=(filename); Command=(command); DataBuffer=(data); mode = EncodingMode.parsed; } /** * Creates an instance and Fills the fields based on the data in the given buffer. * * @param data The buffer Containing the Ole10Native record * @param offset The start offset of the record in the buffer * @throws Ole10NativeException on invalid or unexcepted data format */ public Ole10Native(byte[] data, int offset) { int ofs = offset; // current offset, Initialized to start if (data.Length < offset + 2) { throw new Ole10NativeException("data is too small"); } totalSize = LittleEndian.GetInt(data, ofs); ofs += LittleEndianConsts.INT_SIZE; mode = EncodingMode.unparsed; if (LittleEndian.GetShort(data, ofs) == 2) { // some files like equations don't have a valid filename, // but somehow encode the formula right away in the ole10 header if (char.IsControl((char)data[ofs + LittleEndianConsts.SHORT_SIZE])) { mode = EncodingMode.compact; } else { mode = EncodingMode.parsed; } } int dataSize = 0; switch (mode) { case EncodingMode.parsed: flags1 = LittleEndian.GetShort(data, ofs); ofs += LittleEndianConsts.SHORT_SIZE; int len = GetStringLength(data, ofs); label = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1); ofs += len; len = GetStringLength(data, ofs); fileName = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1); ofs += len; flags2 = LittleEndian.GetShort(data, ofs); ofs += LittleEndianConsts.SHORT_SIZE; unknown1 = LittleEndian.GetShort(data, ofs); ofs += LittleEndianConsts.SHORT_SIZE; len = LittleEndian.GetInt(data, ofs); ofs += LittleEndianConsts.INT_SIZE; command = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1); ofs += len; if (totalSize < ofs) { throw new Ole10NativeException("Invalid Ole10Native"); } dataSize = LittleEndian.GetInt(data, ofs); ofs += LittleEndianConsts.INT_SIZE; if (dataSize < 0 || totalSize - (ofs - LittleEndianConsts.INT_SIZE) < dataSize) { throw new Ole10NativeException("Invalid Ole10Native"); } break; case EncodingMode.compact: flags1 = LittleEndian.GetShort(data, ofs); ofs += LittleEndianConsts.SHORT_SIZE; dataSize = totalSize - LittleEndianConsts.SHORT_SIZE; break; case EncodingMode.unparsed: dataSize = totalSize; break; } dataBuffer = new byte[dataSize]; Array.Copy(data, ofs, dataBuffer, 0, dataSize); ofs += dataSize; } /* * Helper - determine length of zero terminated string (ASCIIZ). */ private static int GetStringLength(byte[] data, int ofs) { int len = 0; while (len + ofs < data.Length && data[ofs + len] != 0) { len++; } len++; return len; } /** * Returns the value of the totalSize field - the total length of the structure * is totalSize + 4 (value of this field + size of this field). * * @return the totalSize */ public int TotalSize { get { return totalSize; } } /** * Returns flags1 - currently unknown - usually 0x0002. * * @return the flags1 */ public short Flags1 { get { return flags1; } set { flags1 = value; } } /** * Returns the label field - usually the name of the file (without directory) but * probably may be any name specified during packaging/embedding the data. * * @return the label */ public String Label { get { return label; } set { label = value; } } /** * Returns the fileName field - usually the name of the file being embedded * including the full path. * * @return the fileName */ public String FileName { get { return fileName; } set { fileName = value; } } /** * Returns flags2 - currently unknown - mostly 0x0000. * * @return the flags2 */ public short Flags2 { get { return flags2; } set { flags2 = value; } } /** * Returns unknown1 field - currently unknown. * * @return the unknown1 */ public short Unknown1 { get { return unknown1; } set { unknown1 = value; } } /** * Returns the command field - usually the name of the file being embedded * including the full path, may be a command specified during embedding the file. * * @return the command */ public String Command { get { return command; } set { command = value; } } /** * Returns the size of the embedded file. If the size is 0 (zero), no data has been * embedded. To be sure, that no data has been embedded, check whether * {@link #getDataBuffer()} returns <code>null</code>. * * @return the dataSize */ public int DataSize { get{return dataBuffer.Length;} } /** * Returns the buffer Containing the embedded file's data, or <code>null</code> * if no data was embedded. Note that an embedding may provide information about * the data, but the actual data is not included. (So label, filename etc. are * available, but this method returns <code>null</code>.) * * @return the dataBuffer */ public byte[] DataBuffer { get { return dataBuffer; } set { dataBuffer =(byte[])value.Clone(); } } /** * Returns the flags3 - currently unknown. * * @return the flags3 */ public short Flags3 { get { return flags3; } set { flags3 = value; } } /** * Have the contents printer out into an OutputStream, used when writing a * file back out to disk (Normally, atom classes will keep their bytes * around, but non atom classes will just request the bytes from their * children, then chuck on their header and return) */ public void WriteOut(Stream out1) { byte[] intbuf = new byte[LittleEndianConsts.INT_SIZE]; byte[] shortbuf = new byte[LittleEndianConsts.SHORT_SIZE]; byte[] zerobuf = { 0, 0, 0, 0 }; LittleEndianOutputStream leosOut = new LittleEndianOutputStream(out1); switch (mode) { case EncodingMode.parsed: { MemoryStream bos = new MemoryStream(); LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); // total size, will be determined later .. leos.WriteShort(Flags1); leos.Write(Encoding.GetEncoding(ISO1).GetBytes(Label)); leos.WriteByte(0); leos.Write(Encoding.GetEncoding(ISO1).GetBytes(FileName)); leos.WriteByte(0); leos.WriteShort(Flags2); leos.WriteShort(Unknown1); leos.WriteInt(Command.Length + 1); leos.Write(Encoding.GetEncoding(ISO1).GetBytes(Command)); leos.WriteByte(0); leos.WriteInt(DataSize); leos.Write(DataBuffer); leos.WriteShort(Flags3); //leos.Close(); // satisfy compiler ... leosOut.WriteInt((int)bos.Length); // total size bos.WriteTo(out1); break; } case EncodingMode.compact: leosOut.WriteInt(DataSize + LittleEndianConsts.SHORT_SIZE); leosOut.WriteShort(Flags1); out1.Write(DataBuffer, 0, DataBuffer.Length); break; default: case EncodingMode.unparsed: leosOut.WriteInt(DataSize); out1.Write(DataBuffer, 0, DataBuffer.Length); break; } } } }
/*- * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * See the file EXAMPLES-LICENSE for license information. * * $Id$ */ using System; using System.Collections.Generic; using System.Text; using BerkeleyDB; namespace excs_lock { class Program { const int EXIT_FAILURE = 1; const int EXIT_SUCCESS = 0; static void Main(string[] args) { DatabaseEntry data; DatabaseEnvironment env; List<Lock> lockList; Lock lk; LockMode mode; string buff; string home; string progName; int lockNo; uint doUnLink; uint locker; uint maxLock; try { home = args[0]; maxLock = uint.Parse(args[1]); doUnLink = uint.Parse(args[2]); } catch { Usage(); return; } data = new DatabaseEntry(); lockList = new List<Lock>(); progName = "excs_lock"; /* Initialize the database environment. */ if (DBInit(out env, home, progName, maxLock, doUnLink) == EXIT_FAILURE) return; /* * Accept lock requests. */ try { locker = env.CreateLockerID(); } catch (Exception e) { Console.WriteLine("{0}:{1}\n{2}", e.Source, e.Message, e.StackTrace); env.Close(); return; } while (true) { /* Choose getting or releasing lock. */ Console.WriteLine("Operation get/release/quit: "); buff = Console.ReadLine(); if (buff == "get") { /* Input the content to be locked. */ Console.WriteLine("Input text string to lock"); try { buff = Console.ReadLine(); DbtFromString(data, buff); } catch { Console.WriteLine("Input fails"); continue; } /* * Choose the locker's mode. More lock modes * could be provided. Only support read/write * mode here. */ while (true) { Console.WriteLine("read or write"); buff = Console.ReadLine(); if (buff == "read" || buff == "write") break; } if (buff == "write") mode = LockMode.WRITE; else mode = LockMode.READ; /* Get lock and add it to the list of locks. */ try { lk = env.GetLock(locker, false, data, mode); } catch (Exception e) { Console.WriteLine("{0}:{1}\n{2}", e.Source, e.Message, e.StackTrace); env.Close(); return; } Console.WriteLine("Lock #{0} granted", lockList.Count); lockList.Add(lk); } else if (buff == "release") { /* * Release a lock. */ while (true) { /* Input lock number to release. */ Console.WriteLine( "Input lock number to release"); buff = Console.ReadLine(); try { lockNo = int.Parse(buff); if (lockNo > 0 && lockNo < lockList.Count) break; else Console.WriteLine( "Lock number is out of range"); } catch { Console.WriteLine( "Not a valid lock number"); } } /* Release a lock and remove it from the list of locks. */ try { env.PutLock(lockList[lockNo]); } catch (Exception e) { Console.WriteLine("{0}:{1}\n{2}", e.Source, e.Message, e.StackTrace); env.Close(); return; } lockList.Remove(lockList[lockNo]); } else if (buff == "quit") { break; } } /*Free locker and close the environment. */ env.FreeLockerID(locker); env.Close(); } /* * Create and open environment and database. */ public static int DBInit(out DatabaseEnvironment env, string home, string progName, uint maxLock, uint doUnLink) { DatabaseEnvironmentConfig envConfig; LockingConfig lkConfig; /* Configure locking subsystem. */ lkConfig = new LockingConfig(); lkConfig.MaxLocks = maxLock; /* Configure environment. */ envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.ErrorPrefix = progName; envConfig.LockSystemCfg = lkConfig; envConfig.UseLocking = true; /* * Optionally remove the environment region and * open the environment. */ try { if (doUnLink == 1) DatabaseEnvironment.Remove(home, true); env = DatabaseEnvironment.Open(home, envConfig); } catch (Exception e) { Console.WriteLine("{0}:{1}\n{2}", e.Source, e.Message, e.StackTrace); env = null; return EXIT_FAILURE; } /* try { env = DatabaseEnvironment.Open(home, envConfig); } catch(Exception e) { Console.WriteLine("{0}:{1}\n{2}", e.Source, e.Message, e.StackTrace); env = null; return ExConstants.EXIT_FAILURE; } */ return EXIT_SUCCESS; } #region Utilities /* Show the usage of the example. */ public static void Usage() { Console.WriteLine( "Usage: [home] [max lock] [1 doUnlink | 0]"); } /* Get dbt from a string. */ static void DbtFromString(DatabaseEntry dbt, string s) { dbt.Data = System.Text.Encoding.ASCII.GetBytes(s); } #endregion Utilities } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geometry; namespace ArcDataBinding { /// <summary> /// This class provides a PropertyDescriptor for a single field of an IRow /// </summary> /// <remarks> /// This class can be used by an ITypedList implementation to provide a property /// description for a single field in an ITable. /// </remarks> internal class FieldPropertyDescriptor: PropertyDescriptor { #region Private Members /// <summary> /// Store the index of the IField that this property descriptor describes /// </summary> private int wrappedFieldIndex; /// <summary> /// Store the .NET type of the value stored in the IField this property /// represents /// </summary> private Type netType; /// <summary> /// This is used to store the actual .NET type of a field that uses a CV /// domain. It retains the type allowing as to restore it when the UseCVDomain /// property is false; /// </summary> private Type actualType; /// <summary> /// Store the esri type of the value stored in the IField this property /// represents /// </summary> private esriFieldType esriType; /// <summary> /// Indicates whether this field is editable or not. /// </summary> /// <remarks> /// This will determined by looking at the Editable property of the IField /// and the type of the field. We currently don't support the editing of /// blob or geometry fields. /// </remarks> bool isEditable = true; /// <summary> /// Used to start and stop editing when adding/updating/deleting rows /// </summary> private IWorkspaceEdit wkspcEdit; /// <summary> /// The coded value domain for the field this instance represents, if any /// </summary> private ICodedValueDomain cvDomain; /// <summary> /// This will be true if we are currently using the string values for the /// coded value domain and false if we are using the numeric values. /// </summary> private bool useCVDomain; /// <summary> /// This type converter is used when the field this instance represents has /// a coded value domain and we are displaying the actual domain values /// </summary> private TypeConverter actualValueConverter; /// <summary> /// This type converter is used when the field this instance represents has /// a coded value domain and we are displaying the names of the domain values /// </summary> private TypeConverter cvDomainValDescriptionConverter; #endregion Private Members #region Construction/Destruction /// <summary> /// Initializes a new instance of the <see cref="FieldPropertyDescriptor"/> class. /// </summary> /// <param name="wrappedTable">The wrapped table.</param> /// <param name="fieldName">Name of the field within wrappedTable.</param> /// <param name="fieldIndex">Index of the field within wrappedTable.</param> public FieldPropertyDescriptor(ITable wrappedTable, string fieldName, int fieldIndex) : base(fieldName, null) { wrappedFieldIndex = fieldIndex; // Get the field this property will represent. We will use it to // get the field type and determine whether it can be edited or not. In // this case, editable means the field's editable property is true and it // is not a blob, geometry or raster field. IField wrappedField = wrappedTable.Fields.get_Field(fieldIndex); esriType = wrappedField.Type; isEditable = wrappedField.Editable && (esriType != esriFieldType.esriFieldTypeBlob) && (esriType != esriFieldType.esriFieldTypeRaster) && (esriType != esriFieldType.esriFieldTypeGeometry); netType = actualType = EsriFieldTypeToSystemType(wrappedField); wkspcEdit = ((IDataset)wrappedTable).Workspace as IWorkspaceEdit; } #endregion Construction/Destruction /// <summary> /// Gets a value indicating whether the field represented by this property /// has a CV domain. /// </summary> /// <value> /// <c>true</c> if this instance has a CV domain; otherwise, <c>false</c>. /// </value> public bool HasCVDomain { get { return null != cvDomain; } } /// <summary> /// Sets a value indicating whether [use CV domain]. /// </summary> /// <value><c>true</c> if [use CV domain]; otherwise, <c>false</c>.</value> public bool UseCVDomain { set { useCVDomain = value; if (value) { // We want the property type for this field to be string netType = typeof(string); } else { // Restore the original type netType = actualType; } } } #region Public Overrides /// <summary> /// Gets the type converter for this property. /// </summary> /// <remarks> /// We need to override this property as the base implementation sets the /// converter once and reuses it as required. We can't do this if the field /// this instance represents has a coded value domain and we change from /// using the value to using the name or vice versa. The reason for this is /// that if we are displaying the domain name, we need a string converter and /// if we are displaying the domain value, we will need one of the numeric /// converters. /// </remarks> /// <returns>A <see cref="T:System.ComponentModel.TypeConverter"></see> /// that is used to convert the <see cref="T:System.Type"></see> of this /// property.</returns> /// <PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, /// mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /// version="1" Flags="UnmanagedCode"/></PermissionSet> public override TypeConverter Converter { get { TypeConverter retVal = null; if (null != cvDomain) { if (useCVDomain) { if (null == cvDomainValDescriptionConverter) { // We want a string converter cvDomainValDescriptionConverter = TypeDescriptor.GetConverter(typeof(string)); } retVal = cvDomainValDescriptionConverter; } else { if (null == actualValueConverter) { // We want a converter for the type of this field's actual value actualValueConverter = TypeDescriptor.GetConverter(actualType); } retVal = actualValueConverter; } } else { // This field doesn't have a coded value domain, the base implementation // works fine. retVal = base.Converter; } return retVal; } } /// <summary> /// Returns whether resetting an object changes its value. /// </summary> /// <param name="component">The component to test for reset capability. /// This will be an IRow</param> /// <returns> /// true if resetting the component changes its value; otherwise, false. /// </returns> public override bool CanResetValue(object component) { return false; } /// <summary> /// Gets the type of the component this property is bound to. /// </summary> /// <value></value> /// <returns>A <see cref="T:System.Type"></see> that represents the type of /// component this property is bound to. When the /// <see cref="M:System.ComponentModel.PropertyDescriptor.GetValue(System.Object)"></see> /// or <see cref="M:System.ComponentModel.PropertyDescriptor.SetValue(System.Object,System.Object)"></see> /// methods are invoked, the object specified might be an instance of this type.</returns> public override Type ComponentType { get { return typeof(IRow); } } /// <summary> /// Gets the current value of the property on a component. /// </summary> /// <param name="component">The component (an IRow) with the property for /// which to retrieve the value.</param> /// <remarks> /// This will return the field value for all fields apart from geometry, raster and Blobs. /// These fields will return the string equivalent of the geometry type. /// </remarks> /// <returns> /// The value of a property for a given component. This will be the value of /// the field this class instance represents in the IRow passed in the component /// parameter. /// </returns> public override object GetValue(object component) { object retVal = null; IRow givenRow = (IRow)component; try { // Get value object value = givenRow.get_Value(wrappedFieldIndex); if ((null != cvDomain) && useCVDomain) { value = cvDomain.get_Name(Convert.ToInt32(value)); } switch (esriType) { case esriFieldType.esriFieldTypeBlob: retVal = "Blob"; break; case esriFieldType.esriFieldTypeGeometry: retVal = GetGeometryTypeAsString(value); break; case esriFieldType.esriFieldTypeRaster: retVal = "Raster"; break; default: retVal = value; break; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } return retVal; } /// <summary> /// Gets a value indicating whether this property is read-only or not. /// </summary> /// <value></value> /// <returns>true if the property is read-only; otherwise, false.</returns> public override bool IsReadOnly { get { return !isEditable; } } /// <summary> /// Gets the type of the property. /// </summary> /// <value></value> /// <returns>A <see cref="T:System.Type"></see> that represents the type /// of the property.</returns> public override Type PropertyType { get { return netType; } } /// <summary> /// Resets the value for this property of the component to the default value. /// </summary> /// <param name="component">The component (an IRow) with the property value /// that is to be reset to the default value.</param> public override void ResetValue(object component) { } /// <summary> /// Sets the value of the component to a different value. /// </summary> /// <remarks> /// If the field this instance represents does not have a coded value domain, /// this method simply sets the given value and stores the row within an edit /// operation. If the field does have a coded value domain, the method first /// needs to check that the given value is valid. If we are displaying the /// coded values, the value passed to this method will be a string and we will /// need to see if it is one of the names in the cv domain. If we are not /// displaying the coded values, we will still need to check that the given /// value is within the domain. If the value is not within the domain, an /// error will be displayed and the method will return. /// Note that the string comparison is case sensitive. /// </remarks> /// <param name="component">The component (an IRow) with the property value /// that is to be set.</param> /// <param name="value">The new value.</param> public override void SetValue(object component, object value) { IRow givenRow = (IRow)component; if (null != cvDomain) { // This field has a coded value domain if (!useCVDomain) { // Check value is valid member of the domain if (!((IDomain)cvDomain).MemberOf(value)) { System.Windows.Forms.MessageBox.Show(string.Format( "Value {0} is not valid for coded value domain {1}", value.ToString(), ((IDomain)cvDomain).Name)); return; } } else { // We need to convert the string value to one of the cv domain values // Loop through all the values until we, hopefully, find a match bool foundMatch = false; for (int valueCount = 0; valueCount < cvDomain.CodeCount; valueCount++) { if (value.ToString() == cvDomain.get_Name(valueCount)) { foundMatch = true; value = valueCount; break; } } // Did we find a match? if (!foundMatch) { System.Windows.Forms.MessageBox.Show(string.Format( "Value {0} is not valid for coded value domain {1}", value.ToString(), ((IDomain)cvDomain).Name)); return; } } } givenRow.set_Value(wrappedFieldIndex, value); // Start editing if we aren't already editing bool weStartedEditing = false; if (!wkspcEdit.IsBeingEdited()) { wkspcEdit.StartEditing(false); weStartedEditing = true; } // Store change in an edit operation wkspcEdit.StartEditOperation(); givenRow.Store(); wkspcEdit.StopEditOperation(); // Stop editing if we started here if (weStartedEditing) { wkspcEdit.StopEditing(true); } } /// <summary> /// When overridden in a derived class, determines a value indicating whether /// the value of this property needs to be persisted. /// </summary> /// <param name="component">The component (an IRow) with the property to be examined for /// persistence.</param> /// <returns> /// true if the property should be persisted; otherwise, false. /// </returns> public override bool ShouldSerializeValue(object component) { return false; } #endregion Public Overrides #region Private Methods /// <summary> /// Converts the specified ESRI field type to a .NET type. /// </summary> /// <param name="esriType">The ESRI field type to be converted.</param> /// <returns>The appropriate .NET type.</returns> private Type EsriFieldTypeToSystemType(IField field) { esriFieldType esriType = field.Type; // Does this field have a domain? cvDomain = field.Domain as ICodedValueDomain; if ((null != cvDomain) && useCVDomain) { return typeof(string); } try { switch (esriType) { case esriFieldType.esriFieldTypeBlob: //beyond scope of sample to deal with blob fields return typeof(string); case esriFieldType.esriFieldTypeDate: return typeof(DateTime); case esriFieldType.esriFieldTypeDouble: return typeof(double); case esriFieldType.esriFieldTypeGeometry: return typeof(string); case esriFieldType.esriFieldTypeGlobalID: return typeof(string); case esriFieldType.esriFieldTypeGUID: return typeof(Guid); case esriFieldType.esriFieldTypeInteger: return typeof(Int32); case esriFieldType.esriFieldTypeOID: return typeof(Int32); case esriFieldType.esriFieldTypeRaster: //beyond scope of sample to correctly display rasters return typeof(string); case esriFieldType.esriFieldTypeSingle: return typeof(Single); case esriFieldType.esriFieldTypeSmallInteger: return typeof(Int16); case esriFieldType.esriFieldTypeString: return typeof(string); default: return typeof(string); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return typeof(string); } } /// <summary> /// Gets the geometry type as string. /// </summary> /// <param name="value">The value.</param> /// <returns>The string equivalent of the geometry type</returns> private string GetGeometryTypeAsString(object value) { string retVal = ""; IGeometry geometry = value as IGeometry; if (geometry != null) { retVal = geometry.GeometryType.ToString(); } return retVal; } #endregion Private Methods } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.Asn1.LBEREncoder.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap.Asn1 { /// <summary> This class provides LBER encoding routines for ASN.1 Types. LBER is a /// subset of BER as described in the following taken from 5.1 of RFC 2251: /// /// 5.1. Mapping Onto BER-based Transport Services /// /// The protocol elements of Ldap are encoded for exchange using the /// Basic Encoding Rules (BER) [11] of ASN.1 [3]. However, due to the /// high overhead involved in using certain elements of the BER, the /// following additional restrictions are placed on BER-encodings of Ldap /// protocol elements: /// /// <li>(1) Only the definite form of length encoding will be used.</li> /// /// <li>(2) OCTET STRING values will be encoded in the primitive form only.</li> /// /// <li>(3) If the value of a BOOLEAN type is true, the encoding MUST have /// its contents octets set to hex "FF".</li> /// /// <li>(4) If a value of a type is its default value, it MUST be absent. /// Only some BOOLEAN and INTEGER types have default values in this /// protocol definition. /// /// These restrictions do not apply to ASN.1 types encapsulated inside of /// OCTET STRING values, such as attribute values, unless otherwise /// noted.</li> /// /// [3] ITU-T Rec. X.680, "Abstract Syntax Notation One (ASN.1) - /// Specification of Basic Notation", 1994. /// /// [11] ITU-T Rec. X.690, "Specification of ASN.1 encoding rules: Basic, /// Canonical, and Distinguished Encoding Rules", 1994. /// /// </summary> [CLSCompliantAttribute(true)] public class LBEREncoder : Asn1Encoder { /* Encoders for ASN.1 simple type Contents */ public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } /// <summary> BER Encode an Asn1Boolean directly into the specified output stream.</summary> public virtual void encode(Asn1Boolean b, System.IO.Stream out_Renamed) { /* Encode the id */ encode(b.getIdentifier(), out_Renamed); /* Encode the length */ out_Renamed.WriteByte((System.Byte) 0x01); /* Encode the boolean content*/ out_Renamed.WriteByte((byte) (b.booleanValue()?(sbyte) SupportClass.Identity(0xff):(sbyte) 0x00)); return ; } /// <summary> Encode an Asn1Numeric directly into the specified outputstream. /// /// Use a two's complement representation in the fewest number of octets /// possible. /// /// Can be used to encode INTEGER and ENUMERATED values. /// </summary> public void encode(Asn1Numeric n, System.IO.Stream out_Renamed) { sbyte[] octets = new sbyte[8]; sbyte len; long value_Renamed = n.longValue(); long endValue = (value_Renamed < 0)?- 1:0; long endSign = endValue & 0x80; for (len = 0; len == 0 || value_Renamed != endValue || (octets[len - 1] & 0x80) != endSign; len++) { octets[len] = (sbyte) (value_Renamed & 0xFF); value_Renamed >>= 8; } encode(n.getIdentifier(), out_Renamed); out_Renamed.WriteByte((byte) len); // Length for (int i = len - 1; i >= 0; i--) // Content out_Renamed.WriteByte((byte) octets[i]); return ; } /* Asn1 TYPE NOT YET SUPPORTED * Encode an Asn1Real directly to a stream. public void encode(Asn1Real r, OutputStream out) throws IOException { throw new IOException("LBEREncoder: Encode to a stream not implemented"); } */ /// <summary> Encode an Asn1Null directly into the specified outputstream.</summary> public void encode(Asn1Null n, System.IO.Stream out_Renamed) { encode(n.getIdentifier(), out_Renamed); out_Renamed.WriteByte((System.Byte) 0x00); // Length (with no Content) return ; } /* Asn1 TYPE NOT YET SUPPORTED * Encode an Asn1BitString directly to a stream. public void encode(Asn1BitString bs, OutputStream out) throws IOException { throw new IOException("LBEREncoder: Encode to a stream not implemented"); } */ /// <summary> Encode an Asn1OctetString directly into the specified outputstream.</summary> public void encode(Asn1OctetString os, System.IO.Stream out_Renamed) { encode(os.getIdentifier(), out_Renamed); encodeLength(os.byteValue().Length, out_Renamed); sbyte[] temp_sbyteArray; temp_sbyteArray = os.byteValue(); out_Renamed.Write(SupportClass.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);;; return ; } /* Asn1 TYPE NOT YET SUPPORTED * Encode an Asn1ObjectIdentifier directly to a stream. * public void encode(Asn1ObjectIdentifier oi, OutputStream out) * throws IOException * { * throw new IOException("LBEREncoder: Encode to a stream not implemented"); * } */ /* Asn1 TYPE NOT YET SUPPORTED * Encode an Asn1CharacterString directly to a stream. * public void encode(Asn1CharacterString cs, OutputStream out) * throws IOException * { * throw new IOException("LBEREncoder: Encode to a stream not implemented"); * } */ /* Encoders for ASN.1 structured types */ /// <summary> Encode an Asn1Structured into the specified outputstream. This method /// can be used to encode SET, SET_OF, SEQUENCE, SEQUENCE_OF /// </summary> public void encode(Asn1Structured c, System.IO.Stream out_Renamed) { encode(c.getIdentifier(), out_Renamed); Asn1Object[] value_Renamed = c.toArray(); System.IO.MemoryStream output = new System.IO.MemoryStream(); /* Cycle through each element encoding each element */ for (int i = 0; i < value_Renamed.Length; i++) { (value_Renamed[i]).encode(this, output); } /* Encode the length */ encodeLength((int)output.Length, out_Renamed); /* Add each encoded element into the output stream */ sbyte[] temp_sbyteArray; temp_sbyteArray = SupportClass.ToSByteArray(output.ToArray()); out_Renamed.Write(SupportClass.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);;; return ; } /// <summary> Encode an Asn1Tagged directly into the specified outputstream.</summary> public void encode(Asn1Tagged t, System.IO.Stream out_Renamed) { if (t.Explicit) { encode(t.getIdentifier(), out_Renamed); /* determine the encoded length of the base type. */ System.IO.MemoryStream encodedContent = new System.IO.MemoryStream(); t.taggedValue().encode(this, encodedContent); encodeLength((int)encodedContent.Length, out_Renamed); sbyte[] temp_sbyteArray; temp_sbyteArray = SupportClass.ToSByteArray(encodedContent.ToArray()); out_Renamed.Write(SupportClass.ToByteArray(temp_sbyteArray), 0, temp_sbyteArray.Length);;;; } else { t.taggedValue().encode(this, out_Renamed); } return ; } /* Encoders for ASN.1 useful types */ /* Encoder for ASN.1 Identifier */ /// <summary> Encode an Asn1Identifier directly into the specified outputstream.</summary> public void encode(Asn1Identifier id, System.IO.Stream out_Renamed) { int c = id.Asn1Class; int t = id.Tag; sbyte ccf = (sbyte) ((c << 6) | (id.Constructed?0x20:0)); if (t < 30) { /* single octet */ out_Renamed.WriteByte((System.Byte) (ccf | t)); } else { /* multiple octet */ out_Renamed.WriteByte((System.Byte) (ccf | 0x1F)); encodeTagInteger(t, out_Renamed); } return ; } /* Private helper methods */ /* * Encodes the specified length into the the outputstream */ private void encodeLength(int length, System.IO.Stream out_Renamed) { if (length < 0x80) { out_Renamed.WriteByte((System.Byte) length); } else { sbyte[] octets = new sbyte[4]; // 4 bytes sufficient for 32 bit int. sbyte n; for (n = 0; length != 0; n++) { octets[n] = (sbyte) (length & 0xFF); length >>= 8; } out_Renamed.WriteByte((System.Byte) (0x80 | n)); for (int i = n - 1; i >= 0; i--) out_Renamed.WriteByte((byte) octets[i]); } return ; } /// <summary> Encodes the provided tag into the outputstream.</summary> private void encodeTagInteger(int value_Renamed, System.IO.Stream out_Renamed) { sbyte[] octets = new sbyte[5]; int n; for (n = 0; value_Renamed != 0; n++) { octets[n] = (sbyte) (value_Renamed & 0x7F); value_Renamed = value_Renamed >> 7; } for (int i = n - 1; i > 0; i--) { out_Renamed.WriteByte((System.Byte) (octets[i] | 0x80)); } out_Renamed.WriteByte((byte) octets[0]); return ; } } }
using System; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using OpenIddict.Abstractions; using OpenIddict.Mvc; using OpenIddict.Server; using OpenIddict.Server.Internal; using OpenIddict.Validation; using OpenIddict.Validation.Internal; using OrchardCore.Environment.Shell; using OrchardCore.Modules; using OrchardCore.OpenId.Services; using OrchardCore.OpenId.Settings; namespace OrchardCore.OpenId.Configuration { [Feature(OpenIdConstants.Features.Server)] public class OpenIdServerConfiguration : IConfigureOptions<AuthenticationOptions>, IConfigureOptions<OpenIddictMvcOptions>, IConfigureNamedOptions<OpenIddictServerOptions>, IConfigureNamedOptions<OpenIddictValidationOptions>, IConfigureNamedOptions<JwtBearerOptions> { private readonly ILogger _logger; private readonly IRunningShellTable _runningShellTable; private readonly ShellSettings _shellSettings; private readonly IOpenIdServerService _serverService; public OpenIdServerConfiguration( ILogger<OpenIdServerConfiguration> logger, IRunningShellTable runningShellTable, ShellSettings shellSettings, IOpenIdServerService serverService) { _logger = logger; _runningShellTable = runningShellTable; _shellSettings = shellSettings; _serverService = serverService; } public void Configure(AuthenticationOptions options) { var settings = GetServerSettingsAsync().GetAwaiter().GetResult(); if (settings == null) { return; } // Register the OpenIddict handler in the authentication handlers collection. options.AddScheme<OpenIddictServerHandler>(OpenIddictServerDefaults.AuthenticationScheme, displayName: null); // If the userinfo endpoint was enabled, register a private JWT or validation handler instance. // Unlike the instance registered by the validation feature, this one is only used for the // OpenID Connect userinfo endpoint and thus only supports local opaque/JWT token validation. if (settings.UserinfoEndpointPath.HasValue) { if (settings.AccessTokenFormat == OpenIdServerSettings.TokenFormat.Encrypted) { options.AddScheme<OpenIddictValidationHandler>(OpenIdConstants.Schemes.Userinfo, displayName: null); } else if (settings.AccessTokenFormat == OpenIdServerSettings.TokenFormat.JWT) { options.AddScheme<JwtBearerHandler>(OpenIdConstants.Schemes.Userinfo, displayName: null); } else { throw new InvalidOperationException("The specified access token format is not valid."); } } } // Note: to ensure no exception is thrown while binding OpenID Connect primitives // when the OpenID server settings are invalid, the binding exceptions that are // thrown by OpenIddict to indicate the request cannot be extracted are turned off. public void Configure(OpenIddictMvcOptions options) => options.DisableBindingExceptions = true; public void Configure(string name, OpenIddictServerOptions options) { // Ignore OpenIddict handler instances that don't correspond to the instance managed by the OpenID module. if (!string.Equals(name, OpenIddictServerDefaults.AuthenticationScheme)) { return; } var settings = GetServerSettingsAsync().GetAwaiter().GetResult(); if (settings == null) { return; } // Note: in Orchard, transport security is usually configured via the dedicated HTTPS module. // To make configuration easier and avoid having to configure it in two different features, // the transport security requirement enforced by OpenIddict by default is always turned off. options.AllowInsecureHttp = true; options.ApplicationCanDisplayErrors = true; options.EnableRequestCaching = true; options.IgnoreScopePermissions = true; options.Issuer = settings.Authority; options.UseRollingTokens = settings.UseRollingTokens; options.UseReferenceTokens = settings.UseReferenceTokens; foreach (var key in _serverService.GetSigningKeysAsync().GetAwaiter().GetResult()) { options.SigningCredentials.AddKey(key); } if (settings.AccessTokenFormat == OpenIdServerSettings.TokenFormat.JWT) { options.AccessTokenHandler = new JwtSecurityTokenHandler(); } options.AuthorizationEndpointPath = settings.AuthorizationEndpointPath; options.LogoutEndpointPath = settings.LogoutEndpointPath; options.TokenEndpointPath = settings.TokenEndpointPath; options.UserinfoEndpointPath = settings.UserinfoEndpointPath; options.GrantTypes.Clear(); options.GrantTypes.UnionWith(settings.GrantTypes); options.Scopes.Add(OpenIddictConstants.Scopes.Email); options.Scopes.Add(OpenIddictConstants.Scopes.Phone); options.Scopes.Add(OpenIddictConstants.Scopes.Profile); options.Scopes.Add(OpenIddictConstants.Claims.Roles); } public void Configure(OpenIddictServerOptions options) => Debug.Fail("This infrastructure method shouldn't be called."); public void Configure(string name, JwtBearerOptions options) { // Ignore JWT handler instances that don't correspond to the private instance managed by the OpenID module. if (!string.Equals(name, OpenIdConstants.Schemes.Userinfo)) { return; } var settings = GetServerSettingsAsync().GetAwaiter().GetResult(); if (settings == null) { return; } options.TokenValidationParameters.ValidAudience = OpenIdConstants.Prefixes.Tenant + _shellSettings.Name; options.TokenValidationParameters.IssuerSigningKeys = _serverService.GetSigningKeysAsync().GetAwaiter().GetResult(); // If an authority was explicitly set in the OpenID server options, // prefer it to the dynamic tenant comparison as it's more efficient. if (settings.Authority != null) { options.TokenValidationParameters.ValidIssuer = settings.Authority.AbsoluteUri; } else { options.TokenValidationParameters.IssuerValidator = (issuer, token, parameters) => { if (!Uri.TryCreate(issuer, UriKind.Absolute, out Uri uri)) { throw new SecurityTokenInvalidIssuerException("The token issuer is not valid."); } var tenant = _runningShellTable.Match(new HostString(uri.Authority), uri.AbsolutePath); if (tenant == null || !string.Equals(tenant.Name, _shellSettings.Name)) { throw new SecurityTokenInvalidIssuerException("The token issuer is not valid."); } return issuer; }; } } public void Configure(JwtBearerOptions options) => Debug.Fail("This infrastructure method shouldn't be called."); public void Configure(string name, OpenIddictValidationOptions options) { // Ignore validation handler instances that don't correspond to the private instance managed by the OpenID module. if (!string.Equals(name, OpenIdConstants.Schemes.Userinfo)) { return; } options.Audiences.Add(OpenIdConstants.Prefixes.Tenant + _shellSettings.Name); var serverSettings = GetServerSettingsAsync().GetAwaiter().GetResult(); if (serverSettings == null) { return; } options.UseReferenceTokens = serverSettings.UseReferenceTokens; } public void Configure(OpenIddictValidationOptions options) => Debug.Fail("This infrastructure method shouldn't be called."); private async Task<OpenIdServerSettings> GetServerSettingsAsync() { var settings = await _serverService.GetSettingsAsync(); if ((await _serverService.ValidateSettingsAsync(settings)).Any(result => result != ValidationResult.Success)) { _logger.LogWarning("The OpenID Connect module is not correctly configured."); return null; } return settings; } } }
using System; using System.Collections.Generic; using System.Linq; using IxMilia.BCad.Entities; using IxMilia.BCad.Extensions; using IxMilia.BCad.Utilities; using Xunit; namespace IxMilia.BCad.Core.Test { public class TrimExtendTests : TestBase { #region Helpers private void DoTrim(IEnumerable<Entity> existingEntities, Entity entityToTrim, Point selectionPoint, bool expectTrim, IEnumerable<Entity> expectedAdded) { expectedAdded = expectedAdded ?? new Entity[0]; // prepare the drawing foreach (var ent in existingEntities) { Workspace.AddToCurrentLayer(ent); } var boundary = Workspace.Drawing.GetEntities().SelectMany(e => e.GetPrimitives()); Workspace.AddToCurrentLayer(entityToTrim); // trim IEnumerable<Entity> removed; IEnumerable<Entity> added; EditUtilities.Trim( new SelectedEntity(entityToTrim, selectionPoint), boundary, out removed, out added); // verify deleted Assert.Equal(expectTrim, removed.Any()); if (expectTrim) { Assert.Equal(1, removed.Count()); Assert.True(removed.Single().EquivalentTo(entityToTrim)); } // verify added Assert.Equal(expectedAdded.Count(), added.Count()); Assert.True(expectedAdded.Zip(added, (a, b) => a.EquivalentTo(b)).All(b => b)); } private void DoExtend(IEnumerable<Entity> existingEntities, Entity entityToExtend, Point selectionPoint, bool expectExtend, IEnumerable<Entity> expectedAdded) { expectedAdded = expectedAdded ?? new Entity[0]; // prepare the drawing foreach (var ent in existingEntities) { Workspace.AddToCurrentLayer(ent); } var boundary = Workspace.Drawing.GetEntities().SelectMany(e => e.GetPrimitives()); Workspace.AddToCurrentLayer(entityToExtend); // extend IEnumerable<Entity> removed; IEnumerable<Entity> added; EditUtilities.Extend( new SelectedEntity(entityToExtend, selectionPoint), boundary, out removed, out added); // verify deleted Assert.Equal(expectExtend, removed.Any()); if (expectExtend) { Assert.Equal(1, removed.Count()); Assert.True(removed.Single().EquivalentTo(entityToExtend)); } // verify added Assert.Equal(expectedAdded.Count(), added.Count()); Assert.True(expectedAdded.Zip(added, (a, b) => a.EquivalentTo(b)).All(b => b)); } #endregion [Fact] public void SimpleLineTrimTest() { var line = new Line(new Point(0, 0, 0), new Point(2, 0, 0)); DoTrim(new[] { new Line(new Point(1.0, -1.0, 0.0), new Point(1.0, 1.0, 0.0)) }, line, Point.Origin, true, new[] { new Line(new Point(1, 0, 0), new Point(2, 0, 0)) }); } [Fact] public void TrimWholeLineBetweenTest() { DoTrim( new[] { new Line(new Point(0.0, 0.0, 0.0), new Point(0.0, 1.0, 0.0)), new Line(new Point(1.0, 0.0, 0.0), new Point(1.0, 1.0, 0.0)) }, new Line(new Point(0.0, 0.0, 0.0), new Point(1.0, 0.0, 0.0)), new Point(0.5, 0, 0), false, null); } [Fact] public void TrimCircleAtZeroAngleTest() { DoTrim( new[] { new Line(new Point(-1.0, 0.0, 0.0), new Point(1.0, 0.0, 0.0)), }, new Circle(Point.Origin, 1.0, Vector.ZAxis), new Point(0.0, -1.0, 0.0), true, new[] { new Arc(Point.Origin, 1.0, 0.0, 180.0, Vector.ZAxis) }); } [Fact] public void TrimHalfArcTest() { // _________ ____ // / | \ | \ // o/ | \ => | \ // | | | | | // | | | | | var sqrt2 = Math.Sqrt(2.0); DoTrim( new[] { new Line(new Point(0.0, 0.0, 0.0), new Point(0.0, 1.0, 0.0)) }, new Arc(Point.Origin, 1.0, 0.0, 180.0, Vector.ZAxis), new Point(-sqrt2 / 2.0, sqrt2 / 2.0, 0.0), true, new[] { new Arc(Point.Origin, 1.0, 0.0, 90.0, Vector.ZAxis) }); } [Fact] public void IsometricCircleTrimTest() { // ____ ___ // / / \ / / // / / | / / // / / | => / / // | / / | / // | / /o | / // \____/ \ DoTrim( new[] { new Line(new Point(-0.612372435695796, -1.0606617177983, 0.0), new Point(0.6123724356958, 1.06066017177983, 0.0)) }, new Ellipse(Point.Origin, new Vector(0.6123724356958, 1.06066017177983, 0.0), 0.577350269189626, 0, 360, Vector.ZAxis), new Point(0.612372435695806, -0.353553390593266, 0.0), true, new[] { new Ellipse(Point.Origin, new Vector(0.6123724356958, 1.06066017177983, 0.0), 0.577350269189626, 0, 180.000062635721, Vector.ZAxis) }); } [Fact] public void SimpleExtendTest() { // | => | // ----o | ---------| // | | DoExtend( new[] { new Line(new Point(2.0, -1.0, 0.0), new Point(2.0, 1.0, 0.0)) }, new Line(new Point(0.0, 0.0, 0.0), new Point(1.0, 0.0, 0.0)), new Point(1.0, 0.0, 0.0), true, new[] { new Line(new Point(0.0, 0.0, 0.0), new Point(2.0, 0.0, 0.0)) }); } [Fact] public void NoExtendFromFurtherPointTest() { // | => | // -o--- | ---------| // | | DoExtend( new[] { new Line(new Point(2.0, -1.0, 0.0), new Point(2.0, 1.0, 0.0)) }, new Line(new Point(0.0, 0.0, 0.0), new Point(1.0, 0.0, 0.0)), new Point(0.1, 0.0, 0.0), false, null); } [Fact] public void SimpleArcExtendTest() { // o / --\ / // / / / / // | / => | / // \ / \ / // --- --- DoExtend( new[] { new Line(new Point(0.0, 0.0, 0.0), new Point(1.0, 1.0, 0.0)) }, new Arc(new Point(0.0, 0.0, 0.0), 1.0, 90.0, 360.0, Vector.ZAxis), new Point(0.0, 1.0, 0.0), true, new[] { new Arc(new Point(0.0, 0.0, 0.0), 1.0, 45.0, 360.0, Vector.ZAxis) }); } [Fact] public void SimpleExtendArcNotAtOriginTest() { // / / // / / // o | => | | // | \ | // | \_| DoExtend( new[] { new Line(new Point(1.0, 1.0, 0.0), new Point(1.0, 0.0, 0.0)) }, new Arc(new Point(1.0, 1.0, 0.0), 1.0, 90.0, 180.0, Vector.ZAxis), new Point(0.0, 1.0, 0.0), true, new[] { new Arc(new Point(1.0, 1.0, 0.0), 1.0, 90.0, 270.0, Vector.ZAxis) }); } } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; namespace SixLabors.Fonts.Unicode { /// <summary> /// An enumerator for retrieving Grapheme instances from a <see cref="ReadOnlySpan{Char}"/>. /// <br/> /// Implements the Unicode Grapheme Cluster Algorithm. UAX:29 /// <see href="https://www.unicode.org/reports/tr29/tr29-37.html"/> /// <br/> /// Methods are pattern-matched by compiler to allow using foreach pattern. /// </summary> public ref struct SpanGraphemeEnumerator { private ReadOnlySpan<char> source; /// <summary> /// Initializes a new instance of the <see cref="SpanGraphemeEnumerator"/> struct. /// </summary> /// <param name="source">The buffer to read from.</param> public SpanGraphemeEnumerator(ReadOnlySpan<char> source) { this.source = source; this.Current = default; } /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> public ReadOnlySpan<char> Current { get; private set; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An enumerator that iterates through the collection.</returns> public SpanGraphemeEnumerator GetEnumerator() => this; /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// <see langword="true"/> if the enumerator was successfully advanced to the next element; /// <see langword="false"/> if the enumerator has passed the end of the collection. /// </returns> public bool MoveNext() { if (this.source.IsEmpty) { return false; } // Algorithm given at https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules. var processor = new Processor(this.source); processor.MoveNext(); // First, consume as many Prepend scalars as we can (rule GB9b). while (processor.CurrentType == GraphemeClusterClass.Prepend) { processor.MoveNext(); } // Next, make sure we're not about to violate control character restrictions. // Essentially, if we saw Prepend data, we can't have Control | CR | LF data afterward (rule GB5). if (processor.CharsConsumed > 0) { if (processor.CurrentType is GraphemeClusterClass.Control or GraphemeClusterClass.CarriageReturn or GraphemeClusterClass.LineFeed) { goto Return; } } // Now begin the main state machine. GraphemeClusterClass previousClusterBreakType = processor.CurrentType; processor.MoveNext(); switch (previousClusterBreakType) { case GraphemeClusterClass.CarriageReturn: if (processor.CurrentType != GraphemeClusterClass.LineFeed) { goto Return; // rules GB3 & GB4 (only <LF> can follow <CR>) } processor.MoveNext(); goto case GraphemeClusterClass.LineFeed; case GraphemeClusterClass.Control: case GraphemeClusterClass.LineFeed: goto Return; // rule GB4 (no data after Control | LF) case GraphemeClusterClass.HangulLead: if (processor.CurrentType == GraphemeClusterClass.HangulLead) { processor.MoveNext(); // rule GB6 (L x L) goto case GraphemeClusterClass.HangulLead; } else if (processor.CurrentType == GraphemeClusterClass.HangulVowel) { processor.MoveNext(); // rule GB6 (L x V) goto case GraphemeClusterClass.HangulVowel; } else if (processor.CurrentType == GraphemeClusterClass.HangulLeadVowel) { processor.MoveNext(); // rule GB6 (L x LV) goto case GraphemeClusterClass.HangulLeadVowel; } else if (processor.CurrentType == GraphemeClusterClass.HangulLeadVowelTail) { processor.MoveNext(); // rule GB6 (L x LVT) goto case GraphemeClusterClass.HangulLeadVowelTail; } else { break; } case GraphemeClusterClass.HangulLeadVowel: case GraphemeClusterClass.HangulVowel: if (processor.CurrentType == GraphemeClusterClass.HangulVowel) { processor.MoveNext(); // rule GB7 (LV | V x V) goto case GraphemeClusterClass.HangulVowel; } else if (processor.CurrentType == GraphemeClusterClass.HangulTail) { processor.MoveNext(); // rule GB7 (LV | V x T) goto case GraphemeClusterClass.HangulTail; } else { break; } case GraphemeClusterClass.HangulLeadVowelTail: case GraphemeClusterClass.HangulTail: if (processor.CurrentType == GraphemeClusterClass.HangulTail) { processor.MoveNext(); // rule GB8 (LVT | T x T) goto case GraphemeClusterClass.HangulTail; } else { break; } case GraphemeClusterClass.ExtendedPictographic: // Attempt processing extended pictographic (rules GB11, GB9). // First, drain any Extend scalars that might exist while (processor.CurrentType == GraphemeClusterClass.Extend) { processor.MoveNext(); } // Now see if there's a ZWJ + extended pictograph again. if (processor.CurrentType != GraphemeClusterClass.ZeroWidthJoiner) { break; } processor.MoveNext(); if (processor.CurrentType != GraphemeClusterClass.ExtendedPictographic) { break; } processor.MoveNext(); goto case GraphemeClusterClass.ExtendedPictographic; case GraphemeClusterClass.RegionalIndicator: // We've consumed a single RI scalar. Try to consume another (to make it a pair). if (processor.CurrentType == GraphemeClusterClass.RegionalIndicator) { processor.MoveNext(); } // Standalone RI scalars (or a single pair of RI scalars) can only be followed by trailers. break; // nothing but trailers after the final RI default: break; } // rules GB9, GB9a while (processor.CurrentType is GraphemeClusterClass.Extend or GraphemeClusterClass.ZeroWidthJoiner or GraphemeClusterClass.SpacingMark) { processor.MoveNext(); } Return: this.Current = this.source.Slice(0, processor.CharsConsumed); this.source = this.source.Slice(processor.CharsConsumed); return true; // rules GB2, GB999 } private ref struct Processor { private readonly ReadOnlySpan<char> source; private int charsConsumed; public Processor(ReadOnlySpan<char> source) { this.source = source; this.CurrentType = GraphemeClusterClass.Any; this.charsConsumed = 0; this.CharsConsumed = 0; } public GraphemeClusterClass CurrentType { get; private set; } public int CharsConsumed { get; private set; } public void MoveNext() { this.CharsConsumed += this.charsConsumed; var codePoint = CodePoint.DecodeFromUtf16At(this.source, this.CharsConsumed, out this.charsConsumed); this.CurrentType = CodePoint.GetGraphemeClusterClass(codePoint); } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Text; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Data; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// Prepare to write out an archive. /// </summary> public class ArchiveWriteRequestPreparation { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected Scene m_scene; protected Stream m_saveStream; protected Guid m_requestId; protected bool m_storeAssets = true; protected C5.HashSet<UUID> m_allowedCreatorIds = new C5.HashSet<UUID>(); public bool MustCheckCreatorIds { get { return m_allowedCreatorIds.Count > 0; } } public ArchiveWriteRequestPreparation(Scene scene, string savePath, Guid requestId, bool storeAssets, IEnumerable<UUID> allowedCreatorIds) : this(scene, savePath, requestId, storeAssets) { foreach (UUID creatorId in allowedCreatorIds) { m_allowedCreatorIds.Add(creatorId); } } /// <summary> /// Constructor /// </summary> public ArchiveWriteRequestPreparation(Scene scene, string savePath, Guid requestId, bool storeAssets) { m_scene = scene; m_saveStream = new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress); m_requestId = requestId; m_storeAssets = storeAssets; } /// <summary> /// Constructor. /// </summary> /// <param name="scene"></param> /// <param name="saveStream">The stream to which to save data.</param> /// <param name="requestId">The id associated with this request</param> public ArchiveWriteRequestPreparation(Scene scene, Stream saveStream, Guid requestId) { m_scene = scene; m_saveStream = saveStream; m_requestId = requestId; } private bool ExportIsAllowed(UUID creatorId) { if (m_allowedCreatorIds.IsEmpty) { return true; } else { return m_allowedCreatorIds.Contains(creatorId); } } protected void AddObjectUsersToList(List<UUID> userlist, SceneObjectGroup grp) { foreach (SceneObjectPart part in grp.GetParts()) { if (!userlist.Contains(part.OwnerID)) userlist.Add(part.OwnerID); if (!userlist.Contains(part.CreatorID)) userlist.Add(part.CreatorID); foreach (TaskInventoryItem item in part.TaskInventory.Values) { if (!userlist.Contains(item.CreatorID)) userlist.Add(item.CreatorID); } } } /// <summary> /// Archive the region requested. /// </summary> /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception> public void ArchiveRegion() { Dictionary<UUID, int> assetUuids = new Dictionary<UUID, int>(); List<EntityBase> entities = m_scene.GetEntities(); List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); List<UUID> userlist = new List<UUID>(); // Filter entities so that we only have scene objects. // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods // end up having to do this foreach (EntityBase entity in entities) { if (entity is SceneObjectGroup) { SceneObjectGroup sceneObject = (SceneObjectGroup)entity; // If storing assets, assume cross-grid and include the user list file if (m_storeAssets) { AddObjectUsersToList(userlist, sceneObject); } if (MustCheckCreatorIds) { bool failedCreatorCheck = false; foreach (SceneObjectPart part in sceneObject.GetParts()) { if (!ExportIsAllowed(part.CreatorID)) { failedCreatorCheck = true; break; } } if (failedCreatorCheck) { continue; } } if (!sceneObject.IsDeleted && !sceneObject.IsAttachment) sceneObjects.Add(sceneObject); } } if (m_storeAssets) { UuidGatherer assetGatherer = new UuidGatherer(m_scene.CommsManager.AssetCache); foreach (SceneObjectGroup sceneObject in sceneObjects) { assetGatherer.GatherAssetUuids(sceneObject, assetUuids); } } // Make sure that we also request terrain texture assets RegionSettings regionSettings = m_scene.RegionInfo.RegionSettings; if (m_storeAssets) { if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1) assetUuids[regionSettings.TerrainTexture1] = 1; if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2) assetUuids[regionSettings.TerrainTexture2] = 1; if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3) assetUuids[regionSettings.TerrainTexture3] = 1; if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4) assetUuids[regionSettings.TerrainTexture4] = 1; } if (MustCheckCreatorIds) { int originalCount = assetUuids.Count; m_log.DebugFormat( "[ARCHIVER]: Filtering {0} asset IDs for {1} allowed creators", originalCount, m_allowedCreatorIds.Count); C5.HashSet<UUID> assetsCreatedByAllowedUsers = this.CollectCreatedAssetIdsFromUserInventories(); IEnumerable<UUID> uuids = new List<UUID>(assetUuids.Keys); assetUuids.Clear(); foreach (UUID assetId in uuids) { if (assetsCreatedByAllowedUsers.Contains(assetId)) { assetUuids.Add(assetId, 1); } } m_log.DebugFormat( "[ARCHIVER]: Allowing export of {0} of {1} assets", assetUuids.Count, originalCount); } m_log.DebugFormat( "[ARCHIVER]: {0} scene objects to serialize requiring save of {1} assets", sceneObjects.Count, assetUuids.Count); TarArchiveWriter archiveWriter = new TarArchiveWriter(m_saveStream); // Asynchronously request all the assets required to perform this archive operation ArchiveWriteRequestExecution awre = new ArchiveWriteRequestExecution( sceneObjects, m_scene.RequestModuleInterface<ITerrainModule>(), m_scene.RequestModuleInterface<IRegionSerializerModule>(), m_scene, archiveWriter, m_requestId); // Write out archive.xml control file first archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, awre.CreateControlFile(assetUuids.Count > 0)); m_log.InfoFormat("[ARCHIVER]: Added {0} control file to archive.", ArchiveConstants.CONTROL_FILE_PATH); // Now include the user list file (only if assets are being saved and it produced a list). if (userlist.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (UUID id in userlist) { String name = m_scene.CommsManager.UserService.Key2Name(id, false); if (!String.IsNullOrWhiteSpace(name)) sb.AppendFormat("{0} {1}{2}", id, name, Environment.NewLine); } String userlistContents = sb.ToString(); if (!String.IsNullOrWhiteSpace(userlistContents)) { archiveWriter.WriteFile(ArchiveConstants.USERLIST_FILE_PATH, userlistContents); m_log.InfoFormat("[ARCHIVER]: Added {0} file to archive.", ArchiveConstants.USERLIST_FILE_PATH); } } new AssetsRequest( new AssetsArchiver(archiveWriter, m_scene), assetUuids.Keys, m_scene.CommsManager.AssetCache, awre.ReceivedAllAssets).Execute(); } private C5.HashSet<UUID> CollectCreatedAssetIdsFromUserInventories() { C5.HashSet<UUID> retAssets = new C5.HashSet<UUID>(); foreach (UUID creatorId in m_allowedCreatorIds) { this.CollectCreatedAssetIdsFromUserInventory(creatorId, retAssets); } return retAssets; } private void CollectCreatedAssetIdsFromUserInventory(UUID creatorId, C5.HashSet<UUID> retAssets) { IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>(); IInventoryStorage provider = selector.GetProvider(creatorId); List<InventoryFolderBase> skel = provider.GetInventorySkeleton(creatorId); foreach (InventoryFolderBase folder in skel) { InventoryFolderBase fullFolder = provider.GetFolder(folder.ID); foreach (InventoryItemBase item in fullFolder.Items) { if (m_allowedCreatorIds.Contains(item.CreatorIdAsUuid)) { retAssets.Add(item.AssetID); } } } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using LanguageExt.Common; using LanguageExt.Effects.Traits; namespace LanguageExt.Pipes { /// <summary> /// One of the algebraic cases of the `Proxy` type. This type represents a resource using computation. It is /// useful for tidying up resources explicitly (if required). /// </summary> /// <remarks> /// The `Proxy` system will tidy up resources automatically, however you must wait until the end of the /// computation. This case allows earlier clean up. /// </remarks> /// <typeparam name="RT">Aff system runtime</typeparam> /// <typeparam name="UOut">Upstream out type</typeparam> /// <typeparam name="UIn">Upstream in type</typeparam> /// <typeparam name="DIn">Downstream in type</typeparam> /// <typeparam name="DOut">Downstream uut type</typeparam> /// <typeparam name="A">The monadic bound variable - it doesn't flow up or down stream, it works just like any bound /// monadic variable. If the effect represented by the `Proxy` ends, then this will be the result value. /// /// When composing `Proxy` sub-types (like `Producer`, `Pipe`, `Consumer`, etc.) </typeparam> public abstract class Use<RT, UOut, UIn, DIn, DOut, A> : Proxy<RT, UOut, UIn, DIn, DOut, A> where RT : struct, HasCancel<RT> { internal abstract Proxy<RT, UOut, UIn, DIn, DOut, A> Run(ConcurrentDictionary<object, IDisposable> disps); } /// <summary> /// One of the algebraic cases of the `Proxy` type. This type represents a resource using computation. It is /// useful for tidying up resources explicitly (if required). /// </summary> /// <remarks> /// The `Proxy` system will tidy up resources automatically, however you must wait until the end of the /// computation. This case allows earlier clean up. /// </remarks> /// <typeparam name="RT">Aff system runtime</typeparam> /// <typeparam name="UOut">Upstream out type</typeparam> /// <typeparam name="UIn">Upstream in type</typeparam> /// <typeparam name="DIn">Downstream in type</typeparam> /// <typeparam name="DOut">Downstream uut type</typeparam> /// <typeparam name="A">The monadic bound variable - it doesn't flow up or down stream, it works just like any bound /// monadic variable. If the effect represented by the `Proxy` ends, then this will be the result value. /// /// When composing `Proxy` sub-types (like `Producer`, `Pipe`, `Consumer`, etc.) </typeparam> public class Use<RT, UOut, UIn, DIn, DOut, X, A> : Use<RT, UOut, UIn, DIn, DOut, A> where RT : struct, HasCancel<RT> { public readonly Func<Aff<RT, X>> Acquire; public readonly Func<X, Unit> Release; public readonly Func<X, Proxy<RT, UOut, UIn, DIn, DOut, A>> Next; public Use(Func<Aff<RT, X>> acquire, Func<X, Unit> release, Func<X, Proxy<RT, UOut, UIn, DIn, DOut, A>> next) => (Acquire, Release, Next) = (acquire, release, next); [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, A> ToProxy() => this; [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, B> Bind<B>(Func<A, Proxy<RT, UOut, UIn, DIn, DOut, B>> f) => new Use<RT, UOut, UIn, DIn, DOut, X, B>(Acquire, Release, x => Next(x).Bind(f)); [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, B> Map<B>(Func<A, B> f) => new Use<RT, UOut, UIn, DIn, DOut, X, B>(Acquire, Release, x => Next(x).Map(f)); [Pure] public override Proxy<RT, UOut, UIn, C1, C, A> For<C1, C>(Func<DOut, Proxy<RT, UOut, UIn, C1, C, DIn>> body) => new Use<RT, UOut, UIn, C1, C, X, A>(Acquire, Release, x => Next(x).For(body)); [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, B> Action<B>(Proxy<RT, UOut, UIn, DIn, DOut, B> rhs) => new Use<RT, UOut, UIn, DIn, DOut, X, B>(Acquire, Release, x => Next(x).Action(rhs)); [Pure] public override Proxy<RT, UOutA, AUInA, DIn, DOut, A> ComposeRight<UOutA, AUInA>(Func<UOut, Proxy<RT, UOutA, AUInA, UOut, UIn, A>> lhs) => new Use<RT, UOutA, AUInA, DIn, DOut, X, A>(Acquire, Release, x => Next(x).ComposeRight(lhs)); [Pure] public override Proxy<RT, UOutA, AUInA, DIn, DOut, A> ComposeRight<UOutA, AUInA>(Func<UOut, Proxy<RT, UOutA, AUInA, DIn, DOut, UIn>> lhs) => new Use<RT, UOutA, AUInA, DIn, DOut, X, A>(Acquire, Release, x => Next(x).ComposeRight(lhs)); [Pure] public override Proxy<RT, UOut, UIn, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<DOut, Proxy<RT, DIn, DOut, DInC, DOutC, A>> rhs) => new Use<RT, UOut, UIn, DInC, DOutC, X, A>(Acquire, Release, x => Next(x).ComposeLeft(rhs)); [Pure] public override Proxy<RT, UOut, UIn, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<DOut, Proxy<RT, UOut, UIn, DInC, DOutC, DIn>> rhs) => new Use<RT, UOut, UIn, DInC, DOutC, X, A>(Acquire, Release, x => Next(x).ComposeLeft(rhs)); [Pure] public override Proxy<RT, DOut, DIn, UIn, UOut, A> Reflect() => new Use<RT, DOut, DIn, UIn, UOut, X, A>(Acquire, Release, x => Next(x).Reflect()); [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, A> Observe() => new Use<RT, UOut, UIn, DIn, DOut, X, A>(Acquire, Release, x => Next(x).Observe()); [Pure] public void Deconstruct(out Func<Aff<RT, X>> acquire, out Func<X, Unit> release, out Func<X, Proxy<RT, UOut, UIn, DIn, DOut, A>> next) => (acquire, release, next) = (Acquire, Release, Next); [Pure] internal override Proxy<RT, UOut, UIn, DIn, DOut, A> Run(ConcurrentDictionary<object, IDisposable> disps) => new M<RT, UOut, UIn, DIn, DOut, A>( Acquire().Map(x => { disps.TryAdd(x, new Disp(() => Release(x))); return x; }).Map(Next)); } internal class Disp : IDisposable { readonly Action dispose; int disposed = 0; public Disp(Action dispose) => this.dispose = dispose; public void Dispose() { if (Interlocked.CompareExchange(ref disposed, 1, 0) == 0) { dispose?.Invoke(); } } } /// <summary> /// One of the algebraic cases of the `Proxy` type. This type represents a resource releasing computation. It is /// useful for tidying up resources that have been used (explicitly). /// </summary> /// <remarks> /// The `Proxy` system will tidy up resources automatically, however you must wait until the end of the /// computation. This case allows earlier clean up. /// </remarks> /// <typeparam name="RT">Aff system runtime</typeparam> /// <typeparam name="UOut">Upstream out type</typeparam> /// <typeparam name="UIn">Upstream in type</typeparam> /// <typeparam name="DIn">Downstream in type</typeparam> /// <typeparam name="DOut">Downstream uut type</typeparam> /// <typeparam name="A">The monadic bound variable - it doesn't flow up or down stream, it works just like any bound /// monadic variable. If the effect represented by the `Proxy` ends, then this will be the result value. /// /// When composing `Proxy` sub-types (like `Producer`, `Pipe`, `Consumer`, etc.) </typeparam> public abstract class Release<RT, UOut, UIn, DIn, DOut, A> : Proxy<RT, UOut, UIn, DIn, DOut, A> where RT : struct, HasCancel<RT> { internal abstract Proxy<RT, UOut, UIn, DIn, DOut, A> Run(ConcurrentDictionary<object, IDisposable> disps); } /// <summary> /// One of the algebraic cases of the `Proxy` type. This type represents a resource releasing computation. It is /// useful for tidying up resources that have been used (explicitly). /// </summary> /// <remarks> /// The `Proxy` system will tidy up resources automatically, however you must wait until the end of the /// computation. This case allows earlier clean up. /// </remarks> /// <typeparam name="RT">Aff system runtime</typeparam> /// <typeparam name="UOut">Upstream out type</typeparam> /// <typeparam name="UIn">Upstream in type</typeparam> /// <typeparam name="DIn">Downstream in type</typeparam> /// <typeparam name="DOut">Downstream uut type</typeparam> /// <typeparam name="A">The monadic bound variable - it doesn't flow up or down stream, it works just like any bound /// monadic variable. If the effect represented by the `Proxy` ends, then this will be the result value. /// /// When composing `Proxy` sub-types (like `Producer`, `Pipe`, `Consumer`, etc.) </typeparam> public class Release<RT, UOut, UIn, DIn, DOut, X, A> : Release<RT, UOut, UIn, DIn, DOut, A> where RT : struct, HasCancel<RT> { public readonly X Value; public readonly Func<Unit, Proxy<RT, UOut, UIn, DIn, DOut, A>> Next; public Release(X value, Func<Unit, Proxy<RT, UOut, UIn, DIn, DOut, A>> next) => (Value, Next) = (value, next); [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, A> ToProxy() => this; [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, B> Bind<B>(Func<A, Proxy<RT, UOut, UIn, DIn, DOut, B>> f) => new Release<RT, UOut, UIn, DIn, DOut, X, B>(Value, x => Next(x).Bind(f)); [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, B> Map<B>(Func<A, B> f) => new Release<RT, UOut, UIn, DIn, DOut, X, B>(Value, x => Next(x).Map(f)); [Pure] public override Proxy<RT, UOut, UIn, C1, C, A> For<C1, C>(Func<DOut, Proxy<RT, UOut, UIn, C1, C, DIn>> body) => new Release<RT, UOut, UIn, C1, C, X, A>(Value, x => Next(x).For(body)); [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, B> Action<B>(Proxy<RT, UOut, UIn, DIn, DOut, B> rhs) => new Release<RT, UOut, UIn, DIn, DOut, X, B>(Value, x => Next(x).Action(rhs)); [Pure] public override Proxy<RT, UOutA, AUInA, DIn, DOut, A> ComposeRight<UOutA, AUInA>(Func<UOut, Proxy<RT, UOutA, AUInA, UOut, UIn, A>> lhs) => new Release<RT, UOutA, AUInA, DIn, DOut, X, A>(Value, x => Next(x).ComposeRight(lhs)); [Pure] public override Proxy<RT, UOutA, AUInA, DIn, DOut, A> ComposeRight<UOutA, AUInA>(Func<UOut, Proxy<RT, UOutA, AUInA, DIn, DOut, UIn>> lhs) => new Release<RT, UOutA, AUInA, DIn, DOut, X, A>(Value, x => Next(x).ComposeRight(lhs)); [Pure] public override Proxy<RT, UOut, UIn, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<DOut, Proxy<RT, DIn, DOut, DInC, DOutC, A>> rhs) => new Release<RT, UOut, UIn, DInC, DOutC, X, A>(Value, x => Next(x).ComposeLeft(rhs)); [Pure] public override Proxy<RT, UOut, UIn, DInC, DOutC, A> ComposeLeft<DInC, DOutC>(Func<DOut, Proxy<RT, UOut, UIn, DInC, DOutC, DIn>> rhs) => new Release<RT, UOut, UIn, DInC, DOutC, X, A>(Value, x => Next(x).ComposeLeft(rhs)); [Pure] public override Proxy<RT, DOut, DIn, UIn, UOut, A> Reflect() => new Release<RT, DOut, DIn, UIn, UOut, X, A>(Value, x => Next(x).Reflect()); [Pure] public override Proxy<RT, UOut, UIn, DIn, DOut, A> Observe() => new Release<RT, UOut, UIn, DIn, DOut, X, A>(Value, x => Next(x).Observe()); [Pure] public void Deconstruct(out X value, out Func<Unit, Proxy<RT, UOut, UIn, DIn, DOut, A>> next) => (value, next) = (Value, Next); [Pure] internal override Proxy<RT, UOut, UIn, DIn, DOut, A> Run(ConcurrentDictionary<object, IDisposable> disps) => new M<RT, UOut, UIn, DIn, DOut, A>( Prelude.Eff<RT, Unit>(_ => { if (disps.TryRemove(Value, out var d)) { d.Dispose(); } return Prelude.unit; }).Map(Next)); } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Management.Automation.Internal; namespace System.Management.Automation { #region OutputRendering /// <summary> /// Defines the options for output rendering. /// </summary> public enum OutputRendering { /// <summary>Render ANSI only to host.</summary> Host = 0, /// <summary>Render as plaintext.</summary> PlainText = 1, /// <summary>Render as ANSI.</summary> Ansi = 2, } #endregion OutputRendering /// <summary> /// Defines the options for views of progress rendering. /// </summary> public enum ProgressView { /// <summary>Render progress using minimal space.</summary> Minimal = 0, /// <summary>Classic rendering of progress.</summary> Classic = 1, } #region PSStyle /// <summary> /// Contains configuration for how PowerShell renders text. /// </summary> public sealed class PSStyle { /// <summary> /// Contains foreground colors. /// </summary> public sealed class ForegroundColor { /// <summary> /// Gets the color black. /// </summary> public string Black { get; } = "\x1b[30m"; /// <summary> /// Gets the color blue. /// </summary> public string Blue { get; } = "\x1b[34m"; /// <summary> /// Gets the color cyan. /// </summary> public string Cyan { get; } = "\x1b[36m"; /// <summary> /// Gets the color dark gray. /// </summary> public string DarkGray { get; } = "\x1b[90m"; /// <summary> /// Gets the color green. /// </summary> public string Green { get; } = "\x1b[32m"; /// <summary> /// Gets the color light blue. /// </summary> public string LightBlue { get; } = "\x1b[94m"; /// <summary> /// Gets the color light cyan. /// </summary> public string LightCyan { get; } = "\x1b[96m"; /// <summary> /// Gets the color light gray. /// </summary> public string LightGray { get; } = "\x1b[97m"; /// <summary> /// Gets the color light green. /// </summary> public string LightGreen { get; } = "\x1b[92m"; /// <summary> /// Gets the color light magenta. /// </summary> public string LightMagenta { get; } = "\x1b[95m"; /// <summary> /// Gets the color light red. /// </summary> public string LightRed { get; } = "\x1b[91m"; /// <summary> /// Gets the color light yellow. /// </summary> public string LightYellow { get; } = "\x1b[93m"; /// <summary> /// Gets the color magenta. /// </summary> public string Magenta { get; } = "\x1b[35m"; /// <summary> /// Gets the color read. /// </summary> public string Red { get; } = "\x1b[31m"; /// <summary> /// Gets the color white. /// </summary> public string White { get; } = "\x1b[37m"; /// <summary> /// Gets the color yellow. /// </summary> public string Yellow { get; } = "\x1b[33m"; /// <summary> /// Set as RGB (Red, Green, Blue). /// </summary> /// <param name="red">Byte value representing red.</param> /// <param name="green">Byte value representing green.</param> /// <param name="blue">Byte value representing blue.</param> /// <returns>String representing ANSI code for RGB value.</returns> public string FromRgb(byte red, byte green, byte blue) { return $"\x1b[38;2;{red};{green};{blue}m"; } /// <summary> /// The color set as RGB as a single number. /// </summary> /// <param name="rgb">RGB value specified as an integer.</param> /// <returns>String representing ANSI code for RGB value.</returns> public string FromRgb(int rgb) { byte red, green, blue; blue = (byte)(rgb & 0xFF); rgb >>= 8; green = (byte)(rgb & 0xFF); rgb >>= 8; red = (byte)(rgb & 0xFF); return FromRgb(red, green, blue); } } /// <summary> /// Contains background colors. /// </summary> public sealed class BackgroundColor { /// <summary> /// Gets the color black. /// </summary> public string Black { get; } = "\x1b[40m"; /// <summary> /// Gets the color blue. /// </summary> public string Blue { get; } = "\x1b[44m"; /// <summary> /// Gets the color cyan. /// </summary> public string Cyan { get; } = "\x1b[46m"; /// <summary> /// Gets the color dark gray. /// </summary> public string DarkGray { get; } = "\x1b[100m"; /// <summary> /// Gets the color green. /// </summary> public string Green { get; } = "\x1b[42m"; /// <summary> /// Gets the color light blue. /// </summary> public string LightBlue { get; } = "\x1b[104m"; /// <summary> /// Gets the color light cyan. /// </summary> public string LightCyan { get; } = "\x1b[106m"; /// <summary> /// Gets the color light gray. /// </summary> public string LightGray { get; } = "\x1b[107m"; /// <summary> /// Gets the color light green. /// </summary> public string LightGreen { get; } = "\x1b[102m"; /// <summary> /// Gets the color light magenta. /// </summary> public string LightMagenta { get; } = "\x1b[105m"; /// <summary> /// Gets the color light red. /// </summary> public string LightRed { get; } = "\x1b[101m"; /// <summary> /// Gets the color light yellow. /// </summary> public string LightYellow { get; } = "\x1b[103m"; /// <summary> /// Gets the color magenta. /// </summary> public string Magenta { get; } = "\x1b[45m"; /// <summary> /// Gets the color read. /// </summary> public string Red { get; } = "\x1b[41m"; /// <summary> /// Gets the color white. /// </summary> public string White { get; } = "\x1b[47m"; /// <summary> /// Gets the color yellow. /// </summary> public string Yellow { get; } = "\x1b[43m"; /// <summary> /// The color set as RGB (Red, Green, Blue). /// </summary> /// <param name="red">Byte value representing red.</param> /// <param name="green">Byte value representing green.</param> /// <param name="blue">Byte value representing blue.</param> /// <returns>String representing ANSI code for RGB value.</returns> public string FromRgb(byte red, byte green, byte blue) { return $"\x1b[48;2;{red};{green};{blue}m"; } /// <summary> /// The color set as RGB as a single number. /// </summary> /// <param name="rgb">RGB value specified as an integer.</param> /// <returns>String representing ANSI code for RGB value.</returns> public string FromRgb(int rgb) { byte red, green, blue; blue = (byte)(rgb & 0xFF); rgb >>= 8; green = (byte)(rgb & 0xFF); rgb >>= 8; red = (byte)(rgb & 0xFF); return FromRgb(red, green, blue); } } /// <summary> /// Contains configuration for the progress bar visualization. /// </summary> public sealed class ProgressConfiguration { /// <summary> /// Gets or sets the style for progress bar. /// </summary> public string Style { get => _style; set => _style = ValidateNoContent(value); } private string _style = "\x1b[33;1m"; /// <summary> /// Gets or sets the max width of the progress bar. /// </summary> public int MaxWidth { get => _maxWidth; set { // Width less than 18 does not render correctly due to the different parts of the progress bar. if (value < 18) { throw new ArgumentOutOfRangeException(nameof(MaxWidth), PSStyleStrings.ProgressWidthTooSmall); } _maxWidth = value; } } private int _maxWidth = 120; /// <summary> /// Gets or sets the view for progress bar. /// </summary> public ProgressView View { get; set; } = ProgressView.Minimal; /// <summary> /// Gets or sets a value indicating whether to use Operating System Command (OSC) control sequences 'ESC ]9;4;' to show indicator in terminal. /// </summary> public bool UseOSCIndicator { get; set; } = false; } /// <summary> /// Contains formatting styles for steams and objects. /// </summary> public sealed class FormattingData { /// <summary> /// Gets or sets the accent style for formatting. /// </summary> public string FormatAccent { get => _formatAccent; set => _formatAccent = ValidateNoContent(value); } private string _formatAccent = "\x1b[32;1m"; /// <summary> /// Gets or sets the style for table headers. /// </summary> public string TableHeader { get => _tableHeader; set => _tableHeader = ValidateNoContent(value); } private string _tableHeader = "\x1b[32;1m"; /// <summary> /// Gets or sets the accent style for errors. /// </summary> public string ErrorAccent { get => _errorAccent; set => _errorAccent = ValidateNoContent(value); } private string _errorAccent = "\x1b[36;1m"; /// <summary> /// Gets or sets the style for error messages. /// </summary> public string Error { get => _error; set => _error = ValidateNoContent(value); } private string _error = "\x1b[31;1m"; /// <summary> /// Gets or sets the style for warning messages. /// </summary> public string Warning { get => _warning; set => _warning = ValidateNoContent(value); } private string _warning = "\x1b[33;1m"; /// <summary> /// Gets or sets the style for verbose messages. /// </summary> public string Verbose { get => _verbose; set => _verbose = ValidateNoContent(value); } private string _verbose = "\x1b[33;1m"; /// <summary> /// Gets or sets the style for debug messages. /// </summary> public string Debug { get => _debug; set => _debug = ValidateNoContent(value); } private string _debug = "\x1b[33;1m"; } /// <summary> /// Contains formatting styles for FileInfo objects. /// </summary> public sealed class FileInfoFormatting { /// <summary> /// Gets or sets the style for directories. /// </summary> public string Directory { get => _directory; set => _directory = ValidateNoContent(value); } private string _directory = "\x1b[44;1m"; /// <summary> /// Gets or sets the style for symbolic links. /// </summary> public string SymbolicLink { get => _symbolicLink; set => _symbolicLink = ValidateNoContent(value); } private string _symbolicLink = "\x1b[36;1m"; /// <summary> /// Gets or sets the style for executables. /// </summary> public string Executable { get => _executable; set => _executable = ValidateNoContent(value); } private string _executable = "\x1b[32;1m"; /// <summary> /// Custom dictionary handling validation of extension and content. /// </summary> public sealed class FileExtensionDictionary { private static string ValidateExtension(string extension) { if (!extension.StartsWith('.')) { throw new ArgumentException(PSStyleStrings.ExtensionNotStartingWithPeriod); } return extension; } private readonly Dictionary<string, string> _extensionDictionary = new(StringComparer.OrdinalIgnoreCase); /// <summary> /// Add new extension and decoration to dictionary. /// </summary> /// <param name="extension">Extension to add.</param> /// <param name="decoration">ANSI string value to add.</param> public void Add(string extension, string decoration) { _extensionDictionary.Add(ValidateExtension(extension), ValidateNoContent(decoration)); } /// <summary> /// Remove an extension from dictionary. /// </summary> /// <param name="extension">Extension to remove.</param> public void Remove(string extension) { _extensionDictionary.Remove(ValidateExtension(extension)); } /// <summary> /// Clear the dictionary. /// </summary> public void Clear() { _extensionDictionary.Clear(); } /// <summary> /// Gets or sets the decoration by specified extension. /// </summary> /// <param name="extension">Extension to get decoration for.</param> /// <returns>The decoration for specified extension.</returns> public string this[string extension] { get { return _extensionDictionary[ValidateExtension(extension)]; } set { _extensionDictionary[ValidateExtension(extension)] = ValidateNoContent(value); } } /// <summary> /// Gets whether the dictionary contains the specified extension. /// </summary> /// <param name="extension">Extension to check for.</param> /// <returns>True if the dictionary contains the specified extension, otherwise false.</returns> public bool ContainsKey(string extension) { if (string.IsNullOrEmpty(extension)) { return false; } return _extensionDictionary.ContainsKey(ValidateExtension(extension)); } /// <summary> /// Gets the extensions for the dictionary. /// </summary> /// <returns>The extensions for the dictionary.</returns> public IEnumerable<string> Keys { get { return _extensionDictionary.Keys; } } } /// <summary> /// Gets the style for archive. /// </summary> public FileExtensionDictionary Extension { get; } /// <summary> /// Initializes a new instance of the <see cref="FileInfoFormatting"/> class. /// </summary> public FileInfoFormatting() { Extension = new FileExtensionDictionary(); // archives Extension.Add(".zip", "\x1b[31;1m"); Extension.Add(".tgz", "\x1b[31;1m"); Extension.Add(".gz", "\x1b[31;1m"); Extension.Add(".tar", "\x1b[31;1m"); Extension.Add(".nupkg", "\x1b[31;1m"); Extension.Add(".cab", "\x1b[31;1m"); Extension.Add(".7z", "\x1b[31;1m"); // powershell Extension.Add(".ps1", "\x1b[33;1m"); Extension.Add(".psd1", "\x1b[33;1m"); Extension.Add(".psm1", "\x1b[33;1m"); Extension.Add(".ps1xml", "\x1b[33;1m"); } } /// <summary> /// Gets or sets the rendering mode for output. /// </summary> public OutputRendering OutputRendering { get; set; } = OutputRendering.Host; /// <summary> /// Gets value to turn off all attributes. /// </summary> public string Reset { get; } = "\x1b[0m"; /// <summary> /// Gets value to turn off blink. /// </summary> public string BlinkOff { get; } = "\x1b[25m"; /// <summary> /// Gets value to turn on blink. /// </summary> public string Blink { get; } = "\x1b[5m"; /// <summary> /// Gets value to turn off bold. /// </summary> public string BoldOff { get; } = "\x1b[22m"; /// <summary> /// Gets value to turn on blink. /// </summary> public string Bold { get; } = "\x1b[1m"; /// <summary> /// Gets value to turn on hidden. /// </summary> public string Hidden { get; } = "\x1b[8m"; /// <summary> /// Gets value to turn off hidden. /// </summary> public string HiddenOff { get; } = "\x1b[28m"; /// <summary> /// Gets value to turn on reverse. /// </summary> public string Reverse { get; } = "\x1b[7m"; /// <summary> /// Gets value to turn off reverse. /// </summary> public string ReverseOff { get; } = "\x1b[27m"; /// <summary> /// Gets value to turn off standout. /// </summary> public string ItalicOff { get; } = "\x1b[23m"; /// <summary> /// Gets value to turn on standout. /// </summary> public string Italic { get; } = "\x1b[3m"; /// <summary> /// Gets value to turn off underlined. /// </summary> public string UnderlineOff { get; } = "\x1b[24m"; /// <summary> /// Gets value to turn on underlined. /// </summary> public string Underline { get; } = "\x1b[4m"; /// <summary> /// Gets value to turn off strikethrough. /// </summary> public string StrikethroughOff { get; } = "\x1b[29m"; /// <summary> /// Gets value to turn on strikethrough. /// </summary> public string Strikethrough { get; } = "\x1b[9m"; /// <summary> /// Gets ANSI representation of a hyperlink. /// </summary> /// <param name="text">Text describing the link.</param> /// <param name="link">A valid hyperlink.</param> /// <returns>String representing ANSI code for the hyperlink.</returns> public string FormatHyperlink(string text, Uri link) { return $"\x1b]8;;{link}\x1b\\{text}\x1b]8;;\x1b\\"; } /// <summary> /// Gets the formatting rendering settings. /// </summary> public FormattingData Formatting { get; } /// <summary> /// Gets the configuration for progress rendering. /// </summary> public ProgressConfiguration Progress { get; } /// <summary> /// Gets foreground colors. /// </summary> public ForegroundColor Foreground { get; } /// <summary> /// Gets background colors. /// </summary> public BackgroundColor Background { get; } /// <summary> /// Gets FileInfo colors. /// </summary> public FileInfoFormatting FileInfo { get; } private static readonly PSStyle s_psstyle = new PSStyle(); private PSStyle() { Formatting = new FormattingData(); Progress = new ProgressConfiguration(); Foreground = new ForegroundColor(); Background = new BackgroundColor(); FileInfo = new FileInfoFormatting(); } private static string ValidateNoContent(string text) { var decorartedString = new StringDecorated(text); if (decorartedString.ContentLength > 0) { throw new ArgumentException(string.Format(PSStyleStrings.TextContainsContent, decorartedString.ToString(OutputRendering.PlainText))); } return text; } /// <summary> /// Gets singleton instance. /// </summary> public static PSStyle Instance { get { return s_psstyle; } } } #endregion PSStyle }
// 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.Diagnostics; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal sealed partial class StorePal { private static X509Certificate2Collection s_machineRootStore; private static readonly X509Certificate2Collection s_machineIntermediateStore = new X509Certificate2Collection(); public static IStorePal FromBlob(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { ICertificatePal singleCert; if (CertificatePal.TryReadX509Der(rawData, out singleCert) || CertificatePal.TryReadX509Pem(rawData, out singleCert)) { // The single X509 structure methods shouldn't return true and out null, only empty // collections have that behavior. Debug.Assert(singleCert != null); return SingleCertToStorePal(singleCert); } List<ICertificatePal> certPals; if (PkcsFormatReader.TryReadPkcs7Der(rawData, out certPals) || PkcsFormatReader.TryReadPkcs7Pem(rawData, out certPals) || PkcsFormatReader.TryReadPkcs12(rawData, password, out certPals)) { Debug.Assert(certPals != null); return ListToStorePal(certPals); } throw Interop.Crypto.CreateOpenSslCryptographicException(); } public static IStorePal FromFile(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { using (SafeBioHandle bio = Interop.Crypto.BioNewFile(fileName, "rb")) { Interop.Crypto.CheckValidOpenSslHandle(bio); return FromBio(bio, password); } } private static IStorePal FromBio(SafeBioHandle bio, string password) { int bioPosition = Interop.Crypto.BioTell(bio); Debug.Assert(bioPosition >= 0); ICertificatePal singleCert; if (CertificatePal.TryReadX509Pem(bio, out singleCert)) { return SingleCertToStorePal(singleCert); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); if (CertificatePal.TryReadX509Der(bio, out singleCert)) { return SingleCertToStorePal(singleCert); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); List<ICertificatePal> certPals; if (PkcsFormatReader.TryReadPkcs7Pem(bio, out certPals)) { return ListToStorePal(certPals); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); if (PkcsFormatReader.TryReadPkcs7Der(bio, out certPals)) { return ListToStorePal(certPals); } // Rewind, try again. CertificatePal.RewindBio(bio, bioPosition); if (PkcsFormatReader.TryReadPkcs12(bio, password, out certPals)) { return ListToStorePal(certPals); } // Since we aren't going to finish reading, leaving the buffer where it was when we got // it seems better than leaving it in some arbitrary other position. // // But, before seeking back to start, save the Exception representing the last reported // OpenSSL error in case the last BioSeek would change it. Exception openSslException = Interop.Crypto.CreateOpenSslCryptographicException(); // Use BioSeek directly for the last seek attempt, because any failure here should instead // report the already created (but not yet thrown) exception. Interop.Crypto.BioSeek(bio, bioPosition); throw openSslException; } public static IStorePal FromCertificate(ICertificatePal cert) { ICertificatePal duplicatedHandles = ((OpenSslX509CertificateReader)cert).DuplicateHandles(); return new CollectionBackedStoreProvider(new X509Certificate2(duplicatedHandles)); } public static IStorePal LinkFromCertificateCollection(X509Certificate2Collection certificates) { return new CollectionBackedStoreProvider(certificates); } public static IStorePal FromSystemStore(string storeName, StoreLocation storeLocation, OpenFlags openFlags) { if (storeLocation != StoreLocation.LocalMachine) { return new DirectoryBasedStoreProvider(storeName, openFlags); } if (openFlags.HasFlag(OpenFlags.ReadWrite)) { throw new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresReadOnly); } // The static store approach here is making an optimization based on not // having write support. Once writing is permitted the stores would need // to fresh-read whenever being requested (or use FileWatcher/etc). if (s_machineRootStore == null) { lock (s_machineIntermediateStore) { if (s_machineRootStore == null) { LoadMachineStores(); } } } if (StringComparer.Ordinal.Equals("Root", storeName)) { return CloneStore(s_machineRootStore); } if (StringComparer.Ordinal.Equals("CA", storeName)) { return CloneStore(s_machineIntermediateStore); } throw new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresRootOnly); } private static IStorePal SingleCertToStorePal(ICertificatePal singleCert) { return new CollectionBackedStoreProvider(new X509Certificate2(singleCert)); } private static IStorePal ListToStorePal(List<ICertificatePal> certPals) { X509Certificate2Collection coll = new X509Certificate2Collection(); for (int i = 0; i < certPals.Count; i++) { coll.Add(new X509Certificate2(certPals[i])); } return new CollectionBackedStoreProvider(coll); } private static IStorePal CloneStore(X509Certificate2Collection seed) { X509Certificate2Collection coll = new X509Certificate2Collection(); foreach (X509Certificate2 cert in seed) { // Duplicate the certificate context into a new handle. coll.Add(new X509Certificate2(cert.Handle)); } return new CollectionBackedStoreProvider(coll); } private static void LoadMachineStores() { Debug.Assert( Monitor.IsEntered(s_machineIntermediateStore), "LoadMachineStores assumes a lock(s_machineIntermediateStore)"); X509Certificate2Collection rootStore = new X509Certificate2Collection(); DirectoryInfo rootStorePath = null; IEnumerable<FileInfo> trustedCertFiles; try { rootStorePath = new DirectoryInfo(Interop.Crypto.GetX509RootStorePath()); } catch (ArgumentException) { // If SSL_CERT_DIR is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStorePath value is ignored. } if (rootStorePath != null && rootStorePath.Exists) { trustedCertFiles = rootStorePath.EnumerateFiles(); } else { trustedCertFiles = Array.Empty<FileInfo>(); } FileInfo rootStoreFile = null; try { rootStoreFile = new FileInfo(Interop.Crypto.GetX509RootStoreFile()); } catch (ArgumentException) { // If SSL_CERT_FILE is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStoreFile value is ignored. } if (rootStoreFile != null && rootStoreFile.Exists) { trustedCertFiles = Append(trustedCertFiles, rootStoreFile); } HashSet<X509Certificate2> uniqueRootCerts = new HashSet<X509Certificate2>(); HashSet<X509Certificate2> uniqueIntermediateCerts = new HashSet<X509Certificate2>(); foreach (FileInfo file in trustedCertFiles) { using (SafeBioHandle fileBio = Interop.Crypto.BioNewFile(file.FullName, "rb")) { ICertificatePal pal; while (CertificatePal.TryReadX509Pem(fileBio, out pal) || CertificatePal.TryReadX509Der(fileBio, out pal)) { X509Certificate2 cert = new X509Certificate2(pal); // The HashSets are just used for uniqueness filters, they do not survive this method. if (StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer)) { if (uniqueRootCerts.Add(cert)) { rootStore.Add(cert); } } else { if (uniqueIntermediateCerts.Add(cert)) { s_machineIntermediateStore.Add(cert); } } } } } s_machineRootStore = rootStore; } private static IEnumerable<T> Append<T>(IEnumerable<T> current, T addition) { foreach (T element in current) yield return element; yield return addition; } } }
//------------------------------------------------------------------------------ // <copyright file="XmlCodeExporter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System; using System.Collections; using System.IO; using System.ComponentModel; using System.Xml.Schema; using System.CodeDom; using System.CodeDom.Compiler; using System.Reflection; using System.Globalization; using System.Diagnostics; using System.Security.Permissions; using System.Xml.Serialization.Advanced; /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter"]/*' /> ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlCodeExporter : CodeExporter { /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.XmlCodeExporter"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlCodeExporter(CodeNamespace codeNamespace) : base(codeNamespace, null, null, CodeGenerationOptions.GenerateProperties, null) {} /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.XmlCodeExporter1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit) : base(codeNamespace, codeCompileUnit, null, CodeGenerationOptions.GenerateProperties, null) {} /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.XmlCodeExporter2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeGenerationOptions options) : base(codeNamespace, codeCompileUnit, null, options, null) {} /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.XmlCodeExporter3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeGenerationOptions options, Hashtable mappings) : base(codeNamespace, codeCompileUnit, null, options, mappings) {} /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.XmlCodeExporter4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable mappings) : base(codeNamespace, codeCompileUnit, codeProvider, options, mappings) {} /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.ExportTypeMapping"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ExportTypeMapping(XmlTypeMapping xmlTypeMapping) { xmlTypeMapping.CheckShallow(); CheckScope(xmlTypeMapping.Scope); if (xmlTypeMapping.Accessor.Any) throw new InvalidOperationException(Res.GetString(Res.XmlIllegalWildcard)); ExportElement(xmlTypeMapping.Accessor); } /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.ExportMembersMapping"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping) { xmlMembersMapping.CheckShallow(); CheckScope(xmlMembersMapping.Scope); for (int i = 0; i < xmlMembersMapping.Count; i++) { AccessorMapping mapping = xmlMembersMapping[i].Mapping; if (mapping.Xmlns == null) { if (mapping.Attribute != null) { ExportType(mapping.Attribute.Mapping, Accessor.UnescapeName(mapping.Attribute.Name), mapping.Attribute.Namespace, null, false); } if (mapping.Elements != null) { for (int j = 0; j < mapping.Elements.Length; j++) { ElementAccessor element = mapping.Elements[j]; ExportType(element.Mapping, Accessor.UnescapeName(element.Name), element.Namespace, null, false); } } if (mapping.Text != null) { ExportType(mapping.Text.Mapping, Accessor.UnescapeName(mapping.Text.Name), mapping.Text.Namespace, null, false); } } } } void ExportElement(ElementAccessor element) { ExportType(element.Mapping, Accessor.UnescapeName(element.Name), element.Namespace, element, true); } void ExportType(TypeMapping mapping, string ns) { ExportType(mapping, null, ns, null, true); } void ExportType(TypeMapping mapping, string name, string ns, ElementAccessor rootElement, bool checkReference) { if (mapping.IsReference && mapping.Namespace != Soap.Encoding) return; if (mapping is StructMapping && checkReference && ((StructMapping)mapping).ReferencedByTopLevelElement && rootElement == null) return; if (mapping is ArrayMapping && rootElement != null && rootElement.IsTopLevelInSchema && ((ArrayMapping)mapping).TopLevelMapping != null) { mapping = ((ArrayMapping)mapping).TopLevelMapping; } CodeTypeDeclaration codeClass = null; if (ExportedMappings[mapping] == null) { ExportedMappings.Add(mapping, mapping); if (mapping.TypeDesc.IsMappedType) { codeClass = mapping.TypeDesc.ExtendedType.ExportTypeDefinition(CodeNamespace, CodeCompileUnit); } else if (mapping is EnumMapping) { codeClass = ExportEnum((EnumMapping)mapping, typeof(XmlEnumAttribute)); } else if (mapping is StructMapping) { codeClass = ExportStruct((StructMapping)mapping); } else if (mapping is ArrayMapping) { EnsureTypesExported(((ArrayMapping)mapping).Elements, ns); } if (codeClass != null) { if (!mapping.TypeDesc.IsMappedType) { // Add [GeneratedCodeAttribute(Tool=.., Version=..)] codeClass.CustomAttributes.Add(GeneratedCodeAttribute); // Add [SerializableAttribute] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(SerializableAttribute).FullName)); if (!codeClass.IsEnum) { // Add [DebuggerStepThrough] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DebuggerStepThroughAttribute).FullName)); // Add [DesignerCategory("code")] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DesignerCategoryAttribute).FullName, new CodeAttributeArgument[] {new CodeAttributeArgument(new CodePrimitiveExpression("code"))})); } AddTypeMetadata(codeClass.CustomAttributes, typeof(XmlTypeAttribute), mapping.TypeDesc.Name, Accessor.UnescapeName(mapping.TypeName), mapping.Namespace, mapping.IncludeInSchema); } else if (FindAttributeDeclaration(typeof(GeneratedCodeAttribute), codeClass.CustomAttributes) == null) { // Add [GeneratedCodeAttribute(Tool=.., Version=..)] codeClass.CustomAttributes.Add(GeneratedCodeAttribute); } ExportedClasses.Add(mapping, codeClass); } } else codeClass = (CodeTypeDeclaration)ExportedClasses[mapping]; if (codeClass != null && rootElement != null) AddRootMetadata(codeClass.CustomAttributes, mapping, name, ns, rootElement); } void AddRootMetadata(CodeAttributeDeclarationCollection metadata, TypeMapping typeMapping, string name, string ns, ElementAccessor rootElement) { string rootAttrName = typeof(XmlRootAttribute).FullName; // check that we haven't already added a root attribute since we can only add one foreach (CodeAttributeDeclaration attr in metadata) { if (attr.Name == rootAttrName) return; } CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(rootAttrName); if (typeMapping.TypeDesc.Name != name) { attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(name))); } if (ns != null) { attribute.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(ns))); } if (typeMapping.TypeDesc != null && typeMapping.TypeDesc.IsAmbiguousDataType) { attribute.Arguments.Add(new CodeAttributeArgument("DataType", new CodePrimitiveExpression(typeMapping.TypeDesc.DataType.Name))); } if ((object)(rootElement.IsNullable) != null) { attribute.Arguments.Add(new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression((bool)rootElement.IsNullable))); } metadata.Add(attribute); } CodeAttributeArgument[] GetDefaultValueArguments(PrimitiveMapping mapping, object value, out CodeExpression initExpression) { initExpression = null; if (value == null) return null; CodeExpression valueExpression = null; CodeExpression typeofValue = null; Type type = value.GetType(); CodeAttributeArgument[] arguments = null; if (mapping is EnumMapping) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (value.GetType() != typeof(string)) throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Invalid enumeration type " + value.GetType().Name)); #endif if (((EnumMapping)mapping).IsFlags) { string[] values = ((string)value).Split(null); for (int i = 0; i < values.Length; i++) { if (values[i].Length == 0) continue; CodeExpression enumRef = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(mapping.TypeDesc.FullName), values[i]); if (valueExpression != null) valueExpression = new CodeBinaryOperatorExpression(valueExpression, CodeBinaryOperatorType.BitwiseOr, enumRef); else valueExpression = enumRef; } } else { valueExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(mapping.TypeDesc.FullName), (string)value); } initExpression = valueExpression; arguments = new CodeAttributeArgument[] {new CodeAttributeArgument(valueExpression)}; } else if (type == typeof(bool) || type == typeof(Int32) || type == typeof(string) || type == typeof(double)) { initExpression = valueExpression = new CodePrimitiveExpression(value); arguments = new CodeAttributeArgument[] {new CodeAttributeArgument(valueExpression)}; } else if (type == typeof(Int16) || type == typeof(Int64) || type == typeof(float) || type == typeof(byte) || type == typeof(decimal)) { valueExpression = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo)); typeofValue = new CodeTypeOfExpression(type.FullName); arguments = new CodeAttributeArgument[] {new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression)}; initExpression = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value)); } else if (type == typeof(sbyte) || type == typeof(UInt16) || type == typeof(UInt32) || type == typeof(UInt64)) { // need to promote the non-CLS complient types value = PromoteType(type, value); valueExpression = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo)); typeofValue = new CodeTypeOfExpression(type.FullName); arguments = new CodeAttributeArgument[] {new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression)}; initExpression = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value)); } else if (type == typeof(DateTime)) { DateTime dt = (DateTime)value; string dtString; long ticks; if (mapping.TypeDesc.FormatterName == "Date") { dtString = XmlCustomFormatter.FromDate(dt); ticks = (new DateTime(dt.Year, dt.Month, dt.Day)).Ticks; } else if (mapping.TypeDesc.FormatterName == "Time") { dtString = XmlCustomFormatter.FromDateTime(dt); ticks = dt.Ticks; } else { dtString = XmlCustomFormatter.FromDateTime(dt); ticks = dt.Ticks; } valueExpression = new CodePrimitiveExpression(dtString); typeofValue = new CodeTypeOfExpression(type.FullName); arguments = new CodeAttributeArgument[] {new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression)}; initExpression = new CodeObjectCreateExpression(new CodeTypeReference(typeof(DateTime)), new CodeExpression[] {new CodePrimitiveExpression(ticks)}); } else if (type == typeof(Guid)) { valueExpression = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo)); typeofValue = new CodeTypeOfExpression(type.FullName); arguments = new CodeAttributeArgument[] {new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression)}; initExpression = new CodeObjectCreateExpression(new CodeTypeReference(typeof(Guid)), new CodeExpression[] {valueExpression}); } if (mapping.TypeDesc.FullName != type.ToString() && !(mapping is EnumMapping)) { // generate cast initExpression = new CodeCastExpression(mapping.TypeDesc.FullName, initExpression); } return arguments; } object ImportDefault(TypeMapping mapping, string defaultValue) { if (defaultValue == null) return null; if (mapping.IsList) { string[] vals = defaultValue.Trim().Split(null); // count all non-zero length values; int count = 0; for (int i = 0; i < vals.Length; i++) { if (vals[i] != null && vals[i].Length > 0) count++; } object[] values = new object[count]; count = 0; for (int i = 0; i < vals.Length; i++) { if (vals[i] != null && vals[i].Length > 0) { values[count++] = ImportDefaultValue(mapping, vals[i]); } } return values; } return ImportDefaultValue(mapping, defaultValue); } object ImportDefaultValue(TypeMapping mapping, string defaultValue) { if (defaultValue == null) return null; if (!(mapping is PrimitiveMapping)) return DBNull.Value; if (mapping is EnumMapping) { EnumMapping em = (EnumMapping)mapping; ConstantMapping[] c = em.Constants; if (em.IsFlags) { Hashtable values = new Hashtable(); string[] names = new string[c.Length]; long[] ids = new long[c.Length]; for (int i = 0; i < c.Length; i++) { ids[i] = em.IsFlags ? 1L << i : (long)i; names[i] = c[i].Name; values.Add(c[i].Name, ids[i]); } // this validates the values long val = XmlCustomFormatter.ToEnum(defaultValue, values, em.TypeName, true); return XmlCustomFormatter.FromEnum(val, names, ids, em.TypeDesc.FullName); } else { for (int i = 0; i < c.Length; i++) { if (c[i].XmlName == defaultValue) return c[i].Name; } } throw new InvalidOperationException(Res.GetString(Res.XmlInvalidDefaultValue, defaultValue, em.TypeDesc.FullName)); } // Primitive mapping PrimitiveMapping pm = (PrimitiveMapping)mapping; if (!pm.TypeDesc.HasCustomFormatter) { if (pm.TypeDesc.FormatterName == "String") return defaultValue; if (pm.TypeDesc.FormatterName == "DateTime") return XmlCustomFormatter.ToDateTime(defaultValue); Type formatter = typeof(XmlConvert); MethodInfo format = formatter.GetMethod("To" + pm.TypeDesc.FormatterName, new Type[] {typeof(string)}); if (format != null) { return format.Invoke(formatter, new Object[] {defaultValue}); } #if DEBUG Debug.WriteLineIf(DiagnosticsSwitches.XmlSerialization.TraceVerbose, "XmlSerialization::Failed to GetMethod " + formatter.Name + ".To" + pm.TypeDesc.FormatterName); #endif } else { if (pm.TypeDesc.HasDefaultSupport) { return XmlCustomFormatter.ToDefaultValue(defaultValue, pm.TypeDesc.FormatterName); } } return DBNull.Value; } void AddDefaultValueAttribute(CodeMemberField field, CodeAttributeDeclarationCollection metadata, object defaultValue, TypeMapping mapping, CodeCommentStatementCollection comments, TypeDesc memberTypeDesc, Accessor accessor, CodeConstructor ctor) { string attributeName = accessor.IsFixed ? "fixed" : "default"; if (!memberTypeDesc.HasDefaultSupport) { if (comments != null && defaultValue is string) { DropDefaultAttribute(accessor, comments, memberTypeDesc.FullName); // do not generate intializers for the user prefered types if they do not have default capability AddWarningComment(comments, Res.GetString(Res.XmlDropAttributeValue, attributeName, mapping.TypeName, defaultValue.ToString())); } return; } if (memberTypeDesc.IsArrayLike && accessor is ElementAccessor) { if (comments != null && defaultValue is string) { DropDefaultAttribute(accessor, comments, memberTypeDesc.FullName); // do not generate intializers for array-like types AddWarningComment(comments, Res.GetString(Res.XmlDropArrayAttributeValue, attributeName, defaultValue.ToString(), ((ElementAccessor)accessor).Name)); } return; } if (mapping.TypeDesc.IsMappedType && field != null && defaultValue is string) { SchemaImporterExtension extension = mapping.TypeDesc.ExtendedType.Extension; CodeExpression init = extension.ImportDefaultValue((string)defaultValue, mapping.TypeDesc.FullName); if (init != null) { if (ctor != null) { AddInitializationStatement(ctor, field, init); } else { field.InitExpression = extension.ImportDefaultValue((string)defaultValue, mapping.TypeDesc.FullName); } } if (comments != null) { DropDefaultAttribute(accessor, comments, mapping.TypeDesc.FullName); if (init == null) { AddWarningComment(comments, Res.GetString(Res.XmlNotKnownDefaultValue, extension.GetType().FullName, attributeName, (string)defaultValue, mapping.TypeName, mapping.Namespace)); } } return; } object value = null; if (defaultValue is string || defaultValue == null) { value = ImportDefault(mapping, (string)defaultValue); } if (value == null) return; if (!(mapping is PrimitiveMapping)) { if (comments != null) { DropDefaultAttribute(accessor, comments, memberTypeDesc.FullName); AddWarningComment(comments, Res.GetString(Res.XmlDropNonPrimitiveAttributeValue, attributeName, defaultValue.ToString())); } return; } PrimitiveMapping pm = (PrimitiveMapping)mapping; if (comments != null && !pm.TypeDesc.HasDefaultSupport && pm.TypeDesc.IsMappedType) { // do not generate intializers for the user prefered types if they do not have default capability DropDefaultAttribute(accessor, comments, pm.TypeDesc.FullName); return; } if (value == DBNull.Value) { if (comments != null) { AddWarningComment(comments, Res.GetString(Res.XmlDropAttributeValue, attributeName, pm.TypeName, defaultValue.ToString())); } return; } CodeAttributeArgument[] arguments = null; CodeExpression initExpression = null; if (pm.IsList) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (value.GetType() != typeof(object[])) throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Default value for list should be object[], not " + value.GetType().Name)); #endif object[] vals = (object[])value; CodeExpression[] initializers = new CodeExpression[vals.Length]; for (int i = 0; i < vals.Length; i++) { GetDefaultValueArguments(pm, vals[i], out initializers[i]); } initExpression = new CodeArrayCreateExpression(field.Type, initializers); } else { arguments = GetDefaultValueArguments(pm, value, out initExpression); } if (field != null) { if (ctor != null) { AddInitializationStatement(ctor, field, initExpression); } else { field.InitExpression = initExpression; } } if (arguments != null && pm.TypeDesc.HasDefaultSupport && accessor.IsOptional && !accessor.IsFixed) { // Add [DefaultValueAttribute] CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(DefaultValueAttribute).FullName, arguments); metadata.Add(attribute); } else if (comments != null) { DropDefaultAttribute(accessor, comments, memberTypeDesc.FullName); } } static void AddInitializationStatement(CodeConstructor ctor, CodeMemberField field, CodeExpression init) { CodeAssignStatement assign = new CodeAssignStatement(); assign.Left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name); assign.Right = init; ctor.Statements.Add(assign); } static void DropDefaultAttribute(Accessor accessor, CodeCommentStatementCollection comments, string type) { if (!accessor.IsFixed && accessor.IsOptional) { AddWarningComment(comments, Res.GetString(Res.XmlDropDefaultAttribute, type)); } } CodeTypeDeclaration ExportStruct(StructMapping mapping) { if (mapping.TypeDesc.IsRoot) { ExportRoot(mapping, typeof(XmlIncludeAttribute)); return null; } string className = mapping.TypeDesc.Name; string baseName = mapping.TypeDesc.BaseTypeDesc == null || mapping.TypeDesc.BaseTypeDesc.IsRoot ? string.Empty : mapping.TypeDesc.BaseTypeDesc.FullName; CodeTypeDeclaration codeClass = new CodeTypeDeclaration(className); codeClass.IsPartial = CodeProvider.Supports(GeneratorSupport.PartialTypes); codeClass.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); CodeNamespace.Types.Add(codeClass); CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = (ctor.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; codeClass.Members.Add(ctor); if (mapping.TypeDesc.IsAbstract) { ctor.Attributes |= MemberAttributes.Abstract; } if (baseName != null && baseName.Length > 0) { codeClass.BaseTypes.Add(baseName); } else AddPropertyChangedNotifier(codeClass); codeClass.TypeAttributes |= TypeAttributes.Public; if (mapping.TypeDesc.IsAbstract) { codeClass.TypeAttributes |= TypeAttributes.Abstract; } AddIncludeMetadata(codeClass.CustomAttributes, mapping, typeof(XmlIncludeAttribute)); if (mapping.IsSequence) { int generatedSequence = 0; for (int i = 0; i < mapping.Members.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.IsParticle && member.SequenceId < 0) member.SequenceId = generatedSequence++; } } if (GenerateProperties) { for (int i = 0; i < mapping.Members.Length; i++) { ExportProperty(codeClass, mapping.Members[i], mapping.Namespace, mapping.Scope, ctor); } } else { for (int i = 0; i < mapping.Members.Length; i++) { ExportMember(codeClass, mapping.Members[i], mapping.Namespace, ctor); } } for (int i = 0; i < mapping.Members.Length; i++) { if (mapping.Members[i].Xmlns != null) continue; EnsureTypesExported(mapping.Members[i].Elements, mapping.Namespace); EnsureTypesExported(mapping.Members[i].Attribute, mapping.Namespace); EnsureTypesExported(mapping.Members[i].Text, mapping.Namespace); } if (mapping.BaseMapping != null) ExportType(mapping.BaseMapping, null, mapping.Namespace, null, false); ExportDerivedStructs(mapping); CodeGenerator.ValidateIdentifiers(codeClass); if (ctor.Statements.Count == 0) codeClass.Members.Remove(ctor); return codeClass; } [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] internal override void ExportDerivedStructs(StructMapping mapping) { for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) ExportType(derived, mapping.Namespace); } /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.AddMappingMetadata"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AddMappingMetadata(CodeAttributeDeclarationCollection metadata, XmlTypeMapping mapping, string ns) { mapping.CheckShallow(); CheckScope(mapping.Scope); // For struct or enum mappings, we generate the XmlRoot on the struct/class/enum. For primitives // or arrays, there is nowhere to generate the XmlRoot, so we generate it elsewhere (on the // method for web services get/post). if (mapping.Mapping is StructMapping || mapping.Mapping is EnumMapping) return; AddRootMetadata(metadata, mapping.Mapping, Accessor.UnescapeName(mapping.Accessor.Name), mapping.Accessor.Namespace, mapping.Accessor); } /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.AddMappingMetadata1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AddMappingMetadata(CodeAttributeDeclarationCollection metadata, XmlMemberMapping member, string ns, bool forceUseMemberName) { AddMemberMetadata(null, metadata, member.Mapping, ns, forceUseMemberName, null, null); } /// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.AddMappingMetadata2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AddMappingMetadata(CodeAttributeDeclarationCollection metadata, XmlMemberMapping member, string ns) { AddMemberMetadata(null, metadata, member.Mapping, ns, false, null, null); } void ExportArrayElements(CodeAttributeDeclarationCollection metadata, ArrayMapping array, string ns, TypeDesc elementTypeDesc, int nestingLevel) { for (int i = 0; i < array.Elements.Length; i++) { ElementAccessor arrayElement = array.Elements[i]; TypeMapping elementMapping = arrayElement.Mapping; string elementName = Accessor.UnescapeName(arrayElement.Name); bool sameName = arrayElement.Mapping.TypeDesc.IsArray ? false : elementName == arrayElement.Mapping.TypeName; bool sameElementType = elementMapping.TypeDesc == elementTypeDesc; bool sameElementNs = arrayElement.Form == XmlSchemaForm.Unqualified || arrayElement.Namespace == ns; bool sameNullable = arrayElement.IsNullable == elementMapping.TypeDesc.IsNullable; bool defaultForm = arrayElement.Form != XmlSchemaForm.Unqualified; if (!sameName || !sameElementType || !sameElementNs || !sameNullable || !defaultForm || nestingLevel > 0) ExportArrayItem(metadata, sameName ? null : elementName, sameElementNs ? null : arrayElement.Namespace, sameElementType ? null : elementMapping.TypeDesc, elementMapping.TypeDesc, arrayElement.IsNullable, defaultForm ? XmlSchemaForm.None : arrayElement.Form, nestingLevel); if (elementMapping is ArrayMapping) ExportArrayElements(metadata, (ArrayMapping) elementMapping, ns, elementTypeDesc.ArrayElementTypeDesc, nestingLevel+1); } } void AddMemberMetadata(CodeMemberField field, CodeAttributeDeclarationCollection metadata, MemberMapping member, string ns, bool forceUseMemberName, CodeCommentStatementCollection comments, CodeConstructor ctor) { if (member.Xmlns != null) { CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(XmlNamespaceDeclarationsAttribute).FullName); metadata.Add(attribute); } else if (member.Attribute != null) { AttributeAccessor attribute = member.Attribute; if (attribute.Any) ExportAnyAttribute(metadata); else { TypeMapping mapping = (TypeMapping)attribute.Mapping; string attrName = Accessor.UnescapeName(attribute.Name); bool sameType = mapping.TypeDesc == member.TypeDesc || (member.TypeDesc.IsArrayLike && mapping.TypeDesc == member.TypeDesc.ArrayElementTypeDesc); bool sameName = attrName == member.Name && !forceUseMemberName; bool sameNs = attribute.Namespace == ns; bool defaultForm = attribute.Form != XmlSchemaForm.Qualified; ExportAttribute(metadata, sameName ? null : attrName, sameNs || defaultForm ? null : attribute.Namespace, sameType ? null : mapping.TypeDesc, mapping.TypeDesc, defaultForm ? XmlSchemaForm.None : attribute.Form); AddDefaultValueAttribute(field, metadata, attribute.Default, mapping, comments, member.TypeDesc, attribute, ctor); } } else { if (member.Text != null) { TypeMapping mapping = (TypeMapping)member.Text.Mapping; bool sameType = mapping.TypeDesc == member.TypeDesc || (member.TypeDesc.IsArrayLike && mapping.TypeDesc == member.TypeDesc.ArrayElementTypeDesc); ExportText(metadata, sameType ? null : mapping.TypeDesc, mapping.TypeDesc.IsAmbiguousDataType ? mapping.TypeDesc.DataType.Name : null); } if (member.Elements.Length == 1) { ElementAccessor element = member.Elements[0]; TypeMapping mapping = (TypeMapping)element.Mapping; string elemName = Accessor.UnescapeName(element.Name); bool sameName = ((elemName == member.Name) && !forceUseMemberName); bool isArray = mapping is ArrayMapping; bool sameNs = element.Namespace == ns; bool defaultForm = element.Form != XmlSchemaForm.Unqualified; if (element.Any) ExportAnyElement(metadata, elemName, element.Namespace, member.SequenceId); else if (isArray) { bool sameType = mapping.TypeDesc == member.TypeDesc; ArrayMapping array = (ArrayMapping)mapping; if (!sameName || !sameNs || element.IsNullable || !defaultForm || member.SequenceId != -1) ExportArray(metadata, sameName ? null : elemName, sameNs ? null : element.Namespace, element.IsNullable, defaultForm ? XmlSchemaForm.None : element.Form, member.SequenceId); else if (mapping.TypeDesc.ArrayElementTypeDesc == new TypeScope().GetTypeDesc(typeof(byte))) { // special case for byte[]. It can be a primitive (base64Binary or hexBinary), or it can // be an array of bytes. Our default is primitive; specify [XmlArray] to get array behavior. ExportArray(metadata, null, null, false, XmlSchemaForm.None, member.SequenceId); } ExportArrayElements(metadata, array, element.Namespace, member.TypeDesc.ArrayElementTypeDesc, 0); } else { bool sameType = mapping.TypeDesc == member.TypeDesc || (member.TypeDesc.IsArrayLike && mapping.TypeDesc == member.TypeDesc.ArrayElementTypeDesc); if (member.TypeDesc.IsArrayLike) sameName = false; ExportElement(metadata, sameName ? null : elemName, sameNs ? null : element.Namespace, sameType ? null : mapping.TypeDesc, mapping.TypeDesc, element.IsNullable, defaultForm ? XmlSchemaForm.None : element.Form, member.SequenceId); } AddDefaultValueAttribute(field, metadata, element.Default, mapping, comments, member.TypeDesc, element, ctor); } else { for (int i = 0; i < member.Elements.Length; i++) { ElementAccessor element = member.Elements[i]; string elemName = Accessor.UnescapeName(element.Name); bool sameNs = element.Namespace == ns; if (element.Any) ExportAnyElement(metadata, elemName, element.Namespace, member.SequenceId); else { bool defaultForm = element.Form != XmlSchemaForm.Unqualified; ExportElement(metadata, elemName, sameNs ? null : element.Namespace, ((TypeMapping)element.Mapping).TypeDesc, ((TypeMapping)element.Mapping).TypeDesc, element.IsNullable, defaultForm ? XmlSchemaForm.None : element.Form, member.SequenceId); } } } if (member.ChoiceIdentifier != null) { CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(XmlChoiceIdentifierAttribute).FullName); attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(member.ChoiceIdentifier.MemberName))); metadata.Add(attribute); } if (member.Ignore) { CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(XmlIgnoreAttribute).FullName); metadata.Add(attribute); } } } void ExportMember(CodeTypeDeclaration codeClass, MemberMapping member, string ns, CodeConstructor ctor) { string fieldType = member.GetTypeName(CodeProvider); CodeMemberField field = new CodeMemberField(fieldType, member.Name); field.Attributes = (field.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; field.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); codeClass.Members.Add(field); AddMemberMetadata(field, field.CustomAttributes, member, ns, false, field.Comments, ctor); if (member.CheckSpecified != SpecifiedAccessor.None) { field = new CodeMemberField(typeof(bool).FullName, member.Name + "Specified"); field.Attributes = (field.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; field.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(XmlIgnoreAttribute).FullName); field.CustomAttributes.Add(attribute); codeClass.Members.Add(field); } } void ExportProperty(CodeTypeDeclaration codeClass, MemberMapping member, string ns, CodeIdentifiers memberScope, CodeConstructor ctor) { string fieldName = memberScope.AddUnique(MakeFieldName(member.Name), member); string fieldType = member.GetTypeName(CodeProvider); // need to create a private field CodeMemberField field = new CodeMemberField(fieldType, fieldName); field.Attributes = MemberAttributes.Private; codeClass.Members.Add(field); CodeMemberProperty prop = CreatePropertyDeclaration(field, member.Name, fieldType); prop.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); AddMemberMetadata(field, prop.CustomAttributes, member, ns, false, prop.Comments, ctor); codeClass.Members.Add(prop); if (member.CheckSpecified != SpecifiedAccessor.None) { field = new CodeMemberField(typeof(bool).FullName, fieldName + "Specified"); field.Attributes = MemberAttributes.Private; codeClass.Members.Add(field); prop = CreatePropertyDeclaration(field, member.Name + "Specified", typeof(bool).FullName); prop.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(XmlIgnoreAttribute).FullName); prop.CustomAttributes.Add(attribute); codeClass.Members.Add(prop); } } void ExportText(CodeAttributeDeclarationCollection metadata, TypeDesc typeDesc, string dataType) { CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(XmlTextAttribute).FullName); if (typeDesc != null) { attribute.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(typeDesc.FullName))); } if (dataType != null) { attribute.Arguments.Add(new CodeAttributeArgument("DataType", new CodePrimitiveExpression(dataType))); } metadata.Add(attribute); } void ExportAttribute(CodeAttributeDeclarationCollection metadata, string name, string ns, TypeDesc typeDesc, TypeDesc dataTypeDesc, XmlSchemaForm form) { ExportMetadata(metadata, typeof(XmlAttributeAttribute), name, ns, typeDesc, dataTypeDesc, null, form, 0, -1); } void ExportArrayItem(CodeAttributeDeclarationCollection metadata, string name, string ns, TypeDesc typeDesc, TypeDesc dataTypeDesc, bool isNullable, XmlSchemaForm form, int nestingLevel) { ExportMetadata(metadata, typeof(XmlArrayItemAttribute), name, ns, typeDesc, dataTypeDesc, isNullable ? null : (object)false, form, nestingLevel, -1); } void ExportElement(CodeAttributeDeclarationCollection metadata, string name, string ns, TypeDesc typeDesc, TypeDesc dataTypeDesc, bool isNullable, XmlSchemaForm form, int sequenceId) { ExportMetadata(metadata, typeof(XmlElementAttribute), name, ns, typeDesc, dataTypeDesc, isNullable ? (object)true : null, form, 0, sequenceId); } void ExportArray(CodeAttributeDeclarationCollection metadata, string name, string ns, bool isNullable, XmlSchemaForm form, int sequenceId) { ExportMetadata(metadata, typeof(XmlArrayAttribute), name, ns, null, null, isNullable ? (object)true : null, form, 0, sequenceId); } void ExportMetadata(CodeAttributeDeclarationCollection metadata, Type attributeType, string name, string ns, TypeDesc typeDesc, TypeDesc dataTypeDesc, object isNullable, XmlSchemaForm form, int nestingLevel, int sequenceId) { CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(attributeType.FullName); if (name != null) { attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(name))); } if (typeDesc != null) { if (isNullable != null && (bool)isNullable && typeDesc.IsValueType && !typeDesc.IsMappedType && CodeProvider.Supports(GeneratorSupport.GenericTypeReference)) { attribute.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression("System.Nullable`1[" + typeDesc.FullName + "]"))); isNullable = null; } else { attribute.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(typeDesc.FullName))); } } if (form != XmlSchemaForm.None) { attribute.Arguments.Add(new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(XmlSchemaForm).FullName), Enum.Format(typeof(XmlSchemaForm), form, "G")))); if (form == XmlSchemaForm.Unqualified && ns != null && ns.Length == 0) { ns = null; } } if (ns != null ) { attribute.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(ns))); } if (dataTypeDesc != null && dataTypeDesc.IsAmbiguousDataType && !dataTypeDesc.IsMappedType) { attribute.Arguments.Add(new CodeAttributeArgument("DataType", new CodePrimitiveExpression(dataTypeDesc.DataType.Name))); } if (isNullable != null) { attribute.Arguments.Add(new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression((bool)isNullable))); } if (nestingLevel > 0) { attribute.Arguments.Add(new CodeAttributeArgument("NestingLevel", new CodePrimitiveExpression(nestingLevel))); } if (sequenceId >= 0) { attribute.Arguments.Add(new CodeAttributeArgument("Order", new CodePrimitiveExpression(sequenceId))); } if (attribute.Arguments.Count == 0 && attributeType == typeof(XmlElementAttribute)) return; metadata.Add(attribute); } void ExportAnyElement(CodeAttributeDeclarationCollection metadata, string name, string ns, int sequenceId) { CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(XmlAnyElementAttribute).FullName); if (name != null && name.Length > 0) { attribute.Arguments.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(name))); } if (ns != null) { attribute.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(ns))); } if (sequenceId >= 0) { attribute.Arguments.Add(new CodeAttributeArgument("Order", new CodePrimitiveExpression(sequenceId))); } metadata.Add(attribute); } void ExportAnyAttribute(CodeAttributeDeclarationCollection metadata) { metadata.Add(new CodeAttributeDeclaration(typeof(XmlAnyAttributeAttribute).FullName)); } internal override void EnsureTypesExported(Accessor[] accessors, string ns) { if (accessors == null) return; for (int i = 0; i < accessors.Length; i++) EnsureTypesExported(accessors[i], ns); } void EnsureTypesExported(Accessor accessor, string ns) { if (accessor == null) return; ExportType(accessor.Mapping, null, ns, null, false); } } }
//------------------------------------------------------------------------------ // <copyright file="MobileListItem.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections; using System.ComponentModel; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Security.Permissions; namespace System.Web.UI.MobileControls { /* * List Item type - enumeration. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItemType"]/*' /> [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public enum MobileListItemType { /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItemType.HeaderItem"]/*' /> HeaderItem, /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItemType.ListItem"]/*' /> ListItem, /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItemType.FooterItem"]/*' /> FooterItem, /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItemType.SeparatorItem"]/*' /> SeparatorItem } /* * Mobile List Item class. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem"]/*' /> [ PersistName("Item"), ToolboxItem(false) ] [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class MobileListItem : TemplateContainer, IStateManager { private const int SELECTED = 0; private const int MARKED = 1; private const int TEXTISDIRTY = 2; private const int VALUEISDIRTY = 3; private const int SELECTIONISDIRTY = 4; private int _index; private MobileListItemType _itemType; private Object _dataItem; private String _text; private String _value; private BitArray _flags; /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.MobileListItem"]/*' /> public MobileListItem() : this(null, null, null) { } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.MobileListItem1"]/*' /> public MobileListItem(String text) : this(null, text, null) { } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.MobileListItem2"]/*' /> public MobileListItem(String text, String value) : this(null, text, value) { } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.MobileListItem3"]/*' /> public MobileListItem(MobileListItemType itemType) : this (null, null, null) { _itemType = itemType; } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.MobileListItem4"]/*' /> public MobileListItem(Object dataItem, String text, String value) { _index = -1; _dataItem = dataItem; _text = text; _value = value; _flags = new BitArray(5); _itemType = MobileListItemType.ListItem; } internal MobileListItemType ItemType { get { return _itemType; } } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.Index"]/*' /> [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public int Index { get { return _index; } } internal void SetIndex(int value) { _index = value; } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.operatorMobileListItem"]/*' /> public static implicit operator MobileListItem(String s) { return new MobileListItem(s); } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.Text"]/*' /> [ DefaultValue("") ] public String Text { get { String s; if (_text != null) { s = _text; } else if (_value != null) { s = _value; } else { s = String.Empty; } return s; } set { _text = value; if (((IStateManager)this).IsTrackingViewState) { _flags.Set (TEXTISDIRTY,true); } } } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.Value"]/*' /> [ DefaultValue("") ] public String Value { get { String s; if (_value != null) { s = _value; } else if (_text != null) { s = _text; } else { s = String.Empty; } return s; } set { _value = value; if (_flags.Get (MARKED)) { _flags.Set (VALUEISDIRTY,true); } } } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.DataItem"]/*' /> [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public Object DataItem { get { return _dataItem; } set { _dataItem = value; } } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.Equals"]/*' /> public override bool Equals(Object o) { MobileListItem other = o as MobileListItem; if (other != null) { return Value.Equals(other.Value) && Text.Equals(other.Text); } return false; } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.GetHashCode"]/*' /> public override int GetHashCode() { return Value.GetHashCode(); } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.FromString"]/*' /> public static MobileListItem FromString(String s) { return new MobileListItem(s); } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.ToString"]/*' /> public override String ToString() { return Text; } ///////////////////////////////////////////////////////////////////////// // STATE MANAGEMENT, FOR ITEM'S DATA (NON-CONTROL) STATE. ///////////////////////////////////////////////////////////////////////// internal virtual Object SaveDataState() { String sa0 = _flags.Get(TEXTISDIRTY) ? _text : null; String sa1 = _flags.Get(VALUEISDIRTY) ? _value : null; if (sa0 == null && sa1 == null) { return null; } else { return new String[2] { sa0, sa1 }; } } internal virtual void LoadDataState(Object state) { if (state != null) { String[] sa = (String[])state; if (sa[0] != null) { Text = sa[0]; } if (sa[1] != null) { Value = sa[1]; } } } /// <internalonly/> protected new bool IsTrackingViewState { get { return _flags.Get (MARKED); } } /// <internalonly/> protected new void LoadViewState(Object state) { LoadDataState (state); } /// <internalonly/> protected new void TrackViewState() { _flags.Set (MARKED, true); } /// <internalonly/> protected new Object SaveViewState() { return SaveDataState (); } internal virtual bool Dirty { get { return (_flags.Get(TEXTISDIRTY) || _flags.Get(VALUEISDIRTY)); } set { _flags.Set (TEXTISDIRTY, value); _flags.Set (VALUEISDIRTY, value); } } internal bool SelectionDirty { get { return _flags.Get(SELECTIONISDIRTY); } set { _flags.Set (SELECTIONISDIRTY, value); } } /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="ListItem.Selected"]/*' /> /// <devdoc> /// <para>Specifies a value indicating whether the /// item is selected.</para> /// </devdoc> [ DefaultValue(false) ] public bool Selected { get { return _flags.Get(SELECTED); } set { _flags.Set(SELECTED,value); if (((IStateManager)this).IsTrackingViewState) { SelectionDirty = true; } } } ///////////////////////////////////////////////////////////////////////// // EVENT BUBBLING ///////////////////////////////////////////////////////////////////////// /// <include file='doc\MobileListItem.uex' path='docs/doc[@for="MobileListItem.OnBubbleEvent"]/*' /> protected override bool OnBubbleEvent(Object source, EventArgs e) { if (e is CommandEventArgs) { ListCommandEventArgs args = new ListCommandEventArgs(this, source, (CommandEventArgs)e); RaiseBubbleEvent (this, args); return true; } return false; } #region Implementation of IStateManager /// <internalonly/> bool IStateManager.IsTrackingViewState { get { return IsTrackingViewState; } } /// <internalonly/> void IStateManager.LoadViewState(object state) { LoadViewState(state); } /// <internalonly/> void IStateManager.TrackViewState() { TrackViewState(); } /// <internalonly/> object IStateManager.SaveViewState() { return SaveViewState(); } #endregion } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; using sqlite3_int64 = System.Int64; using u32 = System.UInt32; using System.Text; namespace System.Data.SQLite { public partial class Sqlite3 { /* ************************************************************************* ** ** This file contains low-level memory & pool allocation drivers ** ** This file contains implementations of the low-level memory allocation ** routines specified in the sqlite3_mem_methods object. ** ************************************************************************* */ /* ** Like malloc(), but remember the size of the allocation ** so that we can find it later using sqlite3MemSize(). ** ** For this low-level routine, we are guaranteed that nByte>0 because ** cases of nByte<=0 will be intercepted and dealt with by higher level ** routines. */ #if SQLITE_POOL_MEM static byte[] sqlite3MemMalloc( u32 nByte ) { return new byte[nByte]; } static byte[] sqlite3MemMalloc( int nByte ) { return new byte[nByte]; } static int[] sqlite3MemMallocInt( int nInt ) { return new int[nInt]; } static Mem sqlite3MemMallocMem( Mem dummy ) { Mem pMem; mem0.msMem.alloc++; if ( mem0.msMem.next > 0 && mem0.aMem[mem0.msMem.next] != null ) { pMem = mem0.aMem[mem0.msMem.next]; mem0.aMem[mem0.msMem.next] = null; mem0.msMem.cached++; mem0.msMem.next--; } else pMem = new Mem(); return pMem; } static BtCursor sqlite3MemMallocBtCursor( BtCursor dummy ) { BtCursor pBtCursor; mem0.msBtCursor.alloc++; if ( mem0.msBtCursor.next > 0 && mem0.aBtCursor[mem0.msBtCursor.next] != null ) { pBtCursor = mem0.aBtCursor[mem0.msBtCursor.next]; Debug.Assert( pBtCursor.pNext == null && pBtCursor.pPrev == null && pBtCursor.wrFlag == 0 ); mem0.aBtCursor[mem0.msBtCursor.next] = null; mem0.msBtCursor.cached++; mem0.msBtCursor.next--; } else pBtCursor = new BtCursor(); return pBtCursor; } #endif /* ** Free memory. */ // -- overloads --------------------------------------- static void sqlite3MemFree<T>(ref T x) where T : class { x = null; } static void sqlite3MemFree(ref string x) { x = null; } // /* ** Like free() but works for allocations obtained from sqlite3MemMalloc() ** or sqlite3MemRealloc(). ** ** For this low-level routine, we already know that pPrior!=0 since ** cases where pPrior==0 will have been intecepted and dealt with ** by higher-level routines. */ #if SQLITE_POOL_MEM static void sqlite3MemFreeInt( ref int[] pPrior ) { pPrior = null; } static void sqlite3MemFreeMem( ref Mem pPrior ) { if ( pPrior == null ) return; #if FALSE && DEBUG for (int i = mem0.msMem.next - 1; i >= 0; i--) if (mem0.aMem[i] != null && mem0.aMem[i] == pPrior) Debugger.Break(); #endif mem0.msMem.dealloc++; if ( mem0.msMem.next < mem0.aMem.Length - 1 ) { pPrior.db = null; pPrior._SumCtx = null; pPrior._MD5Context = null; pPrior._SubProgram = null; pPrior.flags = MEM_Null; pPrior.r = 0; pPrior.u.i = 0; pPrior.n = 0; if ( pPrior.zBLOB != null ) sqlite3MemFree( ref pPrior.zBLOB ); mem0.aMem[++mem0.msMem.next] = pPrior; if ( mem0.msMem.next > mem0.msMem.max ) mem0.msMem.max = mem0.msMem.next; } //Array.Resize( ref mem0.aMem, (int)(mem0.hw_Mem * 1.5 + 1 )); //mem0.aMem[mem0.hw_Mem] = pPrior; //mem0.hw_Mem = mem0.aMem.Length; pPrior = null; return; } static void sqlite3MemFreeBtCursor( ref BtCursor pPrior ) { if ( pPrior == null ) return; #if FALSE && DEBUG for ( int i = mem0.msBtCursor.next - 1; i >= 0; i-- ) if ( mem0.aBtCursor[i] != null && mem0.aBtCursor[i] == pPrior ) Debugger.Break(); #endif mem0.msBtCursor.dealloc++; if ( mem0.msBtCursor.next < mem0.aBtCursor.Length - 1 ) { mem0.aBtCursor[++mem0.msBtCursor.next] = pPrior; if ( mem0.msBtCursor.next > mem0.msBtCursor.max ) mem0.msBtCursor.max = mem0.msBtCursor.next; } //Array.Resize( ref mem0.aBtCursor, (int)(mem0.hw_BtCursor * 1.5 + 1 )); //mem0.aBtCursor[mem0.hw_BtCursor] = pPrior; //mem0.hw_BtCursor = mem0.aBtCursor.Length; pPrior = null; return; } /* ** Like realloc(). Resize an allocation previously obtained from ** sqlite3MemMalloc(). ** ** For this low-level interface, we know that pPrior!=0. Cases where ** pPrior==0 while have been intercepted by higher-level routine and ** redirected to xMalloc. Similarly, we know that nByte>0 becauses ** cases where nByte<=0 will have been intercepted by higher-level ** routines and redirected to xFree. */ static byte[] sqlite3MemRealloc( ref byte[] pPrior, int nByte ) { // sqlite3_int64 p = (sqlite3_int64*)pPrior; // Debug.Assert(pPrior!=0 && nByte>0 ); // nByte = ROUND8( nByte ); // p = (sqlite3_int64*)pPrior; // p--; // p = realloc(p, nByte+8 ); // if( p ){ // p[0] = nByte; // p++; // } // return (void*)p; Array.Resize( ref pPrior, nByte ); return pPrior; } #else /* ** No-op versions of all memory allocation routines */ static byte[] sqlite3MemMalloc(int nByte) { return new byte[nByte]; } static int[] sqlite3MemMallocInt(int nInt) { return new int[nInt]; } static Mem sqlite3MemMallocMem(Mem pMem) { return new Mem(); } static void sqlite3MemFree(ref byte[] pPrior) { pPrior = null; } static void sqlite3MemFreeInt(ref int[] pPrior) { pPrior = null; } static void sqlite3MemFreeMem(ref Mem pPrior) { pPrior = null; } static int sqlite3MemInit() { return SQLITE_OK; } static void sqlite3MemShutdown() { } static BtCursor sqlite3MemMallocBtCursor(BtCursor dummy) { return new BtCursor(); } static void sqlite3MemFreeBtCursor(ref BtCursor pPrior) { pPrior = null; } #endif static byte[] sqlite3MemRealloc(byte[] pPrior, int nByte) { Array.Resize(ref pPrior, nByte); return pPrior; } /* ** Report the allocated size of a prior return from xMalloc() ** or xRealloc(). */ static int sqlite3MemSize(byte[] pPrior) { // sqlite3_int64 p; // if( pPrior==0 ) return 0; // p = (sqlite3_int64*)pPrior; // p--; // return p[0]; return pPrior == null ? 0 : (int)pPrior.Length; } /* ** Round up a request size to the next valid allocation size. */ static int sqlite3MemRoundup(int n) { return n;// ROUND8( n ); } /* ** Initialize this module. */ static int sqlite3MemInit(object NotUsed) { UNUSED_PARAMETER(NotUsed); if (!sqlite3GlobalConfig.bMemstat) { /* If memory status is enabled, then the malloc.c wrapper will already ** hold the STATIC_MEM mutex when the routines here are invoked. */ mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } return SQLITE_OK; } /* ** Deinitialize this module. */ static void sqlite3MemShutdown(object NotUsed) { UNUSED_PARAMETER(NotUsed); return; } /* ** This routine is the only routine in this file with external linkage. ** ** Populate the low-level memory allocation function pointers in ** sqlite3GlobalConfig.m with pointers to the routines in this file. */ static void sqlite3MemSetDefault() { sqlite3_mem_methods defaultMethods = new sqlite3_mem_methods( sqlite3MemMalloc, sqlite3MemMallocInt, sqlite3MemMallocMem, sqlite3MemFree, sqlite3MemFreeInt, sqlite3MemFreeMem, sqlite3MemRealloc, sqlite3MemSize, sqlite3MemRoundup, (dxMemInit)sqlite3MemInit, (dxMemShutdown)sqlite3MemShutdown, 0 ); sqlite3_config(SQLITE_CONFIG_MALLOC, defaultMethods); } static void sqlite3DbFree(sqlite3 db, ref int[] pPrior) { if (pPrior != null) sqlite3MemFreeInt(ref pPrior); } static void sqlite3DbFree(sqlite3 db, ref Mem pPrior) { if (pPrior != null) sqlite3MemFreeMem(ref pPrior); } static void sqlite3DbFree(sqlite3 db, ref Mem[] pPrior) { if (pPrior != null) for (int i = 0; i < pPrior.Length; i++) sqlite3MemFreeMem(ref pPrior[i]); } static void sqlite3DbFree<T>(sqlite3 db, ref T pT) where T : class { } static void sqlite3DbFree(sqlite3 db, ref string pString) { } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using Microsoft.Reactive.Testing; using Avalonia.Data; using Avalonia.Markup.Data; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Markup.UnitTests.Data { public class ExpressionObserverTests_Property { [Fact] public async void Should_Get_Simple_Property_Value() { var data = new { Foo = "foo" }; var target = new ExpressionObserver(data, "Foo"); var result = await target.Take(1); Assert.Equal("foo", result); } [Fact] public void Should_Get_Simple_Property_Value_Type() { var data = new { Foo = "foo" }; var target = new ExpressionObserver(data, "Foo"); Assert.Equal(typeof(string), target.ResultType); } [Fact] public async void Should_Get_Simple_Property_Value_Null() { var data = new { Foo = (string)null }; var target = new ExpressionObserver(data, "Foo"); var result = await target.Take(1); Assert.Null(result); } [Fact] public async void Should_Get_Simple_Property_From_Base_Class() { var data = new Class3 { Foo = "foo" }; var target = new ExpressionObserver(data, "Foo"); var result = await target.Take(1); Assert.Equal("foo", result); } [Fact] public async void Should_Get_Simple_Property_Chain() { var data = new { Foo = new { Bar = new { Baz = "baz" } } }; var target = new ExpressionObserver(data, "Foo.Bar.Baz"); var result = await target.Take(1); Assert.Equal("baz", result); } [Fact] public void Should_Get_Simple_Property_Chain_Type() { var data = new { Foo = new { Bar = new { Baz = "baz" } } }; var target = new ExpressionObserver(data, "Foo.Bar.Baz"); Assert.Equal(typeof(string), target.ResultType); } [Fact] public async void Should_Return_BindingError_For_Broken_Chain() { var data = new { Foo = new { Bar = 1 } }; var target = new ExpressionObserver(data, "Foo.Bar.Baz"); var result = await target.Take(1); Assert.IsType<BindingError>(result); var error = result as BindingError; Assert.IsType<MissingMemberException>(error.Exception); Assert.Equal("Could not find CLR property 'Baz' on '1'", error.Exception.Message); } [Fact] public void Should_Have_Null_ResultType_For_Broken_Chain() { var data = new { Foo = new { Bar = 1 } }; var target = new ExpressionObserver(data, "Foo.Bar.Baz"); Assert.Null(target.ResultType); } [Fact] public void Should_Track_Simple_Property_Value() { var data = new Class1 { Foo = "foo" }; var target = new ExpressionObserver(data, "Foo"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); data.Foo = "bar"; Assert.Equal(new[] { "foo", "bar" }, result); sub.Dispose(); Assert.Equal(0, data.SubscriptionCount); } [Fact] public void Should_Trigger_PropertyChanged_On_Null_Or_Empty_String() { var data = new Class1 { Bar = "foo" }; var target = new ExpressionObserver(data, "Bar"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); Assert.Equal(new[] { "foo" }, result); data.Bar = "bar"; Assert.Equal(new[] { "foo" }, result); data.RaisePropertyChanged(string.Empty); Assert.Equal(new[] { "foo", "bar" }, result); data.RaisePropertyChanged(null); Assert.Equal(new[] { "foo", "bar", "bar" }, result); sub.Dispose(); Assert.Equal(0, data.SubscriptionCount); } [Fact] public void Should_Track_End_Of_Property_Chain_Changing() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = new ExpressionObserver(data, "Next.Bar"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); ((Class2)data.Next).Bar = "baz"; Assert.Equal(new[] { "bar", "baz" }, result); sub.Dispose(); Assert.Equal(0, data.SubscriptionCount); Assert.Equal(0, data.Next.SubscriptionCount); } [Fact] public void Should_Track_Property_Chain_Changing() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = new ExpressionObserver(data, "Next.Bar"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); var old = data.Next; data.Next = new Class2 { Bar = "baz" }; Assert.Equal(new[] { "bar", "baz" }, result); sub.Dispose(); Assert.Equal(0, data.SubscriptionCount); Assert.Equal(0, data.Next.SubscriptionCount); Assert.Equal(0, old.SubscriptionCount); } [Fact] public void Should_Track_Property_Chain_Breaking_With_Null_Then_Mending() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = new ExpressionObserver(data, "Next.Bar"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); var old = data.Next; data.Next = null; data.Next = new Class2 { Bar = "baz" }; Assert.Equal(new[] { "bar", AvaloniaProperty.UnsetValue, "baz" }, result); sub.Dispose(); Assert.Equal(0, data.SubscriptionCount); Assert.Equal(0, data.Next.SubscriptionCount); Assert.Equal(0, old.SubscriptionCount); } [Fact] public void Should_Track_Property_Chain_Breaking_With_Object_Then_Mending() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = new ExpressionObserver(data, "Next.Bar"); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); var old = data.Next; var breaking = new WithoutBar(); data.Next = breaking; data.Next = new Class2 { Bar = "baz" }; Assert.Equal(3, result.Count); Assert.Equal("bar", result[0]); Assert.IsType<BindingError>(result[1]); Assert.Equal("baz", result[2]); sub.Dispose(); Assert.Equal(0, data.SubscriptionCount); Assert.Equal(0, data.Next.SubscriptionCount); Assert.Equal(0, breaking.SubscriptionCount); Assert.Equal(0, old.SubscriptionCount); } [Fact] public void Empty_Expression_Should_Track_Root() { var data = new Class1 { Foo = "foo" }; var update = new Subject<Unit>(); var target = new ExpressionObserver(() => data.Foo, "", update); var result = new List<object>(); target.Subscribe(x => result.Add(x)); data.Foo = "bar"; update.OnNext(Unit.Default); Assert.Equal(new[] { "foo", "bar" }, result); } [Fact] public void Should_Track_Property_Value_From_Observable_Root() { var scheduler = new TestScheduler(); var source = scheduler.CreateColdObservable( OnNext(1, new Class1 { Foo = "foo" }), OnNext(2, new Class1 { Foo = "bar" })); var target = new ExpressionObserver(source, "Foo"); var result = new List<object>(); using (target.Subscribe(x => result.Add(x))) { scheduler.Start(); } Assert.Equal(new[] { AvaloniaProperty.UnsetValue, "foo", "bar" }, result); Assert.All(source.Subscriptions, x => Assert.NotEqual(Subscription.Infinite, x.Unsubscribe)); } [Fact] public void SetValue_Should_Set_Simple_Property_Value() { var data = new Class1 { Foo = "foo" }; var target = new ExpressionObserver(data, "Foo"); Assert.True(target.SetValue("bar")); Assert.Equal("bar", data.Foo); } [Fact] public void SetValue_Should_Set_Property_At_The_End_Of_Chain() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = new ExpressionObserver(data, "Next.Bar"); Assert.True(target.SetValue("baz")); Assert.Equal("baz", ((Class2)data.Next).Bar); } [Fact] public void SetValue_Should_Return_False_For_Missing_Property() { var data = new Class1 { Next = new WithoutBar()}; var target = new ExpressionObserver(data, "Next.Bar"); Assert.False(target.SetValue("baz")); } [Fact] public void SetValue_Should_Return_False_For_Missing_Object() { var data = new Class1(); var target = new ExpressionObserver(data, "Next.Bar"); Assert.False(target.SetValue("baz")); } [Fact] public async void Should_Handle_Null_Root() { var target = new ExpressionObserver((object)null, "Foo"); var result = await target.Take(1); Assert.Equal(AvaloniaProperty.UnsetValue, result); } [Fact] public void Can_Replace_Root() { var first = new Class1 { Foo = "foo" }; var second = new Class1 { Foo = "bar" }; var root = first; var update = new Subject<Unit>(); var target = new ExpressionObserver(() => root, "Foo", update); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); root = second; update.OnNext(Unit.Default); root = null; update.OnNext(Unit.Default); Assert.Equal(new[] { "foo", "bar", AvaloniaProperty.UnsetValue }, result); Assert.Equal(0, first.SubscriptionCount); Assert.Equal(0, second.SubscriptionCount); } [Fact] public void Should_Not_Keep_Source_Alive() { Func<Tuple<ExpressionObserver, WeakReference>> run = () => { var source = new Class1 { Foo = "foo" }; var target = new ExpressionObserver(source, "Foo"); return Tuple.Create(target, new WeakReference(source)); }; var result = run(); result.Item1.Subscribe(x => { }); GC.Collect(); Assert.Null(result.Item2.Target); } private interface INext { int SubscriptionCount { get; } } private class Class1 : NotifyingBase { private string _foo; private INext _next; public string Foo { get { return _foo; } set { _foo = value; RaisePropertyChanged(nameof(Foo)); } } private string _bar; public string Bar { get { return _bar; } set { _bar = value; } } public INext Next { get { return _next; } set { _next = value; RaisePropertyChanged(nameof(Next)); } } } private class Class2 : NotifyingBase, INext { private string _bar; public string Bar { get { return _bar; } set { _bar = value; RaisePropertyChanged(nameof(Bar)); } } } private class Class3 : Class1 { } private class WithoutBar : NotifyingBase, INext { } private Recorded<Notification<object>> OnNext(long time, object value) { return new Recorded<Notification<object>>(time, Notification.CreateOnNext<object>(value)); } } }
#define PROTOTYPE using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using ProBuilder2.Common; using ProBuilder2.MeshOperations; namespace ProBuilder2.Examples { [RequireComponent(typeof(AudioSource))] public class IcoBumpin : MonoBehaviour { pb_Object ico; // A reference to the icosphere pb_Object component Mesh icoMesh; // A reference to the icosphere mesh (cached because we access the vertex array every frame) Transform icoTransform; // A reference to the icosphere transform component. Cached because I can't remember if GameObject.transform is still a performance drain :| AudioSource audioSource;// Cached reference to the audiosource. /** * Holds a pb_Face, the normal of that face, and the index of every vertex that touches it (sharedIndices). */ struct FaceRef { public pb_Face face; public Vector3 nrm; // face normal public int[] indices; // all vertex indices (including shared connected vertices) public FaceRef(pb_Face f, Vector3 n, int[] i) { face = f; nrm = n; indices = i; } } // All faces that have been extruded FaceRef[] outsides; // Keep a copy of the original vertex array to calculate the distance from origin. Vector3[] original_vertices, displaced_vertices; // The radius of the mesh icosphere on instantiation. [Range(1f, 10f)] public float icoRadius = 2f; // The number of subdivisions to give the icosphere. [Range(0, 3)] public int icoSubdivisions = 2; // How far along the normal should each face be extruded when at idle (no audio input). [Range(0f, 1f)] public float startingExtrusion = .1f; // The material to apply to the icosphere. public Material material; // The max distance a frequency range will extrude a face. [Range(1f, 50f)] public float extrusion = 30f; // An FFT returns a spectrum including frequencies that are out of human hearing range - // this restricts the number of bins used from the spectrum to the lower @fftBounds. [Range(8, 128)] public int fftBounds = 32; // How high the icosphere transform will bounce (sample volume determines height). [Range(0f, 10f)] public float verticalBounce = 4f; // Optionally weights the frequency amplitude when calculating extrude distance. public AnimationCurve frequencyCurve; // A reference to the line renderer that will be used to render the raw waveform. public LineRenderer waveform; // The y size of the waveform. public float waveformHeight = 2f; // How far from the icosphere should the waveform be. public float waveformRadius = 20f; // If @rotateWaveformRing is true, this is the speed it will travel. public float waveformSpeed = .1f; // If true, the waveform ring will randomly orbit the icosphere. public bool rotateWaveformRing = false; // If true, the waveform will bounce up and down with the icosphere. public bool bounceWaveform = false; public GameObject missingClipWarning; // Icosphere's starting position. Vector3 icoPosition = Vector3.zero; float faces_length; const float TWOPI = 6.283185f; // 2 * PI const int WAVEFORM_SAMPLES = 1024; // How many samples make up the waveform ring. const int FFT_SAMPLES = 4096; // How many samples are used in the FFT. More means higher resolution. // Keep copy of the last frame's sample data to average with the current when calculating // deformation amounts. Smoothes the visual effect. float[] fft = new float[FFT_SAMPLES], fft_history = new float[FFT_SAMPLES], data = new float[WAVEFORM_SAMPLES], data_history = new float[WAVEFORM_SAMPLES]; // Root mean square of raw data (volume, but not in dB). float rms = 0f, rms_history = 0f; /** * Creates the icosphere, and loads all the cache information. */ void Start() { audioSource = GetComponent<AudioSource>(); if( audioSource.clip == null ) missingClipWarning.SetActive(true); // Create a new icosphere. ico = pb_ShapeGenerator.IcosahedronGenerator(icoRadius, icoSubdivisions); // Shell is all the faces on the new icosphere. pb_Face[] shell = ico.faces; // Materials are set per-face on pb_Object meshes. pb_Objects will automatically // condense the mesh to the smallest set of subMeshes possible based on materials. #if !PROTOTYPE foreach(pb_Face f in shell) f.SetMaterial( material ); #else ico.gameObject.GetComponent<MeshRenderer>().sharedMaterial = material; #endif pb_Face[] connectingFaces; // Extrude all faces on the icosphere by a small amount. The third boolean parameter // specifies that extrusion should treat each face as an individual, not try to group // all faces together. ico.Extrude(shell, startingExtrusion, false, out connectingFaces); // ToMesh builds the mesh positions, submesh, and triangle arrays. Call after adding // or deleting vertices, or changing face properties. ico.ToMesh(); // Refresh builds the normals, tangents, and UVs. ico.Refresh(); outsides = new FaceRef[shell.Length]; Dictionary<int, int> lookup = ico.sharedIndices.ToDictionary(); // Populate the outsides[] cache. This is a reference to the tops of each extruded column, including // copies of the sharedIndices. for(int i = 0; i < shell.Length; ++i) outsides[i] = new FaceRef( shell[i], pb_Math.Normal(ico, shell[i]), ico.sharedIndices.AllIndicesWithValues(lookup, shell[i].distinctIndices).ToArray() ); // Store copy of positions array un-modified original_vertices = new Vector3[ico.vertices.Length]; System.Array.Copy(ico.vertices, original_vertices, ico.vertices.Length); // displaced_vertices should mirror icosphere mesh vertices. displaced_vertices = ico.vertices; icoMesh = ico.msh; icoTransform = ico.transform; faces_length = (float)outsides.Length; // Build the waveform ring. icoPosition = icoTransform.position; waveform.SetVertexCount(WAVEFORM_SAMPLES); if( bounceWaveform ) waveform.transform.parent = icoTransform; audioSource.Play(); } void Update() { // fetch the fft spectrum audioSource.GetSpectrumData(fft, 0, FFTWindow.BlackmanHarris); // get raw data for waveform audioSource.GetOutputData(data, 0); // calculate root mean square (volume) rms = RMS(data); /** * For each face, translate the vertices some distance depending on the frequency range assigned. * Not using the TranslateVertices() pb_Object extension method because as a convenience, that method * gathers the sharedIndices per-face on every call, which while not tremondously expensive in most * contexts, is far too slow for use when dealing with audio, and especially so when the mesh is * somewhat large. */ for(int i = 0; i < outsides.Length; i++) { float normalizedIndex = (i/faces_length); int n = (int)(normalizedIndex*fftBounds); Vector3 displacement = outsides[i].nrm * ( ((fft[n]+fft_history[n]) * .5f) * (frequencyCurve.Evaluate(normalizedIndex) * .5f + .5f)) * extrusion; foreach(int t in outsides[i].indices) { displaced_vertices[t] = original_vertices[t] + displacement; } } Vector3 vec = Vector3.zero; // Waveform ring for(int i = 0; i < WAVEFORM_SAMPLES; i++) { int n = i < WAVEFORM_SAMPLES-1 ? i : 0; vec.x = Mathf.Cos((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight)); vec.z = Mathf.Sin((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight)); vec.y = 0f; waveform.SetPosition(i, vec); } // Ring rotation if( rotateWaveformRing ) { Vector3 rot = waveform.transform.localRotation.eulerAngles; rot.x = Mathf.PerlinNoise(Time.time * waveformSpeed, 0f) * 360f; rot.y = Mathf.PerlinNoise(0f, Time.time * waveformSpeed) * 360f; waveform.transform.localRotation = Quaternion.Euler(rot); } icoPosition.y = -verticalBounce + ((rms + rms_history) * verticalBounce); icoTransform.position = icoPosition; // Keep copy of last FFT samples so we can average with the current. Smoothes the movement. System.Array.Copy(fft, fft_history, FFT_SAMPLES); System.Array.Copy(data, data_history, WAVEFORM_SAMPLES); rms_history = rms; icoMesh.vertices = displaced_vertices; } /** * Root mean square is a good approximation of perceived loudness. */ float RMS(float[] arr) { float v = 0f, len = (float)arr.Length; for(int i = 0; i < len; i++) v += Mathf.Abs(arr[i]); return Mathf.Sqrt(v / (float)len); } } }
/* Ben Scott * [email protected] * 2015-11-11 * YAML */ using System.IO; // Well, here we are! The other main file! using System.Collections.Generic; using System.Text.RegularExpressions; using Buffer=System.Text.StringBuilder; using DateTime=System.DateTime; using Type=System.Type; using YamlDotNet.Serialization; using UnityEngine; using adv=PathwaysEngine.Adventure; using map=PathwaysEngine.Adventure.Setting; using inv=PathwaysEngine.Inventory; using lit=PathwaysEngine.Literature; using puzl=PathwaysEngine.Puzzle; using stat=PathwaysEngine.Statistics; using util=PathwaysEngine.Utilities; /** `YAML` * * These classes act as adapters for the `MonoBehaviour`- * derived classes, which `YamlDotNet` cannot instantiate. * Instances of these classes are instantiated instead, and * then populate the main classes in `Awake()`. **/ namespace PathwaysEngine { /** `YAML` * * These classes act as adapters for the `MonoBehaviour`- * derived classes, which `YamlDotNet` cannot instantiate. * Instances of these classes are instantiated instead, and * then populate the main classes on `Awake()`. **/ public static partial class Pathways { public static Dictionary<string,object> data = new Dictionary<string,object>(); public static Dictionary<Type,object> defaults = new Dictionary<Type,object>(); public static Dictionary<string,lit::Command> commands = new Dictionary<string,lit::Command>(); public static Dictionary<string,lit::Message> messages = new Dictionary<string,lit::Message>(); /** `Deserialize<T,U>()` : **`function`** * * Deserialize loads data, serialized from `yml`, into * an instance of `Thing`. Should probably make use of * type contravariance, but hey, what can you do? * * - `<T>` : **`Type`** * real type, usually derives from `Monobehaviour` * * - `<U>` : **`Type`** * nested type, usually named `yml` * * - `o` : **`<T>`** * object of type `T` to look for **/ public static void Deserialize<T,U>(T o) where T : IStorable where U : ISerializable<T> { Pathways.yml.Deserialize<U>(o.Name).Deserialize(o); } /** `yml` : **`class`** * * Nested class that deals with serializing & * deserializing data from `*.yml` files. **/ public static class yml { static Deserializer deserializer = new Deserializer(); /** `yml` : **`constructor`** * * Instantiates a `Deserializer`, registers tags, & * reads data from the specified files. While the * usage of `static`s *and* `constructor`s aren't * kosher in `Unity`, but in this case, it's ok, as * this has nothing to do with the `MonoBehaviour` * loading / instantiation process. **/ static yml() { string pre = "tag:yaml.org,2002:", ext = ".yml", dir = #if UNITY_EDITOR Directory.GetCurrentDirectory() +"/Assets/PathwaysEngine/Resources/"; #else Application.dataPath+"/Resources/"; #endif // mapping of all the tags to their types var tags = new Dictionary<string,Type> { { "regex", typeof(Regex) }, { "date", typeof(DateTime) }, // PathwaysEngine { "config", typeof(Pathways.Settings) }, // Adventure { "thing", typeof(adv::Thing_yml) }, { "creature", typeof(adv::Creature_yml) }, { "person", typeof(adv::Person_yml) }, { "player", typeof(Player_yml) }, // Setting { "area", typeof(map::Area_yml) }, { "room", typeof(map::Room_yml) }, { "door", typeof(map::Door_yml) }, // Literature //{ "parse", typeof(lit::Parse) }, { "message", typeof(lit::Message) }, { "encounter", typeof(lit::Encounter_yml) }, // Inventory { "item", typeof(inv::Item_yml) }, { "lamp", typeof(inv::Lamp_yml) }, { "items", typeof(inv::ItemSet) }, { "book", typeof(inv::Book_yml) }, //{ "bag", typeof(inv::Bag_yml) }, //{ "backpack", typeof(inv::Backpack_yml) }, { "key", typeof(inv::Key_yml) }, { "crystal", typeof(inv::Crystal_yml) }, { "weapon", typeof(inv::Weapon_yml) }, //{ "gun", typeof(inv::Gun_yml) }, // Puzzle //{ "piece", typeof(puzl::Piece.yml) }, { "button", typeof(puzl::Button_yml) }, { "lever", typeof(puzl::Lever_yml) }}; foreach (var tag in tags) deserializer.RegisterTagMapping( pre+tag.Key, tag.Value); deserializer.RegisterTypeConverter( new RegexYamlConverter()); var files = new[] { // special files "commands", // list of commands "defaults", // default data "pathways", // system messages "settings"}; // project settings foreach (var file in files) { var r = GetReader(Path.Combine(dir,file)+ext); switch (file) { case "commands" : foreach (var kvp in deserializer.Deserialize<Dictionary<string,lit::Command_yml>>(r)) Pathways.commands[kvp.Key] = kvp.Value.Deserialize(kvp.Key); break; case "defaults" : foreach (var elem in deserializer.Deserialize<Dictionary<string,Dictionary<string,object>>>(r)) foreach (var kvp in elem.Value) Pathways.defaults[GetTypeYAML(elem.Key,kvp.Key)] = kvp.Value; break; case "pathways" : foreach (var kvp in deserializer.Deserialize<Dictionary<string,lit::Message>>(r)) Pathways.messages[kvp.Key] = kvp.Value; break; case "settings" : Pathways.Config = deserializer.Deserialize<Settings>(r); break; } } foreach (var elem in Directory.GetFiles(dir,'*'+ext)) { foreach (var file in files) if (elem.Contains(file)) continue; Deserialize(elem); } } /** `GetReader()` : **`StringReader`** * * Gets the `*.yml` file in the main directory only * if it exists and has the proper extension. * * - `throw` : **`Exception`** * if the file does not exist **/ static StringReader GetReader(string file) { if (!File.Exists(file)) throw new System.Exception( $"YAML 404: {file}"); var buffer = new Buffer(); foreach (var line in File.ReadAllLines(file)) buffer.AppendLine(line); return new StringReader(buffer.ToString()); } /** `GetTypeYAML()` : **`Type`** * * Tries to find a `Type` in `PathwaysEngine` which * is a match for the supplied `string`. * * - `ns` : **`string`** * `string`ified namespace to look in * * - `s` : **`string`** * `string`ified name of a `Type` to look for **/ public static Type GetTypeYAML(string ns, string s) => Type.GetType($"PathwaysEngine.{ns}.{s}_yml"); /** `Deserialize()` : **`function`** * * Called without type arguments, this will simply * deserialize into the `data` object. This is used * only by the `static` constructor to get data out * of the rest of the files (skipping the few files * which are specified above). * * - `file` : **`string`** * filename to look for * * - `throw` : **`IOException`** **/ static void Deserialize(string file) { foreach (var kvp in deserializer.Deserialize<Dictionary<string,object>>(GetReader(file))) data[kvp.Key] = kvp.Value; } /** `Deserialize<T>()` : **`<T>`** * * Returns an object of type `<T>` from the * dictionary if it exists. * * - `<T>` : **`Type`** * type to look for, and then to cast to, when * deserializing the data from the file. * * - `s` : **`string`** * key to look for * * - `throw` : **`Exception`** * There is no key at `data[s]`, or some other * problem occurs when attempting to cast the * object to `<T>`. **/ public static T Deserialize<T>(string s) { object o; if (!data.TryGetValue(s,out o)) o = DeserializeDefault<T>(); if (!(o is T)) throw new System.Exception( $"Bad cast: {typeof(T)} as {s}"); return ((T) o); } /** `DeserializeDefault<T>()` : **`<T>`** * * Returns the default object of type `<T>`. **/ public static T DeserializeDefault<T>() { object o; if (!defaults.TryGetValue(typeof(T),out o)) throw new System.Exception( $"Type {typeof (T)} not found in defaults"); return ((T) o); } public static object DeserializeDefault(Type type) { object o; if (!defaults.TryGetValue(type,out o)) throw new System.Exception( $"{type} not found."); return o; } } /** `Settings` : **`class`** * * Simple storage class for project-wide data. **/ public class Settings { [YamlMember(Alias="title")] public string Title {get;set;} [YamlMember(Alias="date")] public string Date {get;set;} [YamlMember(Alias="version")] public string Version {get;set;} [YamlMember(Alias="author")] public string Author {get;set;} [YamlMember(Alias="email")] public string Email {get;set;} [YamlMember(Alias="link")] public string Link {get;set;} } } /** `IStorable` : **`interface`** * * Interface for anything that needs to be serialized * from the `yml` dictionary. **/ public interface IStorable { /** `Name` : **`string`** * * This should be an unique identifier that the `*.yml` * `Deserializer` should look for in files. **/ string Name { get; } } /** `ISerializeable<T>` : **`interface`** * * Typically implemented by nested classes named `yml`, the * main function of this interface is to ensure that there * is a method called `Deserialize` which gets the correct * class to deserialize to at startup. * * - `<T>` : **`type`** * the type of object to deserialize to, usually just * the class that this is nested in. **/ public interface ISerializable<T> where T : IStorable { void Deserialize(T o); } class Player_yml : adv::Person_yml, ISerializable<Player> { public List<string> deathMessages {get;set;} public void Deserialize(Player o) { Deserialize((adv::Person) o); o.deathMessages = new RandList<string>(); o.deathMessages.AddRange(this.deathMessages); } } namespace Adventure { public class Thing_yml : ISerializable<Thing> { public bool seen {get;set;} public string Name {get;set;} public lit::Description description {get;set;} public void ApplyDefaults(Thing o) { var d = Pathways.yml.DeserializeDefault<Thing_yml>(); o.Seen = d.seen; o.description = d.description; } public void Deserialize(Thing o) { ApplyDefaults(o); o.Seen = this.seen; o.description.Name = o.Name; o.description = lit::Description.Merge( this.description, o.description); } } public class Creature_yml : Thing_yml, ISerializable<Creature> { [YamlMember(Alias="dead")] public bool isDead {get;set;} public void Deserialize(Creature o) { Deserialize((Thing) o); o.IsDead = isDead; } } public class Person_yml : Creature_yml, ISerializable<Person> { public map::Area area {get;set;} public map::Room room {get;set;} public void Deserialize(Person o) { Deserialize((Creature) o); o.Area = this.area; o.Room = this.room; } } namespace Setting { public class Room_yml : Thing_yml, ISerializable<Room> { public int depth {get;set;} public List<Room> nearbyRooms {get;set;} public void ApplyDefaults(Room o) { ApplyDefaults((Thing) o); var d = Pathways.yml.DeserializeDefault<Room_yml>(); o.description = lit::Description.Onto( o.description, d.description); } public void Deserialize(Room o) { ApplyDefaults(o); Deserialize((Thing) o); o.description = lit::Description.Merge( this.description, o.description); //o.nearbyRooms = this.nearbyRooms; } } public class Area_yml : Thing_yml, ISerializable<Area> { public bool safe {get;set;} public int level {get;set;} public List<Room_yml> rooms {get;set;} public List<Area_yml> areas {get;set;} public void Deserialize(Area o) { ApplyDefaults(o); Deserialize((Thing) o); o.safe = this.safe; o.level = this.level; //o.rooms = this.rooms; //o.areas = this.areas; } } public class Door_yml : Thing_yml, ISerializable<Door> { [YamlMember(Alias="opened")] public bool IsOpen {get;set;} [YamlMember(Alias="initially opened")] public bool IsInitOpen {get;set;} [YamlMember(Alias="locked")] public bool IsLocked {get;set;} [YamlMember(Alias="lock message")] public string LockMessage {get;set;} public void ApplyDefaults(Door o) { ApplyDefaults((Thing) o); var d = Pathways.yml.DeserializeDefault<Door_yml>(); o.IsOpen = d.IsOpen; o.IsInitOpen = d.IsInitOpen; o.IsLocked = d.IsLocked; o.LockMessage = d.LockMessage; } public void Deserialize(Door o) { Deserialize((Thing) o); ApplyDefaults(o); o.IsOpen = this.IsOpen; o.IsLocked = this.IsLocked; o.IsInitOpen = this.IsInitOpen; o.LockMessage = this.LockMessage; } } } } namespace Inventory { class Item_yml : adv::Thing_yml, ISerializable<Item> { public int cost {get;set;} public float mass {get;set;} public void Deserialize(Item o) { Deserialize((adv::Thing) o); o.Mass = this.mass; o.Cost = this.cost; } } class Bag_yml : Item_yml, ISerializable<Bag> { public void Deserialize(Bag o) { Deserialize((Item) o); } } class Backpack_yml : Item_yml, ISerializable<Backpack> { public void Deserialize(Backpack o) { Deserialize((Bag) o); } } class Lamp_yml : Item_yml, ISerializable<Lamp> { public float time {get;set;} public void Deserialize(Lamp o) { Deserialize((Item) o); o.time = time; } } class Key_yml : Item_yml, ISerializable<Key> { [YamlMember(Alias="key type")] public Keys Kind {get;set;} [YamlMember(Alias="lock number")] public int Value {get;set;} public void Deserialize(Key o) { Deserialize((Item) o); o.Kind = this.Kind; o.Value = this.Value; } } class Book_yml : Item_yml, ISerializable<Book> { public string passage {get;set;} public void ApplyDefaults(Book o) { ApplyDefaults((Item) o); var d = Pathways.yml.DeserializeDefault<Book_yml>(); o.description = lit::Description.Merge( o.description, d.description); } public void Deserialize(Book o) { ApplyDefaults(o); Deserialize((adv::Thing) o); o.Passage = this.passage; } } class Crystal_yml : Item_yml, ISerializable<Crystal> { public uint shards {get;set;} public void Deserialize(Crystal o) { Deserialize((Item) o); o.Shards = this.shards; } } class Weapon_yml : Item_yml, ISerializable<Weapon> { public float rate {get;set;} public void Deserialize(Weapon o) { Deserialize((Item) o); o.rate = rate; } } } namespace Literature { public class Command_yml : IStorable { public string Name {get;set;} public Regex regex {get;set;} public Handlers parse {get;set;} /** `Handlers` : **`enum`** * * This local `enum` defines the `Parse` delegates * that the `Parser` should call for each verb and * command entered. This is awful. * * - `Sudo` : **`Handlers`** * `Pathways.Sudo` overrides commands * * - `Quit` : **`Handlers`** * `Pathways.Quit` begins the quitting routine * * - `Redo` : **`Handlers`** * `Pathways.Redo` repeats the last command * * - `Save` : **`Handlers`** * `Pathways.Save` saves the game * * - `Load` : **`Handlers`** * `Pathways.Load` loads from a `*.yml` file * * - `Help` : **`Handlers`** * `Pathways.Help` displays a simple help text * * - `View` : **`Handlers`** * `Player.View` examines some object * * - `Look` : **`Handlers`** * `Player.Look` looks around/examines a room * * - `Goto` : **`Handlers`** * `Player.Goto` sends the `Player` somewhere * * - `Move` : **`Handlers`** * `Player.Goto` can be called to move objects * * - `Invt` : **`Handlers`** * `Player.Invt` opens the inventory menu * * - `Take` : **`Handlers`** * `Player.Take` takes an item * * - `Drop` : **`Handlers`** * `Player.Drop` drops an item * * - `Wear` : **`Handlers`** * `Player.Wear` has the player wear something * * - `Stow` : **`Handlers`** * `Player.Stow` has the player stow something * * - `Read` : **`Handlers`** * `Player.Read` reads an `IReadable` thing * * - `Open` : **`Handlers`** * `Player.Open` opens something * * - `Shut` : **`Handlers`** * `Player.Shut` closes something * * - `Push` : **`Handlers`** * `Player.Push` pushes something * * - `Pull` : **`Handlers`** * `Player.Pull` pulls something **/ public enum Handlers { Sudo, Quit, Redo, Save, Load, Help, View, Look, Goto, Move, Invt, Take, Drop, Wear, Stow, Read, Open, Shut, Push, Pull, Show, Hide, Use } public Command Deserialize(string s) { this.Name = s; return new Command( this.Name, this.regex, SelectParse(this.parse)); } public void Deserialize(Command o) { o = new Command( this.Name, this.regex, SelectParse(this.parse)); } Parse SelectParse(Handlers e) { switch (e) { case Handlers.Sudo : return Handler.Sudo; case Handlers.Quit : return Handler.Quit; case Handlers.Redo : return Handler.Redo; case Handlers.Save : return Handler.Save; case Handlers.Load : return Handler.Load; case Handlers.Help : return Handler.Help; case Handlers.View : return Handler.View; case Handlers.Look : return Handler.Look; case Handlers.Goto : return Handler.Goto; case Handlers.Move : return Handler.Move; case Handlers.Invt : return Handler.Invt; case Handlers.Take : return Handler.Take; case Handlers.Drop : return Handler.Drop; case Handlers.Use : return Handler.Use; case Handlers.Wear : return Handler.Wear; case Handlers.Stow : return Handler.Stow; case Handlers.Read : return Handler.Read; case Handlers.Open : return Handler.Open; case Handlers.Shut : return Handler.Shut; case Handlers.Push : return Handler.Push; case Handlers.Pull : return Handler.Pull; case Handlers.Show : return Handler.Show; case Handlers.Hide : return Handler.Hide; default : return null; } } } public class Encounter_yml : adv::Thing_yml, ISerializable<Encounter> { public bool reuse {get;set;} public float time {get;set;} public Inputs input {get;set;} public void Deserialize(Encounter o) { base.Deserialize((adv::Thing) o); o.reuse = this.reuse; o.time = this.time; o.input = this.input; } } } namespace Puzzle { public class Piece_yml<T> : adv::Thing_yml, ISerializable<Piece<T>> { public T condition {get;set;} public T solution {get;set;} public void Deserialize(Piece<T> o) { Deserialize((adv::Thing) o); o.Condition = condition; o.Solution = solution; } } public class Button_yml : Piece_yml<bool>, ISerializable<Button> { public void Deserialize(Button o) { Deserialize((Piece<bool>) o); } } public class Lever_yml : adv::Thing_yml, ISerializable<Lever> { public bool IsSolved {get;set;} public void Deserialize(Lever o) { Deserialize((adv::Thing) o); } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; namespace Microsoft.DotNet.Tools.Common { internal static class PathUtility { public static bool IsPlaceholderFile(string path) { return string.Equals(Path.GetFileName(path), "_._", StringComparison.Ordinal); } public static bool IsChildOfDirectory(string dir, string candidate) { if (dir == null) { throw new ArgumentNullException(nameof(dir)); } if (candidate == null) { throw new ArgumentNullException(nameof(candidate)); } dir = Path.GetFullPath(dir); dir = EnsureTrailingSlash(dir); candidate = Path.GetFullPath(candidate); return candidate.StartsWith(dir, StringComparison.OrdinalIgnoreCase); } public static string EnsureTrailingSlash(string path) { return EnsureTrailingCharacter(path, Path.DirectorySeparatorChar); } public static string EnsureTrailingForwardSlash(string path) { return EnsureTrailingCharacter(path, '/'); } private static string EnsureTrailingCharacter(string path, char trailingCharacter) { if (path == null) { throw new ArgumentNullException(nameof(path)); } // if the path is empty, we want to return the original string instead of a single trailing character. if (path.Length == 0 || path[path.Length - 1] == trailingCharacter) { return path; } return path + trailingCharacter; } public static void EnsureParentDirectory(string filePath) { string directory = Path.GetDirectoryName(filePath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } } /// <summary> /// Returns path2 relative to path1, with Path.DirectorySeparatorChar as separator /// </summary> public static string GetRelativePath(string path1, string path2) { return GetRelativePath(path1, path2, Path.DirectorySeparatorChar); } /// <summary> /// Returns path2 relative to path1, with given path separator /// </summary> public static string GetRelativePath(string path1, string path2, char separator) { if (string.IsNullOrEmpty(path1)) { throw new ArgumentException("Path must have a value", nameof(path1)); } if (string.IsNullOrEmpty(path2)) { throw new ArgumentException("Path must have a value", nameof(path2)); } StringComparison compare; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { compare = StringComparison.OrdinalIgnoreCase; // check if paths are on the same volume if (!string.Equals(Path.GetPathRoot(path1), Path.GetPathRoot(path2))) { // on different volumes, "relative" path is just path2 return path2; } } else { compare = StringComparison.Ordinal; } var index = 0; var path1Segments = path1.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var path2Segments = path2.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); // if path1 does not end with / it is assumed the end is not a directory // we will assume that is isn't a directory by ignoring the last split var len1 = path1Segments.Length - 1; var len2 = path2Segments.Length; // find largest common absolute path between both paths var min = Math.Min(len1, len2); while (min > index) { if (!string.Equals(path1Segments[index], path2Segments[index], compare)) { break; } // Handle scenarios where folder and file have same name (only if os supports same name for file and directory) // e.g. /file/name /file/name/app else if ((len1 == index && len2 > index + 1) || (len1 > index && len2 == index + 1)) { break; } ++index; } var path = ""; // check if path2 ends with a non-directory separator and if path1 has the same non-directory at the end if (len1 + 1 == len2 && !string.IsNullOrEmpty(path1Segments[index]) && string.Equals(path1Segments[index], path2Segments[index], compare)) { return path; } for (var i = index; len1 > i; ++i) { path += ".." + separator; } for (var i = index; len2 - 1 > i; ++i) { path += path2Segments[i] + separator; } // if path2 doesn't end with an empty string it means it ended with a non-directory name, so we add it back if (!string.IsNullOrEmpty(path2Segments[len2 - 1])) { path += path2Segments[len2 - 1]; } return path; } public static string GetAbsolutePath(string basePath, string relativePath) { if (basePath == null) { throw new ArgumentNullException(nameof(basePath)); } if (relativePath == null) { throw new ArgumentNullException(nameof(relativePath)); } Uri resultUri = new Uri(new Uri(basePath), new Uri(relativePath, UriKind.Relative)); return resultUri.LocalPath; } public static string GetDirectoryName(string path) { path = path.TrimEnd(Path.DirectorySeparatorChar); return path.Substring(Path.GetDirectoryName(path).Length).Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); } public static string GetPathWithForwardSlashes(string path) { return path.Replace('\\', '/'); } public static string GetPathWithBackSlashes(string path) { return path.Replace('/', '\\'); } public static string GetPathWithDirectorySeparator(string path) { if (Path.DirectorySeparatorChar == '/') { return GetPathWithForwardSlashes(path); } else { return GetPathWithBackSlashes(path); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Web.Script.Services; using System.Web.Services; using System.Xml; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Web; using Umbraco.Web.WebServices; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.BusinessLogic.Actions; using umbraco.cms.businesslogic.web; namespace umbraco.presentation.webservices { /// <summary> /// Summary description for nodeSorter /// </summary> [WebService(Namespace = "http://umbraco.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] [ScriptService] public class nodeSorter : UmbracoAuthorizedWebService { [WebMethod] public SortNode GetNodes(string ParentId, string App) { if (BasePage.ValidateUserContextID(BasePage.umbracoUserContextID)) { var nodes = new List<SortNode>(); // "hack for stylesheet" if (App == "settings") { var stylesheet = Services.FileService.GetStylesheetByName(ParentId.EnsureEndsWith(".css")); if (stylesheet == null) throw new InvalidOperationException("No stylesheet found by name " + ParentId); var sort = 0; foreach (var child in stylesheet.Properties) { nodes.Add(new SortNode(child.Name.GetHashCode(), sort, child.Name, DateTime.Now)); sort++; } return new SortNode() { SortNodes = nodes.ToArray() }; } else { var asInt = int.Parse(ParentId); var parent = new SortNode { Id = asInt }; var entityService = base.ApplicationContext.Services.EntityService; // Root nodes? if (asInt == -1) { if (App == "media") { var rootMedia = entityService.GetRootEntities(UmbracoObjectTypes.Media); nodes.AddRange(rootMedia.Select(media => new SortNode(media.Id, media.SortOrder, media.Name, media.CreateDate))); } else { var rootContent = entityService.GetRootEntities(UmbracoObjectTypes.Document); nodes.AddRange(rootContent.Select(content => new SortNode(content.Id, content.SortOrder, content.Name, content.CreateDate))); } } else { var children = entityService.GetChildren(asInt); nodes.AddRange(children.Select(child => new SortNode(child.Id, child.SortOrder, child.Name, child.CreateDate))); } parent.SortNodes = nodes.ToArray(); return parent; } } throw new ArgumentException("User not logged in"); } [WebMethod] public void UpdateSortOrder(string ParentId, string SortOrder) { if (AuthorizeRequest() == false) return; if (SortOrder.Trim().Length <= 0) return; var isContent = helper.Request("app") == "content" | helper.Request("app") == ""; var isMedia = helper.Request("app") == "media"; //ensure user is authorized for the app requested if (isContent && AuthorizeRequest(DefaultApps.content.ToString()) == false) return; if (isMedia && AuthorizeRequest(DefaultApps.media.ToString()) == false) return; var ids = SortOrder.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (isContent) { SortContent(ids, int.Parse(ParentId)); } else if (isMedia) { SortMedia(ids); } else { SortStylesheetProperties(ParentId, ids); } } private void SortMedia(string[] ids) { var mediaService = base.ApplicationContext.Services.MediaService; var sortedMedia = new List<IMedia>(); try { for (var i = 0; i < ids.Length; i++) { var id = int.Parse(ids[i]); var m = mediaService.GetById(id); sortedMedia.Add(m); } // Save Media with new sort order and update content xml in db accordingly var sorted = mediaService.Sort(sortedMedia); } catch (Exception ex) { LogHelper.Error<nodeSorter>("Could not update media sort order", ex); } } private void SortStylesheetProperties(string stylesheetName, string[] names) { var stylesheet = Services.FileService.GetStylesheetByName(stylesheetName.EnsureEndsWith(".css")); if (stylesheet == null) throw new InvalidOperationException("No stylesheet found by name " + stylesheetName); var currProps = stylesheet.Properties.ToArray(); //remove them all first foreach (var prop in currProps) { stylesheet.RemoveProperty(prop.Name); } //re-add them in the right order for (var i = 0; i < names.Length; i++) { var found = currProps.Single(x => x.Name == names[i]); stylesheet.AddProperty(found); } Services.FileService.SaveStylesheet(stylesheet); } private void SortContent(string[] ids, int parentId) { var contentService = base.ApplicationContext.Services.ContentService; var sortedContent = new List<IContent>(); try { for (var i = 0; i < ids.Length; i++) { var id = int.Parse(ids[i]); var c = contentService.GetById(id); sortedContent.Add(c); } // Save content with new sort order and update db+cache accordingly var sorted = contentService.Sort(sortedContent); // refresh sort order on cached xml // but no... this is not distributed - solely relying on content service & events should be enough //content.Instance.SortNodes(parentId); //send notifications! TODO: This should be put somewhere centralized instead of hard coded directly here ApplicationContext.Services.NotificationService.SendNotification(contentService.GetById(parentId), ActionSort.Instance, UmbracoContext, ApplicationContext); } catch (Exception ex) { LogHelper.Error<nodeSorter>("Could not update content sort order", ex); } } } [Serializable] public class SortNode { public SortNode() { } private SortNode[] _sortNodes; public SortNode[] SortNodes { get { return _sortNodes; } set { _sortNodes = value; } } public int TotalNodes { get { return _sortNodes != null ? _sortNodes.Length : 0; } set { int test = value; } } public SortNode(int Id, int SortOrder, string Name, DateTime CreateDate) { _id = Id; _sortOrder = SortOrder; _name = Name; _createDate = CreateDate; } private DateTime _createDate; public DateTime CreateDate { get { return _createDate; } set { _createDate = value; } } private string _name; public string Name { get { return _name; } set { _name = value; } } private int _sortOrder; public int SortOrder { get { return _sortOrder; } set { _sortOrder = value; } } private int _id; public int Id { get { return _id; } set { _id = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using iServe.Models; using iServe.Models.dotNailsCommon; //using xVal.ServerSide; using iServe.Models.Security; using System.Configuration; using System.Net.Mail; using System.Text; using System.Net; namespace iServe.Controllers { public class NeedController : iServeController, IDotNailsController { public IModelFactory<iServeDBProcedures> Model { get; set; } #region Pagination Properties public int CurrentPageNumber { get { int page = 1; if (this.Request.Params["page"] != null) { int.TryParse(this.Request.Params["page"], out page); } return page; } } #endregion Pagination Properties public NeedController() { Model = new ModelFactory<iServeDBProcedures>(new iServeDBDataContext(), GetCurrentUserID()); } public NeedController(IModelFactory<iServeDBProcedures> modelFactory) { Model = modelFactory; } #region Action Methods public ActionResult Index() { Model.DataContext.Log = new DebugTextWriter(); GetNeedsResultList needs = null; int? rowCount = 0; if (Request.IsAuthenticated) { needs = Model.SPs.GetNeeds(CurrentUser.ChurchID, CurrentUser.ID, CurrentPageNumber, Config.RecordsPerPage, "Created", false, ref rowCount); } return View("Index", needs); } public ActionResult Show(int id) { Need need = Model.New<Need>().GetByKey(id); return View(need); } public ActionResult New() { Need need = Model.New<Need>(); need.HelpersNeeded = 1; LoadSelectLists(need); return View(need); } public ActionResult Create(Need need) { if (ModelState.IsValid) { try { need.SubmittedByID = CurrentUser.ID; need.ChurchID = CurrentUser.ChurchID; need.NeedStatusID = (int)NeedStatusEnum.Pending; need.Save(); return RedirectToAction("Index"); } catch (Exception ex) { // put exception somewhere on screen or redirect throw (ex); } } // Unsuccessful, so load the necessary data for the form and show it again LoadSelectLists(need); return View("New", need); } public ActionResult Edit(int id) { return View(); } // TODO: Implement this. Currently unused and untested. public ActionResult Update(int id) { Need need = Model.New<Need>(); need.ID = id; // Bind data from form // Save need.Save(); return RedirectToAction("Index", "Need"); } public ActionResult Dashboard() { return View(); } public ActionResult iNeed() { // Create and run the query to return a list of needs that are submitted by the user. var needs = Model.New<Need>().GetByUserID(this.CurrentUser.ID); // Get the number of interested and committed users per need. List<int> unratedCommittedUsers = new List<int>(); List<int> interestedUsers = new List<int>(); foreach (var need in needs) { int committedUserCount = Model.New<UserNeed>().GetUnratedCommittedUsersCount(need.ID); int interestedUserCount = Model.New<UserNeed>().GetInterestedUsersCount(need.ID); if (committedUserCount > 0) { unratedCommittedUsers.Add(need.ID); } if (interestedUserCount > 0) { interestedUsers.Add(need.ID); } } // Add interested and committed user counts to ViewData in order to retrieve it from the page. ViewData["InterestedUsers"] = interestedUsers; ViewData["UnratedCommittedUsers"] = unratedCommittedUsers; // Only get the needs that are met but with committed users that haven't been rated or needs that haven't been cancelled or met. var openNeeds = needs.Where(need => ((NeedStatusEnum)need.NeedStatusID == NeedStatusEnum.Met && unratedCommittedUsers.Contains(need.ID)) || ((NeedStatusEnum)need.NeedStatusID != NeedStatusEnum.Cancelled) && (NeedStatusEnum)need.NeedStatusID != NeedStatusEnum.Met); // Return the partial view with the list of needs. return View("_iNeed", openNeeds); } public ActionResult iServe() { List<GetNeedInfoByHelperResult> needInfo = Model.SPs.GetNeedInfoByHelper(CurrentUser.ID, CurrentUser.ChurchID).ToList(); //Dictionary<int, string> userNeedStatuses; //List<Need> needs = Model.New<Need>().GetAllByUser(CurrentUser.ID, out userNeedStatuses); //var unMetNeeds = needs.Where(need => need.NeedStatusID != (int)NeedStatusEnum.Met); //ViewData["UserNeedStatuses"] = userNeedStatuses; //ViewData["CanRate"] = canRate; // Return the partial view with the list of needs. return View("_iServe", needInfo); } public ActionResult NeedAdmin() { List<Need> needs = Model.New<Need>().GetAll().ToList(); return View("NeedAdmin", needs); } #endregion #region Ajax methods public ActionResult ExpressInterest(int id) { try { UserNeed userNeed = Model.New<UserNeed>(); userNeed.EntityState = EntityStateEnum.Added; userNeed.UserID = CurrentUser.ID; userNeed.NeedID = id; userNeed.UserNeedStatusID = (int)UserNeedStatusEnum.Interested; userNeed.Save(); // Send message to submitter. //SendMessageToSubmitter(id); } catch (Exception ex) { ViewData["error"] = ex.Message + "<br/> Inner Exception: <br/>"; if (ex.InnerException != null) ViewData["error"] += ex.InnerException.Message; return View("Error"); } //int? rowCount = 0; //GetNeedsResultList needs = Model.SPs.GetNeeds(CurrentUser.ChurchID, CurrentUser.ID, CurrentPageNumber, RecordsPerPage, "Created", false, ref rowCount); //return View("Index", needs); //return new RedirectResult(Url.Action("Index")); return new EmptyResult(); } /// <summary> /// Shows the users that have expressed interest or have committed to the specified need. /// </summary> /// <param name="needID"> /// The id of the need. /// </param> /// <returns></returns> public ActionResult ShowInvolvement(int needID) { // Get the need with the specified id that is submitted by the current user. Need need = Model.New<Need>().GetByKeyAndUserID(needID, this.CurrentUser.ID); if (need != null) { // Get committed users. List<GetNeedHelpersByStatusResult> committedUsers = Model.SPs.GetNeedHelpersByStatus(needID, (int)UserNeedStatusEnum.Committed, CurrentUser.ChurchID).ToList(); ViewData["CommittedUsers"] = committedUsers; // Get accepted users. List<GetNeedHelpersByStatusResult> acceptedUsers = Model.SPs.GetNeedHelpersByStatus(needID, (int)UserNeedStatusEnum.Accepted, CurrentUser.ChurchID).ToList(); ViewData["AcceptedUsers"] = acceptedUsers; // Get interested users. List<GetNeedHelpersByStatusResult> interestedUsers = Model.SPs.GetNeedHelpersByStatus(needID, (int)UserNeedStatusEnum.Interested, CurrentUser.ChurchID).ToList(); ViewData["InterestedUsers"] = interestedUsers; return View("_needInvolvement", need); } ViewData["error"] = "The need doesn't exist or you do not have permissions to access this need."; return View("Error"); } /// <summary> /// Accepts a user that has expressed interest in a need. /// </summary> /// <param name="needID"> /// The id of the need that the user has expressed interest in. /// </param> /// <param name="userID"> /// The id of the user to accept. /// </param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult AcceptUser(int needID, int userID) { UserNeed userNeed = Model.New<UserNeed>(); userNeed.EntityState = EntityStateEnum.Modified; userNeed.UserID = userID; userNeed.NeedID = needID; userNeed.UserNeedStatusID = (int)UserNeedStatusEnum.Accepted; userNeed.Save(); return new EmptyResult(); } /// <summary> /// Declines a user that has expressed interest in a need. /// </summary> /// <param name="needID"> /// The id of the need that the user has expressed interest in. /// </param> /// <param name="userID"> /// The id of the user to decline. /// </param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeclineUser(int needID, int userID) { UserNeed userNeed = Model.New<UserNeed>(); userNeed.EntityState = EntityStateEnum.Modified; userNeed.UserID = userID; userNeed.NeedID = needID; userNeed.UserNeedStatusID = (int)UserNeedStatusEnum.SubmitterDeclined; userNeed.Save(); return new EmptyResult(); } /// <summary> /// Removes a user's involvement in a need. /// </summary> /// <param name="needID"> /// The id of the need that the user is involved with. /// </param> /// <param name="userID"> /// The id of the user. /// </param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult RemoveUser(int needID, int userID) { UserNeed userNeed = Model.New<UserNeed>(); userNeed.EntityState = EntityStateEnum.Deleted; userNeed.UserID = userID; userNeed.NeedID = needID; userNeed.Save(); return new EmptyResult(); } /// <summary> /// Commits a user to a need. /// </summary> /// <param name="needID"> /// The id of the need to commit the user to. /// </param> /// <param name="userID"> /// The id of the user. /// </param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult CommitUser(int needID, int userID) { UserNeed userNeed = Model.New<UserNeed>(); userNeed.EntityState = EntityStateEnum.Modified; userNeed.UserID = userID; userNeed.NeedID = needID; userNeed.UserNeedStatusID = (int)UserNeedStatusEnum.Committed; userNeed.Save(); return new EmptyResult(); } /// <summary> /// Rates a committed helper after the need has been met or cancelled. /// </summary> /// <param name="rating"> /// The rating value to add to the helper's total rating. /// </param> /// <param name="userID"> /// The user id of the helper. /// </param> /// <param name="needID"> /// The id of the need. /// </param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult RateHelper(int rating, int userID, int needID) { // Get the helper to obtain the helper's current rating. User user = Model.New<User>().GetByKey(userID); // Update the helper's rating. user.Rating += rating; user.Save(); // Remember that the helper has been rated so that the submitter cannot rate the helper again. UserNeed helper = Model.New<UserNeed>().GetByKey(userID, needID); helper.HasBeenRated = true; helper.Save(); return new EmptyResult(); } /// <summary> /// Rates the submitter after the need has been met or cancelled. /// </summary> /// <param name="rating"> /// The rating value to add to the submitter's total rating. /// </param> /// <param name="userID"> /// The user id of the submitter. /// </param> /// <param name="needID"> /// The id of the need. /// </param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult RateSubmitter(int rating, int userID, int needID) { // Get the submitter to obtain the submitter's current rating. User user = Model.New<User>().GetByKey(userID); // Update the helper's rating. user.Rating += rating; user.Save(); // Remember that the submitter has been rated so that the helper cannot rate the submitter again. UserNeed helper = Model.New<UserNeed>().GetByKey(this.CurrentUser.ID, needID); helper.HasRatedSubmitter = true; helper.Save(); return new EmptyResult(); } /// <summary> /// Completes a need. /// </summary> /// <param name="needID"> /// The id of the need to complete /// </param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult CompleteNeed(int needID) { Model.SPs.CompleteNeed(needID); return new EmptyResult(); } /// <summary> /// Cancels a need. /// </summary> /// <param name="needID"> /// The id of the need to cancel /// </param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult CancelNeed(int needID) { Model.SPs.CancelNeed(needID); return View("Dashboard"); } #endregion #region Private Methods /// <summary> /// Creates SelectLists for Foreign-keys /// </summary> private void LoadSelectLists(Need need) { var categories = Model.New<Category>().GetAll().ToList(); ViewData["Categories"] = new SelectList(categories, "ID", "Name", need.CategoryID); } /// <summary> /// Sends an email /// </summary> /// <param name="userID"> /// The id of the helper to send the message to. /// If the id is null, the message will be sent to the submitter of the need. /// </param> public ActionResult SendMessage(int needID, int? userID, string messageText) { try { string fromEmail = Config.FromEmail; string smtpServer = Config.SMTPServer; // Get the need (we use the name) Need need = Model.New<Need>().GetByKey(needID); // Get the user to send to. User user = null; if (userID != null && userID != int.MinValue) { user = Model.New<User>().GetByKey(userID.Value); } else { user = Model.New<User>().GetSubmitterByNeedID(needID); } string subject = string.Format("You received a message from {0} regarding need: {1}", CurrentUser.Name, need.Name); StringBuilder body = new StringBuilder(); body.AppendFormat("<b>Username:</b> {0}<br />", CurrentUser.Name); body.AppendFormat("<b>Need:</b> {0}<br />", need.Name); body.AppendFormat("<b>Message:</b><br />{0}", messageText); // Save the message Message message = Model.New<Message>(); message.Body = body.ToString(); message.NeedID = needID; message.FromUserID = CurrentUser.ID; message.ChurchID = CurrentUser.ChurchID; message.Save(); // Send the message as an email to the user MailMessage mailMessage = new MailMessage(fromEmail, user.Email, subject, body.ToString()); mailMessage.IsBodyHtml = true; SmtpClient client = new SmtpClient(Config.SMTPServer); NetworkCredential credentials = new NetworkCredential(Config.SMTPUsername, Config.SMTPPassword); client.UseDefaultCredentials = false; client.Credentials = credentials; client.Send(mailMessage); } catch (Exception ex) { ViewData["error"] = ex.Message + "<br/> Inner Exception: <br/>"; if (ex.InnerException != null) ViewData["error"] += ex.InnerException.Message; return View("Error"); } return new EmptyResult(); } #endregion Private Methods #region IdotNailsController Members public IEntity CreateModelEntityUsingDefaultFactory(Type type) { return Model.New(type); } #endregion } }
// // DatabaseSource.cs // // Author: // Aaron Bockover <[email protected]> // Gabriel Burt <[email protected]> // // Copyright (C) 2005-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Query; using Hyena.Data.Sqlite; using Hyena.Collections; using Banshee.Base; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration; using Banshee.Query; namespace Banshee.Sources { public abstract class DatabaseSource : Source, ITrackModelSource, IFilterableSource, IDurationAggregator, IFileSizeAggregator { public event EventHandler FiltersChanged; protected delegate void TrackRangeHandler (DatabaseTrackListModel model, RangeCollection.Range range); protected DatabaseTrackListModel track_model; protected DatabaseAlbumListModel album_model; protected DatabaseArtistListModel artist_model; protected DatabaseQueryFilterModel<string> genre_model; private RateLimiter reload_limiter; public DatabaseSource (string generic_name, string name, string id, int order) : this (generic_name, name, id, order, null) { } public DatabaseSource (string generic_name, string name, string id, int order, Source parent) : base (generic_name, name, order, id) { if (parent != null) { SetParentSource (parent); } DatabaseSourceInitialize (); } protected DatabaseSource () : base () { } public void UpdateCounts () { DatabaseTrackModel.UpdateUnfilteredAggregates (); ever_counted = true; OnUpdated (); } public abstract void Save (); protected override void Initialize () { base.Initialize (); DatabaseSourceInitialize (); } protected virtual bool HasArtistAlbum { get { return true; } } public DatabaseTrackListModel DatabaseTrackModel { get { return track_model ?? (track_model = (Parent as DatabaseSource ?? this).CreateTrackModelFor (this)); } protected set { track_model = value; } } private IDatabaseTrackModelCache track_cache; protected IDatabaseTrackModelCache TrackCache { get { return track_cache ?? (track_cache = new DatabaseTrackModelCache<DatabaseTrackInfo> ( ServiceManager.DbConnection, UniqueId, DatabaseTrackModel, TrackProvider)); } set { track_cache = value; } } protected DatabaseTrackModelProvider<DatabaseTrackInfo> TrackProvider { get { return DatabaseTrackInfo.Provider; } } private void DatabaseSourceInitialize () { InitializeTrackModel (); current_filters_schema = CreateSchema<string[]> ("current_filters"); DatabaseSource filter_src = Parent as DatabaseSource ?? this; foreach (IFilterListModel filter in filter_src.CreateFiltersFor (this)) { AvailableFilters.Add (filter); DefaultFilters.Add (filter); } reload_limiter = new RateLimiter (RateLimitedReload); } protected virtual DatabaseTrackListModel CreateTrackModelFor (DatabaseSource src) { return new DatabaseTrackListModel (ServiceManager.DbConnection, TrackProvider, src); } protected virtual IEnumerable<IFilterListModel> CreateFiltersFor (DatabaseSource src) { if (!HasArtistAlbum) { yield break; } DatabaseArtistListModel artist_model = new DatabaseArtistListModel (src, src.DatabaseTrackModel, ServiceManager.DbConnection, src.UniqueId); DatabaseAlbumListModel album_model = new DatabaseAlbumListModel (src, src.DatabaseTrackModel, ServiceManager.DbConnection, src.UniqueId); DatabaseQueryFilterModel<string> genre_model = new DatabaseQueryFilterModel<string> (src, src.DatabaseTrackModel, ServiceManager.DbConnection, Catalog.GetString ("All Genres ({0})"), src.UniqueId, BansheeQuery.GenreField, "Genre"); if (this == src) { this.artist_model = artist_model; this.album_model = album_model; this.genre_model = genre_model; } yield return artist_model; yield return album_model; yield return genre_model; } protected virtual void AfterInitialized () { DatabaseTrackModel.Initialize (TrackCache); OnSetupComplete (); } protected virtual void InitializeTrackModel () { } protected bool NeedsReloadWhenFieldsChanged (Hyena.Query.QueryField [] fields) { if (fields == null) { return true; } foreach (QueryField field in fields) if (NeedsReloadWhenFieldChanged (field)) return true; return false; } private List<QueryField> query_fields; private QueryNode last_query; protected virtual bool NeedsReloadWhenFieldChanged (Hyena.Query.QueryField field) { if (field == null) return true; // If it's the artist or album name, then we care, since it affects the browser // FIXME this should be based on what filters (aka browsers) are active. InternetRadio, // for example, has only a Genre filter. if (field == Banshee.Query.BansheeQuery.ArtistField || field == Banshee.Query.BansheeQuery.AlbumField) { return true; } if (DatabaseTrackModel == null) { Log.Error ("DatabaseTrackModel should not be null in DatabaseSource.NeedsReloadWhenFieldChanged"); return false; } // If it's the field we're sorting by, then yes, we care var sort_column = DatabaseTrackModel.SortColumn; if (sort_column != null && sort_column.Field == field) { return true; } // Make sure the query isn't dependent on this field QueryNode query = DatabaseTrackModel.Query; if (query != null) { if (query != last_query) { query_fields = new List<QueryField> (query.GetFields ()); last_query = query; } if (query_fields.Contains (field)) return true; } return false; } #region Public Properties public override int Count { get { return ever_counted ? DatabaseTrackModel.UnfilteredCount : SavedCount; } } public override int FilteredCount { get { return DatabaseTrackModel.Count; } } public virtual TimeSpan Duration { get { return DatabaseTrackModel.Duration; } } public virtual long FileSize { get { return DatabaseTrackModel.FileSize; } } public override string FilterQuery { set { base.FilterQuery = value; DatabaseTrackModel.UserQuery = FilterQuery; ThreadAssist.SpawnFromMain (delegate { Reload (); }); } } public virtual bool CanAddTracks { get { return true; } } public virtual bool CanRemoveTracks { get { return true; } } public virtual bool CanDeleteTracks { get { return true; } } public virtual bool ConfirmRemoveTracks { get { return true; } } public virtual bool CanRepeat { get { return true; } } public virtual bool CanShuffle { get { return true; } } public override string TrackModelPath { get { return DBusServiceManager.MakeObjectPath (DatabaseTrackModel); } } public TrackListModel TrackModel { get { return DatabaseTrackModel; } } public virtual bool ShowBrowser { get { return true; } } public virtual bool Indexable { get { return false; } } private int saved_count; protected int SavedCount { get { return saved_count; } set { saved_count = value; } } public override bool AcceptsInputFromSource (Source source) { return CanAddTracks && source != this; } public override bool AcceptsUserInputFromSource (Source source) { return base.AcceptsUserInputFromSource (source) && CanAddTracks; } public override bool HasViewableTrackProperties { get { return true; } } #endregion #region Filters (aka Browsers) private IList<IFilterListModel> available_filters; public IList<IFilterListModel> AvailableFilters { get { return available_filters ?? (available_filters = new List<IFilterListModel> ()); } protected set { available_filters = value; } } private IList<IFilterListModel> default_filters; public IList<IFilterListModel> DefaultFilters { get { return default_filters ?? (default_filters = new List<IFilterListModel> ()); } protected set { default_filters = value; } } private IList<IFilterListModel> current_filters; public IList<IFilterListModel> CurrentFilters { get { if (current_filters == null) { current_filters = new List<IFilterListModel> (); string [] current = current_filters_schema.Get (); if (current != null) { foreach (string filter_name in current) { foreach (IFilterListModel filter in AvailableFilters) { if (filter.FilterName == filter_name) { current_filters.Add (filter); break; } } } } else { foreach (IFilterListModel filter in DefaultFilters) { current_filters.Add (filter); } } } return current_filters; } protected set { current_filters = value; } } public void ReplaceFilter (IFilterListModel old_filter, IFilterListModel new_filter) { int i = current_filters.IndexOf (old_filter); if (i != -1) { current_filters[i] = new_filter; SaveCurrentFilters (); } } public void AppendFilter (IFilterListModel filter) { if (current_filters.IndexOf (filter) == -1) { current_filters.Add (filter); SaveCurrentFilters (); } } public void RemoveFilter (IFilterListModel filter) { if (current_filters.Remove (filter)) { SaveCurrentFilters (); } } private void SaveCurrentFilters () { Reload (); if (current_filters == null) { current_filters_schema.Set (null); } else { string [] filters = new string [current_filters.Count]; int i = 0; foreach (IFilterListModel filter in CurrentFilters) { filters[i++] = filter.FilterName; } current_filters_schema.Set (filters); } EventHandler handler = FiltersChanged; if (handler != null) { handler (this, EventArgs.Empty); } } private SchemaEntry<string[]> current_filters_schema; #endregion #region Public Methods public virtual void Reload () { ever_counted = ever_reloaded = true; reload_limiter.Execute (); } protected void RateLimitedReload () { lock (track_model) { DatabaseTrackModel.Reload (); } OnUpdated (); Save (); } public virtual bool HasDependencies { get { return false; } } public void RemoveTrack (int index) { if (index != -1) { RemoveTrackRange (track_model, new RangeCollection.Range (index, index)); OnTracksRemoved (); } } public void RemoveTrack (DatabaseTrackInfo track) { RemoveTrack (track_model.IndexOf (track)); } public virtual void RemoveSelectedTracks () { RemoveSelectedTracks (track_model); } public virtual void RemoveSelectedTracks (DatabaseTrackListModel model) { WithTrackSelection (model, RemoveTrackRange); OnTracksRemoved (); } public virtual void DeleteSelectedTracks () { DeleteSelectedTracks (track_model); } protected virtual void DeleteSelectedTracks (DatabaseTrackListModel model) { if (model == null) return; WithTrackSelection (model, DeleteTrackRange); OnTracksDeleted (); } public virtual bool AddSelectedTracks (Source source) { if (!AcceptsInputFromSource (source)) return false; DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel; if (model == null) { return false; } WithTrackSelection (model, AddTrackRange); OnTracksAdded (); OnUserNotifyUpdated (); return true; } public virtual bool AddAllTracks (Source source) { if (!AcceptsInputFromSource (source) || source.Count == 0) return false; DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel; lock (model) { AddTrackRange (model, new RangeCollection.Range (0, source.Count)); } OnTracksAdded (); OnUserNotifyUpdated (); return true; } public virtual void RateSelectedTracks (int rating) { RateSelectedTracks (track_model, rating); } public virtual void RateSelectedTracks (DatabaseTrackListModel model, int rating) { Selection selection = model.Selection; if (selection.Count == 0) return; lock (model) { foreach (RangeCollection.Range range in selection.Ranges) { RateTrackRange (model, range, rating); } } OnTracksChanged (BansheeQuery.RatingField); // In case we updated the currently playing track DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo; if (track != null) { track.Refresh (); ServiceManager.PlayerEngine.TrackInfoUpdated (); } } public override SourceMergeType SupportedMergeTypes { get { return SourceMergeType.All; } } public override void MergeSourceInput (Source source, SourceMergeType mergeType) { if (mergeType == SourceMergeType.Source || mergeType == SourceMergeType.All) { AddAllTracks (source); } else if (mergeType == SourceMergeType.ModelSelection) { AddSelectedTracks (source); } } #endregion #region Protected Methods protected virtual void OnTracksAdded () { Reload (); } protected void OnTracksChanged () { OnTracksChanged (null); } protected virtual void OnTracksChanged (params QueryField [] fields) { HandleTracksChanged (this, new TrackEventArgs (fields)); foreach (PrimarySource psource in PrimarySources) { psource.NotifyTracksChanged (fields); } } protected virtual void OnTracksDeleted () { PruneArtistsAlbums (); HandleTracksDeleted (this, new TrackEventArgs ()); foreach (PrimarySource psource in PrimarySources) { psource.NotifyTracksDeleted (); } } protected virtual void OnTracksRemoved () { PruneArtistsAlbums (); Reload (); } // If we are a PrimarySource, return ourself and our children, otherwise if our Parent // is one, do so for it, otherwise do so for all PrimarySources. private IEnumerable<PrimarySource> PrimarySources { get { PrimarySource psource; if ((psource = this as PrimarySource) != null) { yield return psource; } else { if ((psource = Parent as PrimarySource) != null) { yield return psource; } else { foreach (Source source in ServiceManager.SourceManager.Sources) { if ((psource = source as PrimarySource) != null) { yield return psource; } } } } } } protected HyenaSqliteCommand rate_track_range_command; protected HyenaSqliteCommand RateTrackRangeCommand { get { if (rate_track_range_command == null) { if (track_model.CachesJoinTableEntries) { rate_track_range_command = new HyenaSqliteCommand (String.Format (@" UPDATE CoreTracks SET Rating = ?, DateUpdatedStamp = ? WHERE TrackID IN (SELECT TrackID FROM {0} WHERE {1} IN (SELECT ItemID FROM CoreCache WHERE ModelID = {2} LIMIT ?, ?))", track_model.JoinTable, track_model.JoinPrimaryKey, track_model.CacheId )); } else { rate_track_range_command = new HyenaSqliteCommand (String.Format (@" UPDATE CoreTracks SET Rating = ?, DateUpdatedStamp = ? WHERE TrackID IN ( SELECT ItemID FROM CoreCache WHERE ModelID = {0} LIMIT ?, ?)", track_model.CacheId )); } } return rate_track_range_command; } } private bool ever_reloaded = false, ever_counted = false; public override void Activate () { if (!ever_reloaded) Reload (); } public override void Deactivate () { DatabaseTrackModel.InvalidateCache (false); foreach (IFilterListModel filter in AvailableFilters) { filter.InvalidateCache (false); } } protected virtual void RemoveTrackRange (DatabaseTrackListModel model, RangeCollection.Range range) { Log.ErrorFormat ("RemoveTrackRange not implemented by {0}", this); } protected virtual void DeleteTrackRange (DatabaseTrackListModel model, RangeCollection.Range range) { Log.ErrorFormat ("DeleteTrackRange not implemented by {0}", this); } protected virtual void AddTrackRange (DatabaseTrackListModel model, RangeCollection.Range range) { Log.ErrorFormat ("AddTrackRange not implemented by {0}", this); } protected virtual void AddTrack (DatabaseTrackInfo track) { Log.ErrorFormat ("AddTrack not implemented by {0}", this); } protected virtual void RateTrackRange (DatabaseTrackListModel model, RangeCollection.Range range, int rating) { ServiceManager.DbConnection.Execute (RateTrackRangeCommand, rating, DateTime.Now, range.Start, range.End - range.Start + 1); } protected void WithTrackSelection (DatabaseTrackListModel model, TrackRangeHandler handler) { Selection selection = model.Selection; if (selection.Count == 0) return; lock (model) { foreach (RangeCollection.Range range in selection.Ranges) { handler (model, range); } } } protected HyenaSqliteCommand prune_command; protected HyenaSqliteCommand PruneCommand { get { return prune_command ?? (prune_command = new HyenaSqliteCommand (String.Format ( @"DELETE FROM CoreCache WHERE ModelID = ? AND ItemID NOT IN (SELECT ArtistID FROM CoreTracks WHERE TrackID IN (SELECT {0})); DELETE FROM CoreCache WHERE ModelID = ? AND ItemID NOT IN (SELECT AlbumID FROM CoreTracks WHERE TrackID IN (SELECT {0}));", track_model.TrackIdsSql ), artist_model.CacheId, artist_model.CacheId, 0, artist_model.Count, album_model.CacheId, album_model.CacheId, 0, album_model.Count )); } } protected void InvalidateCaches () { track_model.InvalidateCache (true); foreach (IFilterListModel filter in CurrentFilters) { filter.InvalidateCache (true); } } protected virtual void PruneArtistsAlbums () { //Console.WriteLine ("Pruning with {0}", PruneCommand.Text); //ServiceManager.DbConnection.Execute (PruneCommand); } protected virtual void HandleTracksAdded (Source sender, TrackEventArgs args) { } protected virtual void HandleTracksChanged (Source sender, TrackEventArgs args) { } protected virtual void HandleTracksDeleted (Source sender, TrackEventArgs args) { } #endregion } }
/*! @file @author Generate utility by Albert Semenov @date 01/2009 @module */ using System; using System.Runtime.InteropServices; namespace MyGUI.Sharp { public class TabControl : Widget { #region TabControl protected override string GetWidgetType() { return "TabControl"; } internal static BaseWidget RequestWrapTabControl(BaseWidget _parent, IntPtr _widget) { TabControl widget = new TabControl(); widget.WrapWidget(_parent, _widget); return widget; } internal static BaseWidget RequestCreateTabControl(BaseWidget _parent, WidgetStyle _style, string _skin, IntCoord _coord, Align _align, string _layer, string _name) { TabControl widget = new TabControl(); widget.CreateWidgetImpl(_parent, _style, _skin, _coord, _align, _layer, _name); return widget; } #endregion //InsertPoint #region Event TabChangeSelect [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControlEvent_AdviseTabChangeSelect(IntPtr _native, bool _advise); public delegate void HandleTabChangeSelect( TabControl _sender, uint _index); private HandleTabChangeSelect mEventTabChangeSelect; public event HandleTabChangeSelect EventTabChangeSelect { add { if (ExportEventTabChangeSelect.mDelegate == null) { ExportEventTabChangeSelect.mDelegate = new ExportEventTabChangeSelect.ExportHandle(OnExportTabChangeSelect); ExportEventTabChangeSelect.ExportTabControlEvent_DelegateTabChangeSelect(ExportEventTabChangeSelect.mDelegate); } if (mEventTabChangeSelect == null) ExportTabControlEvent_AdviseTabChangeSelect(Native, true); mEventTabChangeSelect += value; } remove { mEventTabChangeSelect -= value; if (mEventTabChangeSelect == null) ExportTabControlEvent_AdviseTabChangeSelect(Native, false); } } private struct ExportEventTabChangeSelect { [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] public static extern void ExportTabControlEvent_DelegateTabChangeSelect(ExportHandle _delegate); [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void ExportHandle( IntPtr _sender, uint _index); public static ExportHandle mDelegate; } private static void OnExportTabChangeSelect( IntPtr _sender, uint _index) { TabControl sender = (TabControl)BaseWidget.GetByNative(_sender); if (sender.mEventTabChangeSelect != null) sender.mEventTabChangeSelect( sender , _index); } #endregion #region Method GetButtonWidth [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern int ExportTabControl_GetButtonWidth__item(IntPtr _native, IntPtr _item); public int GetButtonWidth( TabItem _item) { return ExportTabControl_GetButtonWidth__item(Native, _item.Native); } #endregion #region Method GetButtonWidthAt [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern int ExportTabControl_GetButtonWidthAt__index(IntPtr _native, uint _index); public int GetButtonWidthAt( uint _index) { return ExportTabControl_GetButtonWidthAt__index(Native, _index); } #endregion #region Method SetButtonWidth [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SetButtonWidth__item__width(IntPtr _native, IntPtr _item, int _width); public void SetButtonWidth( TabItem _item, int _width) { ExportTabControl_SetButtonWidth__item__width(Native, _item.Native, _width); } #endregion #region Method SetButtonWidthAt [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SetButtonWidthAt__index__width(IntPtr _native, uint _index, int _width); public void SetButtonWidthAt( uint _index, int _width) { ExportTabControl_SetButtonWidthAt__index__width(Native, _index, _width); } #endregion #region Method BeginToItemSelected [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_BeginToItemSelected(IntPtr _native); public void BeginToItemSelected( ) { ExportTabControl_BeginToItemSelected(Native); } #endregion #region Method BeginToItemLast [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_BeginToItemLast(IntPtr _native); public void BeginToItemLast( ) { ExportTabControl_BeginToItemLast(Native); } #endregion #region Method BeginToItemFirst [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_BeginToItemFirst(IntPtr _native); public void BeginToItemFirst( ) { ExportTabControl_BeginToItemFirst(Native); } #endregion #region Method BeginToItem [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_BeginToItem__item(IntPtr _native, IntPtr _item); public void BeginToItem( TabItem _item) { ExportTabControl_BeginToItem__item(Native, _item.Native); } #endregion #region Method BeginToItemAt [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_BeginToItemAt__index(IntPtr _native, uint _index); public void BeginToItemAt( uint _index) { ExportTabControl_BeginToItemAt__index(Native, _index); } #endregion #region Method GetItemName [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExportTabControl_GetItemName__item(IntPtr _native, IntPtr _item); public string GetItemName( TabItem _item) { return Marshal.PtrToStringUni(ExportTabControl_GetItemName__item(Native, _item.Native)); } #endregion #region Method GetItemNameAt [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExportTabControl_GetItemNameAt__index(IntPtr _native, uint _index); public string GetItemNameAt( uint _index) { return Marshal.PtrToStringUni(ExportTabControl_GetItemNameAt__index(Native, _index)); } #endregion #region Method SetItemName [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SetItemName__item__name(IntPtr _native, IntPtr _item, [MarshalAs(UnmanagedType.LPWStr)] string _name); public void SetItemName( TabItem _item, string _name) { ExportTabControl_SetItemName__item__name(Native, _item.Native, _name); } #endregion #region Method SetItemNameAt [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SetItemNameAt__index__name(IntPtr _native, uint _index, [MarshalAs(UnmanagedType.LPWStr)] string _name); public void SetItemNameAt( uint _index, string _name) { ExportTabControl_SetItemNameAt__index__name(Native, _index, _name); } #endregion #region Method SwapItems [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SwapItems__index1__index2(IntPtr _native, uint _index1, uint _index2); public void SwapItems( uint _index1, uint _index2) { ExportTabControl_SwapItems__index1__index2(Native, _index1, _index2); } #endregion #region Method FindItemWith [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExportTabControl_FindItemWith__name(IntPtr _native, [MarshalAs(UnmanagedType.LPWStr)] string _name); public TabItem FindItemWith( string _name) { return (TabItem)BaseWidget.GetByNative(ExportTabControl_FindItemWith__name(Native, _name)); } #endregion #region Method FindItemIndexWith [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern uint ExportTabControl_FindItemIndexWith__name(IntPtr _native, [MarshalAs(UnmanagedType.LPWStr)] string _name); public uint FindItemIndexWith( string _name) { return ExportTabControl_FindItemIndexWith__name(Native, _name); } #endregion #region Method FindItemIndex [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern uint ExportTabControl_FindItemIndex__item(IntPtr _native, IntPtr _item); public uint FindItemIndex( TabItem _item) { return ExportTabControl_FindItemIndex__item(Native, _item.Native); } #endregion #region Method GetItemIndex [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern uint ExportTabControl_GetItemIndex__item(IntPtr _native, IntPtr _item); public uint GetItemIndex( TabItem _item) { return ExportTabControl_GetItemIndex__item(Native, _item.Native); } #endregion #region Method GetItemAt [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExportTabControl_GetItemAt__index(IntPtr _native, uint _index); public TabItem GetItemAt( uint _index) { return (TabItem)BaseWidget.GetByNative(ExportTabControl_GetItemAt__index(Native, _index)); } #endregion #region Method RemoveAllItems [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_RemoveAllItems(IntPtr _native); public void RemoveAllItems( ) { ExportTabControl_RemoveAllItems(Native); } #endregion #region Method RemoveItem [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_RemoveItem__item(IntPtr _native, IntPtr _item); public void RemoveItem( TabItem _item) { ExportTabControl_RemoveItem__item(Native, _item.Native); } #endregion #region Method RemoveItemAt [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_RemoveItemAt__index(IntPtr _native, uint _index); public void RemoveItemAt( uint _index) { ExportTabControl_RemoveItemAt__index(Native, _index); } #endregion #region Method AddItem [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExportTabControl_AddItem__name(IntPtr _native, [MarshalAs(UnmanagedType.LPWStr)] string _name); public TabItem AddItem( string _name) { return (TabItem)BaseWidget.GetByNative(ExportTabControl_AddItem__name(Native, _name)); } #endregion #region Method InsertItemAt [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExportTabControl_InsertItemAt__index__name(IntPtr _native, uint _index, [MarshalAs(UnmanagedType.LPWStr)] string _name); public TabItem InsertItemAt( uint _index, string _name) { return (TabItem)BaseWidget.GetByNative(ExportTabControl_InsertItemAt__index__name(Native, _index, _name)); } #endregion #region Property SmoothShow [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern bool ExportTabControl_GetSmoothShow(IntPtr _widget); [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SetSmoothShow(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value); public bool SmoothShow { get { return ExportTabControl_GetSmoothShow(Native); } set { ExportTabControl_SetSmoothShow(Native, value); } } #endregion #region Property ButtonAutoWidth [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern bool ExportTabControl_GetButtonAutoWidth(IntPtr _widget); [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SetButtonAutoWidth(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value); public bool ButtonAutoWidth { get { return ExportTabControl_GetButtonAutoWidth(Native); } set { ExportTabControl_SetButtonAutoWidth(Native, value); } } #endregion #region Property ButtonDefaultWidth [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern int ExportTabControl_GetButtonDefaultWidth(IntPtr _widget); [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SetButtonDefaultWidth(IntPtr _widget, int _value); public int ButtonDefaultWidth { get { return ExportTabControl_GetButtonDefaultWidth(Native); } set { ExportTabControl_SetButtonDefaultWidth(Native, value); } } #endregion #region Property ItemSelected [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ExportTabControl_GetItemSelected(IntPtr _widget); [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SetItemSelected(IntPtr _widget, TabItem _value); public TabItem ItemSelected { get { return (TabItem)BaseWidget.GetByNative(ExportTabControl_GetItemSelected(Native)); } set { ExportTabControl_SetItemSelected(Native, value); } } #endregion #region Property IndexSelected [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern uint ExportTabControl_GetIndexSelected(IntPtr _widget); [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern void ExportTabControl_SetIndexSelected(IntPtr _widget, uint _value); public uint IndexSelected { get { return ExportTabControl_GetIndexSelected(Native); } set { ExportTabControl_SetIndexSelected(Native, value); } } #endregion #region Property ItemCount [DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)] private static extern uint ExportTabControl_GetItemCount(IntPtr _native); public uint ItemCount { get { return ExportTabControl_GetItemCount(Native); } } #endregion } }
// // DialogViewController.cs: drives MonoTouch.Dialog // // Author: // Miguel de Icaza // // Code to support pull-to-refresh based on Martin Bowling's TweetTableView // which is based in turn in EGOTableViewPullRefresh code which was created // by Devin Doty and is Copyrighted 2009 enormego and released under the // MIT X11 license // using System; using System.Collections.Generic; #if XAMCORE_2_0 using Foundation; using UIKit; using CoreGraphics; using NSAction = global::System.Action; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; #endif #if !XAMCORE_2_0 using nint = global::System.Int32; using nuint = global::System.UInt32; using nfloat = global::System.Single; using CGSize = global::System.Drawing.SizeF; using CGPoint = global::System.Drawing.PointF; using CGRect = global::System.Drawing.RectangleF; #endif namespace MonoTouch.Dialog { /// <summary> /// The DialogViewController is the main entry point to use MonoTouch.Dialog, /// it provides a simplified API to the UITableViewController. /// </summary> public class DialogViewController : UITableViewController { public UITableViewStyle Style = UITableViewStyle.Grouped; public event Action<NSIndexPath> OnSelection; UISearchBar searchBar; UITableView tableView; RefreshTableHeaderView refreshView; RootElement root; bool pushing; bool dirty; bool reloading; /// <summary> /// The root element displayed by the DialogViewController, the value can be changed during runtime to update the contents. /// </summary> public RootElement Root { get { return root; } set { if (root == value) return; if (root != null) root.Dispose (); root = value; root.TableView = tableView; ReloadData (); } } EventHandler refreshRequested; /// <summary> /// If you assign a handler to this event before the view is shown, the /// DialogViewController will have support for pull-to-refresh UI. /// </summary> public event EventHandler RefreshRequested { add { if (tableView != null) throw new ArgumentException ("You should set the handler before the controller is shown"); refreshRequested += value; } remove { refreshRequested -= value; } } // If the value is true, we are enabled, used in the source for quick computation bool enableSearch; public bool EnableSearch { get { return enableSearch; } set { if (enableSearch == value) return; // After MonoTouch 3.0, we can allow for the search to be enabled/disable if (tableView != null) throw new ArgumentException ("You should set EnableSearch before the controller is shown"); enableSearch = value; } } // If set, we automatically scroll the content to avoid showing the search bar until // the user manually pulls it down. public bool AutoHideSearch { get; set; } public string SearchPlaceholder { get; set; } /// <summary> /// Invoke this method to trigger a data refresh. /// </summary> /// <remarks> /// This will invoke the RerfeshRequested event handler, the code attached to it /// should start the background operation to fetch the data and when it completes /// it should call ReloadComplete to restore the control state. /// </remarks> public void TriggerRefresh () { TriggerRefresh (false); } void TriggerRefresh (bool showStatus) { if (refreshRequested == null) return; if (reloading) return; reloading = true; if (refreshView != null) refreshView.SetActivity (true); refreshRequested (this, EventArgs.Empty); if (reloading && showStatus && refreshView != null){ UIView.BeginAnimations ("reloadingData"); UIView.SetAnimationDuration (0.2); var tableInset = TableView.ContentInset; tableInset.Top += 60; TableView.ContentInset = tableInset; UIView.CommitAnimations (); } } /// <summary> /// Invoke this method to signal that a reload has completed, this will update the UI accordingly. /// </summary> public void ReloadComplete () { if (refreshView != null) refreshView.LastUpdate = DateTime.Now; if (!reloading) return; reloading = false; if (refreshView == null) return; refreshView.SetActivity (false); refreshView.Flip (false); UIView.BeginAnimations ("doneReloading"); UIView.SetAnimationDuration (0.3f); var tableInset = TableView.ContentInset; tableInset.Top -= 60; TableView.ContentInset = tableInset; refreshView.SetStatus (RefreshViewStatus.PullToReload); UIView.CommitAnimations (); } /// <summary> /// Controls whether the DialogViewController should auto rotate /// </summary> public bool Autorotate { get; set; } public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { return Autorotate || toInterfaceOrientation == UIInterfaceOrientation.Portrait; } public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation) { base.DidRotate (fromInterfaceOrientation); //Fixes the RefreshView's size if it is shown during rotation if (refreshView != null) { var bounds = View.Bounds; refreshView.Frame = new CGRect (0, -bounds.Height, bounds.Width, bounds.Height); } ReloadData (); } Section [] originalSections; Element [][] originalElements; /// <summary> /// Allows caller to programatically activate the search bar and start the search process /// </summary> public void StartSearch () { if (originalSections != null) return; searchBar.BecomeFirstResponder (); originalSections = Root.Sections.ToArray (); originalElements = new Element [originalSections.Length][]; for (int i = 0; i < originalSections.Length; i++) originalElements [i] = originalSections [i].Elements.ToArray (); } /// <summary> /// Allows the caller to programatically stop searching. /// </summary> public virtual void FinishSearch () { if (originalSections == null) return; Root.Sections = new List<Section> (originalSections); originalSections = null; originalElements = null; searchBar.ResignFirstResponder (); ReloadData (); } public delegate void SearchTextEventHandler (object sender, SearchChangedEventArgs args); public event SearchTextEventHandler SearchTextChanged; public virtual void OnSearchTextChanged (string text) { if (SearchTextChanged != null) SearchTextChanged (this, new SearchChangedEventArgs (text)); } public void PerformFilter (string text) { if (originalSections == null) return; OnSearchTextChanged (text); var newSections = new List<Section> (); for (int sidx = 0; sidx < originalSections.Length; sidx++){ Section newSection = null; var section = originalSections [sidx]; Element [] elements = originalElements [sidx]; for (int eidx = 0; eidx < elements.Length; eidx++){ if (elements [eidx].Matches (text)){ if (newSection == null){ newSection = new Section (section.Header, section.Footer){ FooterView = section.FooterView, HeaderView = section.HeaderView }; newSections.Add (newSection); } newSection.Add (elements [eidx]); } } } Root.Sections = newSections; ReloadData (); } public virtual void SearchButtonClicked (string text) { } class SearchDelegate : UISearchBarDelegate { DialogViewController container; public SearchDelegate (DialogViewController container) { this.container = container; } public override void OnEditingStarted (UISearchBar searchBar) { searchBar.ShowsCancelButton = true; container.StartSearch (); } public override void OnEditingStopped (UISearchBar searchBar) { searchBar.ShowsCancelButton = false; container.FinishSearch (); } public override void TextChanged (UISearchBar searchBar, string searchText) { container.PerformFilter (searchText ?? ""); } public override void CancelButtonClicked (UISearchBar searchBar) { searchBar.ShowsCancelButton = false; container.searchBar.Text = ""; container.FinishSearch (); searchBar.ResignFirstResponder (); } public override void SearchButtonClicked (UISearchBar searchBar) { container.SearchButtonClicked (searchBar.Text); } } public class Source : UITableViewSource { const float yboundary = 65; protected DialogViewController Container; protected RootElement Root; bool checkForRefresh; public Source (DialogViewController container) { this.Container = container; Root = container.root; } public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath) { var section = Root.Sections [(int) indexPath.Section]; var element = (section.Elements [(int) indexPath.Row] as StyledStringElement); if (element != null) element.AccessoryTap (); } public override nint RowsInSection (UITableView tableview, nint section) { var s = Root.Sections [(int) section]; var count = s.Elements.Count; return count; } public override nint NumberOfSections (UITableView tableView) { return Root.Sections.Count; } public override string TitleForHeader (UITableView tableView, nint section) { return Root.Sections [(int) section].Caption; } public override string TitleForFooter (UITableView tableView, nint section) { return Root.Sections [(int) section].Footer; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var section = Root.Sections [(int) indexPath.Section]; var element = section.Elements [(int) indexPath.Row]; return element.GetCell (tableView); } public override void WillDisplay (UITableView tableView, UITableViewCell cell, NSIndexPath indexPath) { if (Root.NeedColorUpdate){ var section = Root.Sections [(int) indexPath.Section]; var element = section.Elements [(int) indexPath.Row]; var colorized = element as IColorizeBackground; if (colorized != null) colorized.WillDisplay (tableView, cell, indexPath); } } public override void RowDeselected (UITableView tableView, NSIndexPath indexPath) { Container.Deselected (indexPath); } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { var onSelection = Container.OnSelection; if (onSelection != null) onSelection (indexPath); Container.Selected (indexPath); } public override UIView GetViewForHeader (UITableView tableView, nint sectionIdx) { var section = Root.Sections [(int) sectionIdx]; return section.HeaderView; } public override nfloat GetHeightForHeader (UITableView tableView, nint sectionIdx) { var section = Root.Sections [(int) sectionIdx]; if (section.HeaderView == null) return -1; return section.HeaderView.Frame.Height; } public override UIView GetViewForFooter (UITableView tableView, nint sectionIdx) { var section = Root.Sections [(int) sectionIdx]; return section.FooterView; } public override nfloat GetHeightForFooter (UITableView tableView, nint sectionIdx) { var section = Root.Sections [(int) sectionIdx]; if (section.FooterView == null) return -1; return section.FooterView.Frame.Height; } #region Pull to Refresh support public override void Scrolled (UIScrollView scrollView) { if (!checkForRefresh) return; if (Container.reloading) return; var view = Container.refreshView; if (view == null) return; var point = Container.TableView.ContentOffset; if (view.IsFlipped && point.Y > -yboundary && point.Y < 0){ view.Flip (true); view.SetStatus (RefreshViewStatus.PullToReload); } else if (!view.IsFlipped && point.Y < -yboundary){ view.Flip (true); view.SetStatus (RefreshViewStatus.ReleaseToReload); } } public override void DraggingStarted (UIScrollView scrollView) { checkForRefresh = true; } public override void DraggingEnded (UIScrollView scrollView, bool willDecelerate) { if (Container.refreshView == null) return; checkForRefresh = false; if (Container.TableView.ContentOffset.Y > -yboundary) return; Container.TriggerRefresh (true); } #endregion } // // Performance trick, if we expose GetHeightForRow, the UITableView will // probe *every* row for its size; Avoid this by creating a separate // model that is used only when we have items that require resizing // public class SizingSource : Source { public SizingSource (DialogViewController controller) : base (controller) {} public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { var section = Root.Sections [(int) indexPath.Section]; var element = section.Elements [(int) indexPath.Row]; var sizable = element as IElementSizing; if (sizable == null) return (nfloat)tableView.RowHeight; return sizable.GetHeight (tableView, indexPath); } } /// <summary> /// Activates a nested view controller from the DialogViewController. /// If the view controller is hosted in a UINavigationController it /// will push the result. Otherwise it will show it as a modal /// dialog /// </summary> public void ActivateController (UIViewController controller) { dirty = true; var parent = ParentViewController; var nav = parent as UINavigationController; // We can not push a nav controller into a nav controller if (nav != null && !(controller is UINavigationController)) nav.PushViewController (controller, true); else PresentModalViewController (controller, true); } /// <summary> /// Dismisses the view controller. It either pops or dismisses /// based on the kind of container we are hosted in. /// </summary> public void DeactivateController (bool animated) { var parent = ParentViewController; var nav = parent as UINavigationController; #if XAMCORE_2_0 if (nav != null) nav.PopViewController (animated); else DismissModalViewController (animated); #else if (nav != null) nav.PopViewControllerAnimated (animated); else DismissModalViewControllerAnimated (animated); #endif } void SetupSearch () { if (enableSearch){ searchBar = new UISearchBar (new CGRect (0, 0, tableView.Bounds.Width, 44)) { Delegate = new SearchDelegate (this) }; if (SearchPlaceholder != null) searchBar.Placeholder = this.SearchPlaceholder; tableView.TableHeaderView = searchBar; } else { // Does not work with current Monotouch, will work with 3.0 // tableView.TableHeaderView = null; } } public virtual void Deselected (NSIndexPath indexPath) { var section = root.Sections [(int) indexPath.Section]; var element = section.Elements [(int) indexPath.Row]; element.Deselected (this, tableView, indexPath); } public virtual void Selected (NSIndexPath indexPath) { var section = root.Sections [(int) indexPath.Section]; var element = section.Elements [(int) indexPath.Row]; element.Selected (this, tableView, indexPath); } public virtual UITableView MakeTableView (CGRect bounds, UITableViewStyle style) { return new UITableView (bounds, style); } public override void LoadView () { tableView = MakeTableView (UIScreen.MainScreen.Bounds, Style); tableView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin; tableView.AutosizesSubviews = true; if (root != null) root.Prepare (); UpdateSource (); View = tableView; SetupSearch (); ConfigureTableView (); if (root == null) return; root.TableView = tableView; } void ConfigureTableView () { if (refreshRequested != null){ // The dimensions should be large enough so that even if the user scrolls, we render the // whole are with the background color. var bounds = View.Bounds; refreshView = MakeRefreshTableHeaderView (new CGRect (0, -bounds.Height, bounds.Width, bounds.Height)); if (reloading) refreshView.SetActivity (true); TableView.AddSubview (refreshView); } } public virtual RefreshTableHeaderView MakeRefreshTableHeaderView (CGRect rect) { return new RefreshTableHeaderView (rect); } public event EventHandler ViewAppearing; public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); if (AutoHideSearch){ if (enableSearch){ if (TableView.ContentOffset.Y < 44) TableView.ContentOffset = new CGPoint (0, 44); } } if (root == null) return; root.Prepare (); NavigationItem.HidesBackButton = !pushing; if (root.Caption != null) NavigationItem.Title = root.Caption; if (dirty){ tableView.ReloadData (); dirty = false; } if (ViewAppearing != null) ViewAppearing (this, EventArgs.Empty); } public bool Pushing { get { return pushing; } set { pushing = value; if (NavigationItem != null) NavigationItem.HidesBackButton = !pushing; } } public virtual Source CreateSizingSource (bool unevenRows) { return unevenRows ? new SizingSource (this) : new Source (this); } Source TableSource; void UpdateSource () { if (root == null) return; TableSource = CreateSizingSource (root.UnevenRows); tableView.Source = TableSource; } public void ReloadData () { if (root == null) return; if(root.Caption != null) NavigationItem.Title = root.Caption; root.Prepare (); if (tableView != null){ UpdateSource (); tableView.ReloadData (); } dirty = false; } public event EventHandler ViewDisappearing; [Obsolete ("Use the ViewDisappearing event instead")] public event EventHandler ViewDissapearing { add { ViewDisappearing += value; } remove { ViewDisappearing -= value; } } public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); if (ViewDisappearing != null) ViewDisappearing (this, EventArgs.Empty); } public DialogViewController (RootElement root) : base (UITableViewStyle.Grouped) { this.root = root; } public DialogViewController (UITableViewStyle style, RootElement root) : base (style) { Style = style; this.root = root; } /// <summary> /// Creates a new DialogViewController from a RootElement and sets the push status /// </summary> /// <param name="root"> /// The <see cref="RootElement"/> containing the information to render. /// </param> /// <param name="pushing"> /// A <see cref="System.Boolean"/> describing whether this is being pushed /// (NavigationControllers) or not. If pushing is true, then the back button /// will be shown, allowing the user to go back to the previous controller /// </param> public DialogViewController (RootElement root, bool pushing) : base (UITableViewStyle.Grouped) { this.pushing = pushing; this.root = root; } public DialogViewController (UITableViewStyle style, RootElement root, bool pushing) : base (style) { Style = style; this.pushing = pushing; this.root = root; } public DialogViewController (IntPtr handle) : base(handle) { this.root = new RootElement (""); } } }
// // CollectionIndexer.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using NDesk.DBus; using Hyena.Query; using Hyena.Data.Sqlite; using Banshee.Library; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Collection.Database; namespace Banshee.Collection.Indexer { [DBusExportable (ServiceName = "CollectionIndexer")] public class CollectionIndexerService : ICollectionIndexerService, IDBusExportable, IDisposable { private List<LibrarySource> libraries = new List<LibrarySource> (); private string [] available_export_fields; private int open_indexers; public event ActionHandler CollectionChanged; public event ActionHandler CleanupAndShutdown; private ActionHandler shutdown_handler; public ActionHandler ShutdownHandler { get { return shutdown_handler; } set { shutdown_handler = value; } } public CollectionIndexerService () { DBusConnection.Connect ("CollectionIndexer"); ServiceManager.SourceManager.SourceAdded += OnSourceAdded; ServiceManager.SourceManager.SourceRemoved += OnSourceRemoved; foreach (Source source in ServiceManager.SourceManager.Sources) { MonitorLibrary (source as LibrarySource); } } public void Dispose () { while (libraries.Count > 0) { UnmonitorLibrary (libraries[0]); } } void ICollectionIndexerService.Hello () { Hyena.Log.DebugFormat ("Hello called on {0}", GetType ()); } public void Shutdown () { lock (this) { if (open_indexers == 0 && shutdown_handler != null) { shutdown_handler (); } } } public void ForceShutdown () { Dispose (); if (shutdown_handler != null) { shutdown_handler (); } } public ICollectionIndexer CreateIndexer () { lock (this) { return new CollectionIndexer (null); } } internal void DisposeIndexer (CollectionIndexer indexer) { lock (this) { ServiceManager.DBusServiceManager.UnregisterObject (indexer); open_indexers--; } } ObjectPath ICollectionIndexerService.CreateIndexer () { lock (this) { ObjectPath path = ServiceManager.DBusServiceManager.RegisterObject (new CollectionIndexer (this)); open_indexers++; return path; } } public bool HasCollectionCountChanged (int count) { lock (this) { int total_count = 0; foreach (LibrarySource library in libraries) { total_count += library.Count; } return count != total_count; } } public bool HasCollectionLastModifiedChanged (long time) { lock (this) { long last_updated = 0; foreach (LibrarySource library in libraries) { last_updated = Math.Max (last_updated, ServiceManager.DbConnection.Query<long> ( String.Format ("SELECT MAX(CoreTracks.DateUpdatedStamp) {0}", library.DatabaseTrackModel.UnfilteredQuery))); } return last_updated > time; } } public string [] GetAvailableExportFields () { lock (this) { if (available_export_fields != null) { return available_export_fields; } List<string> fields = new List<string> (); foreach (KeyValuePair<string, System.Reflection.PropertyInfo> field in TrackInfo.GetExportableProperties ( typeof (Banshee.Collection.Database.DatabaseTrackInfo))) { fields.Add (field.Key); } available_export_fields = fields.ToArray (); return available_export_fields; } } private void MonitorLibrary (LibrarySource library) { if (library == null || !library.Indexable || libraries.Contains (library)) { return; } libraries.Add (library); library.TracksAdded += OnLibraryChanged; library.TracksDeleted += OnLibraryChanged; library.TracksChanged += OnLibraryChanged; } private void UnmonitorLibrary (LibrarySource library) { if (library == null || !libraries.Contains (library)) { return; } library.TracksAdded -= OnLibraryChanged; library.TracksDeleted -= OnLibraryChanged; library.TracksChanged -= OnLibraryChanged; libraries.Remove (library); } private void OnSourceAdded (SourceAddedArgs args) { MonitorLibrary (args.Source as LibrarySource); } private void OnSourceRemoved (SourceEventArgs args) { UnmonitorLibrary (args.Source as LibrarySource); } private void OnLibraryChanged (object o, TrackEventArgs args) { if (args.ChangedFields == null) { OnCollectionChanged (); return; } foreach (Hyena.Query.QueryField field in args.ChangedFields) { if (field != Banshee.Query.BansheeQuery.LastPlayedField && field != Banshee.Query.BansheeQuery.LastSkippedField && field != Banshee.Query.BansheeQuery.PlayCountField && field != Banshee.Query.BansheeQuery.SkipCountField) { OnCollectionChanged (); return; } } } public void RequestCleanupAndShutdown () { ActionHandler handler = CleanupAndShutdown; if (handler != null) { handler (); } } private void OnCollectionChanged () { ActionHandler handler = CollectionChanged; if (handler != null) { handler (); } } IDBusExportable IDBusExportable.Parent { get { return null; } } string IService.ServiceName { get { return "CollectionIndexerService"; } } } }
/* Date : Monday, June 13, 2016 Author : pdcdeveloper (https://github.com/pdcdeveloper) Objective : Implements the complete OAuth installed flow for any of Google's services, automatically manages use of a user's refresh token and revocation requests to Google. Version : 1.0 */ using Newtonsoft.Json; using QPGoogleAPI.OAuth.Models; using QPLib.Base; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Windows.Security.Authentication.Web; using Windows.Security.Credentials; using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Media.Imaging; using Windows.Web.Http; using Windows.Web.Http.Headers; namespace QPGoogleAPI.OAuth.Flows { /// /// <summary> /// Implements the complete OAuth installed flow for any of Google's services, automatically manages /// use of a user's refresh token and revocation requests to Google. /// </summary> /// /// /// <remarks> /// /// Stores multiple users, with the first user within the vault as the default user. /// /// Storing tokens (securely): /// <see cref="https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.passwordvault.aspx"/> /// <see cref="https://msdn.microsoft.com/en-us/library/windows/apps/hh701231.aspx"/> /// <see cref="https://stackoverflow.com/questions/9052482/best-practice-for-saving-sensitive-data-in-windows-8"/> /// /// General information on Google's OAuth implementation (DO NOT use the Windows 8.1 example code): /// <see cref="https://developers.google.com/youtube/v3/guides/auth/installed-apps"/> /// /// The classes that support OAuth2 for WinRT: /// <see cref="https://msdn.microsoft.com/windows/uwp/security/web-authentication-broker"/> /// <see cref="https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.authentication.web.aspx"/> /// <see cref="https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.security.authentication.web.webauthenticationbroker.aspx"/> /// <see cref="https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.security.authentication.web.webauthenticationresult.aspx"/> /// /// DO NOT USE THE EXAMPLES FROM THIS DOCUMENT!!! /// <donotsee cref="https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#user-credentials"/> /// /// /// /// Extremely helpful post about... POST - authorized token exchange: /// <see cref="https://stackoverflow.com/questions/15176538/net-httpclient-how-to-post-string-value"/> /// /// /// /// /// How PasswordCredential is stored: /// PasswordCredential.UserName = "PlusPersonResponse.DisplayName,PlusPersonResponse.Id,PlusPersonResponse.ProfileImageUrl" /// PasswordCredential.Resource = "APP_NAME,TokenResponse.TokenType" /// PasswordCredential.Password = "TokenResponse.AccessToken,TokenResponse.RefreshToken,TokenResponse.ExpiresIn.ToString(),DateTime.UtcNow.ToString()" /// /// /// This entire class is centered around the PasswordCredential, which makes the overall design very hack-ish. /// /// /// </remarks> /// /// /// <updates> /// /// Update 2016-06-01: /// Added retry attempts within TryExchangeForAccessTokenAsync(). /// /// Update 2016-06-13: /// Currently, only asks for YouTube, Profile and Email scopes. /// /// Update 2016-06-27: /// Consolidated preperation of AuthorizedUser to PasswordCredential and /// PasswordCredential to AuthorizedUser. /// /// </updates> /// public class OAuthInstalledFlow : NotifyPropertyChangedBase { static readonly string APP_NAME = Application.Current.ToString(); // // Installed secrets path // const string INSTALLED_FLOW_SECRETS_PATH = @"ms-appx:///client_secret.json"; // // Scopes // const string YOUTUBE_SCOPE = @"https://www.googleapis.com/auth/youtube.force-ssl"; // UserInfoResponse: // GET https://www.googleapis.com/userinfo/v2/me // or // GET https://www.googleapis.com/oauth2/v2/userinfo // // PlusPersonResponse: // GET https://www.googleapis.com/plus/v1/people/me // // Currently using UserInfoResponse rest api call. // const string PROFILE_SCOPE = @"https://www.googleapis.com/auth/userinfo.profile"; const string EMAIL_SCOPE = @"https://www.googleapis.com/auth/userinfo.email"; // Uses the same api call as PROFILE_SCOPE // // Space delimited // const string AUTHENTICATION_SCOPES = YOUTUBE_SCOPE + @" " + PROFILE_SCOPE + @" " + EMAIL_SCOPE; #region rest api calls // // Revocation -- requires the token parameter // const string REVOCATION_API_URL = @"https://accounts.google.com/o/oauth2/revoke?token="; // // User info, such as name and profile image -- requires a bearer token in the auth header of the GET request. // Use with either PROFILE_SCOPE or EMAIL_SCOPE. // const string USER_INFO_API_URL = @"https://www.googleapis.com/oauth2/v2/userinfo"; #endregion // // Makes it easier for the view and gets rid of repetitive checks // static BitmapImage _profileImage = null; public BitmapImage ProfileImage { get { if (AuthorizedUser != null) { _profileImage.DecodePixelHeight = 50; _profileImage.DecodePixelWidth = 50; return _profileImage; } return null; } set { _profileImage = value; OnPropertyChanged(); } } static AuthorizedUser _authorizedUser = null; [DisplayAttribute(Name = "AuthorizedUser")] public AuthorizedUser AuthorizedUser { get { if (_authorizedUser != null) return _authorizedUser; // // Call this setter to invoke a property change. // This is optional, otherwise you would explicitly return null. // // //AuthorizedUser = TryGetDefaultAuthorizedUser(); // loop detected //return _authorizedUser; return null; } set { _authorizedUser = value; // // Property changed event for profile image // if (value != null && !string.IsNullOrEmpty(value.ProfileImageUrl)) ProfileImage = new BitmapImage(new Uri(value.ProfileImageUrl, UriKind.Absolute)); else ProfileImage = null; OnPropertyChanged(); OnSingletonPropertyChanged(); } } AuthorizedUser TryGetDefaultAuthorizedUser() { //if (_authorizedUser != null) // return _authorizedUser; // // Try to get the default user from the vault // PasswordVault vault = new PasswordVault(); PasswordCredential cred = null; IReadOnlyList<PasswordCredential> credentials = vault.RetrieveAll(); if (credentials != null && credentials.Count > 0) { cred = credentials.First(); } // // Break // if (cred == null) return null; #region v1 //// //// Prep a new user //// //AuthorizedUser user = new AuthorizedUser(); //// //// Password //// //cred.RetrievePassword(); //if (!string.IsNullOrEmpty(cred.Password)) //{ // user.AccessToken = cred.Password.Split(',').ElementAt(0); // user.RefreshToken = cred.Password.Split(',').ElementAt(1); // user.ExpiresIn = int.Parse(cred.Password.Split(',').ElementAt(2)); // user.DateAcquiredUtc = DateTime.Parse(cred.Password.Split(',').ElementAt(3)); //} //// //// Resource //// //if (!string.IsNullOrEmpty(cred.Resource) && cred.Resource.Split(',').ElementAt(0).Contains(APP_NAME)) //{ // user.TokenType = cred.Resource.Split(',').ElementAt(1); //} //var s = cred.Resource.Split(','); //if (s.Length > 2) // user.Email = cred.Resource.Split(',').ElementAt(2); //// //// UserName //// //if (!string.IsNullOrEmpty(cred.UserName)) //{ // user.DisplayName = cred.UserName.Split(',').ElementAt(0); // user.Id = cred.UserName.Split(',').ElementAt(1); // user.ProfileImageUrl = cred.UserName.Split(',').ElementAt(2); //} #endregion #region v2 AuthorizedUser user = this.PasswordCredentialToAuthorizedUser(cred); #endregion // // // return user; } #region public functionality public async Task LoginAsync() { // // Ask the user to authenticate by bringing up the web view // string authorizationToken = await this.TryGetAuthorizationTokenAsync(); if (string.IsNullOrEmpty(authorizationToken)) return; // // Exchange authorization token for access and refresh tokens // PasswordCredential credential = await this.TryExchangeForAccessTokenAsync(authorizationToken); // // Break // if (credential == null) return; // // Check if the user already exists before storing in the vault. // Always compare by id, never by name. // PasswordVault vault = new PasswordVault(); #region v1 //IReadOnlyList<PasswordCredential> credentials = null; //if (!string.IsNullOrEmpty(credential.UserName)) //{ // string id = credential.UserName.Split(',').ElementAt(1); // credentials = vault.RetrieveAll(); // if (credentials != null && credentials.Count > 0) // foreach (var cred in credentials) // { // if (string.IsNullOrEmpty(cred.UserName)) // continue; // // // // UserInfo // // // string credId = cred.UserName.Split(',').ElementAt(1); // if (credId == id) // { // cred.RetrievePassword(); // string accessToken = cred.Password.Split(',').ElementAt(0); // // // // Revoke, remove from the vault, and from the view, if applicable // // // await this.RevokeTokensAsync(accessToken); // break; // } // } //} #endregion #region v2 bool userExists = await this.TryRemoveExistingUser(credential); // the return value is currently unused #if DEBUG if (userExists) Debug.WriteLine("Duplicate user removed from the password vault."); #endif #endregion // // Store the credential // vault.Add(credential); // // Fill out a new authorized user // #region v1 //AuthorizedUser user = new AuthorizedUser(); //// //// Password //// //user.AccessToken = credential.Password.Split(',').ElementAt(0); //user.RefreshToken = credential.Password.Split(',').ElementAt(1); //user.ExpiresIn = int.Parse(credential.Password.Split(',').ElementAt(2)); //user.DateAcquiredUtc = DateTime.Parse(credential.Password.Split(',').ElementAt(3)); //// //// Resource //// //user.TokenType = credential.Resource.Split(',').ElementAt(1); //var s = credential.Resource.Split(','); //if (s.Length > 2) // user.Email = credential.Resource.Split(',').ElementAt(2); //// //// UserName //// //if (!string.IsNullOrEmpty(credential.UserName)) //{ // user.DisplayName = credential.UserName.Split(',').ElementAt(0); // user.Id = credential.UserName.Split(',').ElementAt(1); // user.ProfileImageUrl = credential.UserName.Split(',').ElementAt(2); //} #endregion #region v2 AuthorizedUser user = this.PasswordCredentialToAuthorizedUser(credential); #endregion // // Update the view // AuthorizedUser = user; } public async Task LogoutAsync(PasswordCredential credential) { if (credential == null) return; credential.RetrievePassword(); if (string.IsNullOrEmpty(credential.Password)) return; string accessToken = credential.Password.Split(',').ElementAt(0); // // Revoke the token, remove from the vault and from the view, if applicable // await this.RevokeTokensAsync(accessToken); } // // Implicitly log out the current authorized user // public async Task LogoutAsync() { if (_authorizedUser == null) return; // // Find the current authorized user // PasswordVault vault = new PasswordVault(); IReadOnlyList<PasswordCredential> credentials = vault.RetrieveAll(); if (credentials != null && credentials.Count > 0) { // // Try revoking by id // if (!string.IsNullOrEmpty(_authorizedUser.Id)) foreach (var cred in credentials) { if (string.IsNullOrEmpty(cred.UserName)) continue; string credId = cred.UserName.Split(',').ElementAt(1); if (credId == _authorizedUser.Id) { await this.RevokeTokensAsync(_authorizedUser.RefreshToken); return; } } // // Try revoking by refresh token // if (!string.IsNullOrEmpty(_authorizedUser.RefreshToken)) foreach (var cred in credentials) { cred.RetrievePassword(); string credRefresh = cred.Password.Split(',').ElementAt(1); if (credRefresh == _authorizedUser.RefreshToken) { await this.RevokeTokensAsync(_authorizedUser.RefreshToken); return; } } } } // // The parameter that is most likely to be passed in is // this.AuthorizedUser. // public async Task UseRefreshToken(AuthorizedUser user) { if (user == null) return; if (string.IsNullOrEmpty(user.RefreshToken) || user.DateAcquiredUtc == null) return; // // // InstalledFlowSecrets secrets = await GetInstalledFlowSecretsAsync(); PasswordVault vault = new PasswordVault(); IReadOnlyList<PasswordCredential> credentials = null; OAuthTokenResponse oauthTokens = null; // // // using (HttpClient client = new HttpClient()) { Uri tokenUri = new Uri(secrets.Installed.TokenUri, UriKind.Absolute); // // Create POST content // Dictionary<string, string> content = new Dictionary<string, string>(); content.Add("client_id", secrets.Installed.ClientId); content.Add("client_secret", secrets.Installed.ClientSecret); content.Add("refresh_token", user.RefreshToken); content.Add("grant_type", "refresh_token"); // state parameter is not allowed // // Url encode the content // HttpFormUrlEncodedContent body = new HttpFormUrlEncodedContent(content); // // Send a POST request with the content body // HttpResponseMessage refreshResponse = await client.PostAsync(tokenUri, body); // // Break -- the token was probably revoked from outside this application // if (refreshResponse == null || !refreshResponse.IsSuccessStatusCode) { // // Revoke the user from the service, then remove from the vault and from the view, if applicable. // Although you will get a bad request if the refresh token has already been revoked, the credential // will still be scrubbed away. // await this.RevokeTokensAsync(user.RefreshToken); return; } // // Deserialize the JSON content // string jsonRefreshText = await refreshResponse.Content.ReadAsStringAsync(); oauthTokens = JsonConvert.DeserializeObject<OAuthTokenResponse>(jsonRefreshText); } // // Refresh the credential within the vault with a new PasswordCredential // #region v1 //PasswordCredential credential = new PasswordCredential(); //DateTime dateAcquiredUtc = DateTime.UtcNow; //// //// Password //// //credential.Password // = oauthTokens.AccessToken // + ',' + user.RefreshToken // + ',' + oauthTokens.ExpiresIn.ToString() // + ',' + dateAcquiredUtc.ToString(); //// //// Resource //// //credential.Resource // = APP_NAME // + ',' + oauthTokens.TokenType; //// //// //// //if (!string.IsNullOrEmpty(user.Email)) // credential.Resource += ',' + user.Email; //// //// UserName //// //if (!string.IsNullOrEmpty(user.DisplayName)) //{ // credential.UserName // = user.DisplayName // + ',' + user.Id // + ',' + user.ProfileImageUrl; //} #endregion #region v2 PasswordCredential credential = this.AuthorizedUserToPasswordCredential(user, oauthTokens); #endregion // // Find the credential in the vault and remove it before adding its replacement // credentials = vault.RetrieveAll(); if (credentials != null && credentials.Count > 0) foreach (var cred in credentials) { cred.RetrievePassword(); if (!string.IsNullOrEmpty(cred.Password)) if (cred.Password.Contains(user.RefreshToken)) { //#if DEBUG // Debug.WriteLine(Environment.NewLine); // Debug.WriteLine("Credential being updated:"); // Debug.WriteLine(cred.Password.Split(',').ElementAt(0)); // Debug.WriteLine(cred.Password.Split(',').ElementAt(1)); // Debug.WriteLine(cred.Password.Split(',').ElementAt(2)); // Debug.WriteLine(cred.Password.Split(',').ElementAt(3)); // Debug.WriteLine(Environment.NewLine); //#endif vault.Remove(cred); break; } } // // // vault.Add(credential); //#if DEBUG // credentials = vault.RetrieveAll(); // if (credentials != null && credentials.Count > 0) // foreach (var cred in credentials) // { // cred.RetrievePassword(); // if (!string.IsNullOrEmpty(cred.Password)) // if (cred.Password.Contains(user.RefreshToken)) // { // Debug.WriteLine(Environment.NewLine); // Debug.WriteLine("Checking if the credential has been updated:"); // Debug.WriteLine(cred.Password.Split(',').ElementAt(0)); // Debug.WriteLine(cred.Password.Split(',').ElementAt(1)); // Debug.WriteLine(cred.Password.Split(',').ElementAt(2)); // Debug.WriteLine(cred.Password.Split(',').ElementAt(3)); // Debug.WriteLine(Environment.NewLine); // break; // } // } //#endif // // Refresh _authorizedUser, if applicable // #region v1 //if (_authorizedUser != null && _authorizedUser.RefreshToken == user.RefreshToken) //{ // // // // The view gets updated implicitly -- AuthorizedUser implements NotifyPropertyChangedBase for each of its properties // // // _authorizedUser.AccessToken = oauthTokens.AccessToken; // _authorizedUser.ExpiresIn = oauthTokens.ExpiresIn; // _authorizedUser.TokenType = oauthTokens.TokenType; // _authorizedUser.DateAcquiredUtc = dateAcquiredUtc; //} #endregion #region v2 AuthorizedUser = this.PasswordCredentialToAuthorizedUser(credential); #endregion #if DEBUG Debug.WriteLine("AuthorizedUser has been refreshed."); #endif } // // Alternate version // public async Task UseRefreshToken(PasswordCredential credential) { // // To do: // Build a AuthorizedUser object from the Password credential, // then call the overload. // // // Untested // await this.UseRefreshToken(this.PasswordCredentialToAuthorizedUser(credential)); } // // Change the user by passing in a credential from the vault. // You can also use this method to set the default user when the application launches. // public void ChangeUser(PasswordCredential credential) { if (credential == null) return; credential.RetrievePassword(); if (string.IsNullOrEmpty(credential.Password)) return; // // Check if the credential is in the vault // PasswordVault vault = new PasswordVault(); IReadOnlyList<PasswordCredential> credentials = vault.RetrieveAll(); if (credentials != null && credentials.Count > 0) foreach (var cred in credentials) { string refreshToken = credential.Password.Split(',').ElementAt(1); cred.RetrievePassword(); if (cred.Password.Contains(refreshToken)) break; else if (cred == credentials.Last()) return; else continue; } else return; // // Build an AuthorizedUser // #region v1 //AuthorizedUser user = new AuthorizedUser(); //// //// Password //// //user.AccessToken = credential.Password.Split(',').ElementAt(0); //user.RefreshToken = credential.Password.Split(',').ElementAt(1); //user.ExpiresIn = int.Parse(credential.Password.Split(',').ElementAt(2)); //user.DateAcquiredUtc = DateTime.Parse(credential.Password.Split(',').ElementAt(3)); //// //// Resource //// //user.TokenType = credential.Resource.Split(',').ElementAt(1); //// //var s = credential.Resource.Split(','); //if (s.Length > 2) // user.Email = credential.Resource.Split(',').ElementAt(2); //// //// UserName //// //if (!string.IsNullOrEmpty(credential.UserName)) //{ // user.DisplayName = credential.UserName.Split(',').ElementAt(0); // user.Id = credential.UserName.Split(',').ElementAt(1); // user.ProfileImageUrl = credential.UserName.Split(',').ElementAt(2); //} #endregion #region v2 AuthorizedUser user = this.PasswordCredentialToAuthorizedUser(credential); #endregion // // Change the user to propagate property changes // AuthorizedUser = user; } // // Uninstall scenario or if user wants to clear all previous credentials // from both the service and the vault. // public async Task RevokeAllTokensAndClearVaultAsync() { PasswordVault vault = new PasswordVault(); IReadOnlyList<PasswordCredential> credentials = vault.RetrieveAll(); string[] tokens; if (credentials != null && credentials.Count > 0) { tokens = new string[credentials.Count]; for (int i = 0; i < credentials.Count; i++) { credentials[i].RetrievePassword(); tokens[i] = credentials[i].Password.Split(',').ElementAt(0); } } else // // Break -- there is nothing to revoke // return; // // Break -- something went wrong when building the array // if (tokens == null) return; if (tokens.Length < 1) return; // // Revoke, then remove each token from the vault // await this.RevokeTokensAsync(tokens); } #endregion #region helpers public virtual string AccessTokenHelper() { if (AuthorizedUser != null) return AuthorizedUser.AccessToken; return null; } public virtual async Task RefreshTokenHelper() { if (AuthorizedUser != null) if (AuthorizedUser.IsAccessTokenExpired) await UseRefreshToken(AuthorizedUser); } public virtual async Task RefreshTokenHelper(bool forceRefresh) { if (AuthorizedUser != null) if (AuthorizedUser.IsAccessTokenExpired || forceRefresh) await UseRefreshToken(AuthorizedUser); } #endregion #region developer console static InstalledFlowSecrets _developerSecrets = null; async Task<InstalledFlowSecrets> GetInstalledFlowSecretsAsync() { if (_developerSecrets != null) return _developerSecrets; InstalledFlowSecrets secrets = null; Uri secretsPath = new Uri(INSTALLED_FLOW_SECRETS_PATH); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(secretsPath); // // JSON // string jsonText = await FileIO.ReadTextAsync(file); secrets = JsonConvert.DeserializeObject<InstalledFlowSecrets>(jsonText); // // // _developerSecrets = secrets; return _developerSecrets; } #endregion #region authentication && authorization // // Returns an authentication token, which will be consumed by TryExchangeForAccessTokensAsync(string). // This will bring up a web view. // // <see cref="https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/WebAuthenticationBroker/cs/Scenario4_Google.xaml.cs"/> // async Task<string> TryGetAuthorizationTokenAsync() { InstalledFlowSecrets secrets = await this.GetInstalledFlowSecretsAsync(); // // Configure state parameter to prevent XSS // Random random = new Random((int)DateTime.UtcNow.TimeOfDay.TotalMilliseconds); int state = 0; for (int i = 0; i < DateTime.UtcNow.TimeOfDay.Seconds; i++) state = random.Next(); // // Build the start url for web auth broker // string startUrl = secrets.Installed.AuthUri + "?client_id=" + Uri.EscapeDataString(secrets.Installed.ClientId) + "&redirect_uri=" + Uri.EscapeDataString(secrets.Installed.RedirectUris[0]) + "&response_type=code" + "&scope=" + Uri.EscapeDataString(AUTHENTICATION_SCOPES) + "&state=" + Uri.EscapeDataString(state.ToString()); // // Build the end url for the web auth broker. // The success parameters are appended to the end of this url, // which allows the application to seamlessly get the authorization // token without asking the user to copy and paste. // string endUrl = @"https://accounts.google.com/o/oauth2/approval?"; // // // Uri startUri = new Uri(startUrl, UriKind.Absolute); Uri endUri = new Uri(endUrl, UriKind.Absolute); try { // // Bring up the web view for the user to authenticate to the service // WebAuthenticationResult authResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, startUri, endUri); switch (authResult.ResponseStatus) { case WebAuthenticationStatus.Success: // // ResponseData example: "Success state=1676265812&code=4/c-kI5b5jVGl_NSw7JYmrAmG1h-vH_sY_hJ5FKrbRplA" // ////// Assumes the state parameter will always come before the code parameter. // // // Check the state parameter to prevent XSS. // Update 2016-06-07 // +Regex improved. // //Match s = Regex.Match(authResult.ResponseData, @"(?<=state\x3D).*?(?=\x26)"); Match s = Regex.Match(authResult.ResponseData, @"((?<=state\x3D).*?(?=\x26))|((?<=state\x3D).*)"); // the more specific regex should be evaluated first if (s.Success) { if (s.Value != state.ToString()) { #if DEBUG Debug.WriteLine("state (" + state.ToString() + ")"); Debug.WriteLine("s.Value (" + s.Value.ToString() + ")"); #endif throw new Exception("State parameter does not match. Beware XSS."); } // // Get the authorization token // //Match m = Regex.Match(authResult.ResponseData, @"(?<=code\x3D).*"); Match m = Regex.Match(authResult.ResponseData, @"((?<=code\x3D).*?(?=\x26))|((?<=code\x3D).*)"); // the more specific regex should be evaluated first if (m.Success) return m.Value; else throw new Exception("Could not get the authorization token code parameter from ResponseData."); } else { // // Do not continue any further // throw new Exception("Could not get state parameter from ResponseData."); } case WebAuthenticationStatus.ErrorHttp: case WebAuthenticationStatus.UserCancel: return null; } // // Fall through // return null; } catch (Exception ex) { #if DEBUG Debug.WriteLine("TryGetAuthorizationTokenAsync: something went wrong."); Debug.WriteLine(ex.Message); #endif return null; } } // // A user must obtain an authorization token by authenticating to the service before // exchanging the token for access and refresh tokens. // // It's up to the login function to add the PasswordCredential to the vault // and to fill out a new AuthorizedUser. The reason why the the vault is not // opened here is to allow the log in function to check if the user already exists. // async Task<PasswordCredential> TryExchangeForAccessTokenAsync(string authorizationToken) { if (string.IsNullOrEmpty(authorizationToken)) return null; InstalledFlowSecrets secrets = await this.GetInstalledFlowSecretsAsync(); PasswordCredential credential = new PasswordCredential(); // // Use the authorization token to build up responses to fill out a PasswordCredential // OAuthTokenResponse oauthTokens = null; UserInfoResponse userInfo = null; using (HttpClient client = new HttpClient()) { #region authorization Uri tokenUri = new Uri(secrets.Installed.TokenUri, UriKind.Absolute); // // Create POST content // Dictionary<string, string> content = new Dictionary<string, string>(); content.Add("code", authorizationToken); content.Add("client_id", secrets.Installed.ClientId); content.Add("client_secret", secrets.Installed.ClientSecret); content.Add("redirect_uri", secrets.Installed.RedirectUris[0]); content.Add("grant_type", "authorization_code"); // // Url encode the content // HttpFormUrlEncodedContent body = new HttpFormUrlEncodedContent(content); // // Send a POST request with the content body // HttpResponseMessage tokenResponse = null;// = await client.PostAsync(tokenUri, body); // // Retry // int retryCount = 2; while ((tokenResponse == null || !tokenResponse.IsSuccessStatusCode) & retryCount-- > 1) // disable short circuit with single ampersand { #if DEBUG if (retryCount != 1) Debug.WriteLine("Retrying tokenResponse = await client.PostAsync(tokenUri, body)..."); #endif tokenResponse = await client.PostAsync(tokenUri, body); //--retryCount; // use post decrement check } // // Break // if (tokenResponse == null || !tokenResponse.IsSuccessStatusCode) return null; // // Deserialize the JSON result for the oauth tokens // string jsonTokens = await tokenResponse.Content.ReadAsStringAsync(); oauthTokens = JsonConvert.DeserializeObject<OAuthTokenResponse>(jsonTokens); // // Break // if (oauthTokens == null) return null; #endregion #region userinfo Uri userInfoUri = new Uri(USER_INFO_API_URL, UriKind.Absolute); // // Auth scheme "Bearer" // HttpCredentialsHeaderValue authHeader = new HttpCredentialsHeaderValue("Bearer", oauthTokens.AccessToken); client.DefaultRequestHeaders.Authorization = authHeader; // // Send a GET request // HttpResponseMessage userInfoResponse = null;// await client.GetAsync(userInfoUri); // // Retry // retryCount = 2; while ((userInfoResponse == null || !userInfoResponse.IsSuccessStatusCode) & retryCount-- > 1) // disable short circuit with single ampersand { #if DEBUG if (retryCount != 1) Debug.WriteLine("Retrying userInfoResponse = await client.GetAsync(userInfoUri)..."); #endif userInfoResponse = await client.GetAsync(userInfoUri); //--retryCount; // use post decrement check } if (userInfoResponse != null && userInfoResponse.IsSuccessStatusCode) { string jsonUserInfo = await userInfoResponse.Content.ReadAsStringAsync(); userInfo = JsonConvert.DeserializeObject<UserInfoResponse>(jsonUserInfo); } #endregion #region v1 //// //// Start building the PasswordCredential //// //// //// Resource //// //credential.Resource // = APP_NAME // + ',' + oauthTokens.TokenType; //// //// Password //// //credential.Password // = oauthTokens.AccessToken // + ',' + oauthTokens.RefreshToken // + ',' + oauthTokens.ExpiresIn.ToString() // + ',' + DateTime.UtcNow.ToString(); //// //// Finish the prep on the PasswordCredential //// //if (userInfoResponse != null && userInfoResponse.IsSuccessStatusCode) //{ // string jsonUserInfo = await userInfoResponse.Content.ReadAsStringAsync(); // userInfo = JsonConvert.DeserializeObject<UserInfoResponse>(jsonUserInfo); // if (userInfo != null) // { // // // // UserName // // // credential.UserName // = userInfo.GivenName // + ',' + userInfo.Id // + ',' + userInfo.Picture; // // // // Email // // // if (!string.IsNullOrEmpty(userInfo.Email)) // credential.Resource += ',' + userInfo.Email; // } //} #endregion #region v2 //if (oauthTokens != null) // not necessary this.ResponseToPasswordCredential(oauthTokens, ref credential); if (userInfo != null) this.ResponseToPasswordCredential(userInfo, ref credential); #endregion } // // Break // //credential.RetrievePassword(); //if (string.IsNullOrEmpty(credential.Password)) // return null; return credential; } #endregion #region revocation /// /// <summary> /// Revocate by passing in access or refresh tokens. This also removes /// the credential within the vault, if found, and also updates /// AuthorizedUser, if applicable. /// </summary> /// /// /// <remarks> /// /// Send a GET request with either a refresh token or an access token. /// The associated refresh token is also removed if an access token is revoked. /// /// Success response status code is 200. /// Error response status code is 400. /// /// </remarks> /// async Task RevokeTokensAsync(params string[] tokens) { if (tokens?.Length < 1) return; // // Revoking the token from the service should also remove the token // from the vault. // PasswordVault vault = new PasswordVault(); IReadOnlyList<PasswordCredential> credentials = null; // // // using (HttpClient client = new HttpClient()) foreach (string token in tokens) { // // Append the token to the revocation url // Uri revokeUri = new Uri(REVOCATION_API_URL + token); // // Send the revocation request // HttpResponseMessage response = await client.GetAsync(revokeUri); // // Check the status code. // 400 status code typically means the user manually revoked the token // using the service's account management. // if (response.StatusCode == HttpStatusCode.BadRequest) { // // Not much to do here... // #if DEBUG Debug.WriteLine("This token has already been revoked."); #endif } // // Check if the token is stored in the vault and remove // the credential if it is found. // credentials = vault.RetrieveAll(); if (credentials?.Count > 0) foreach (var cred in credentials) { cred.RetrievePassword(); if (cred.Password.Contains(token)) { vault.Remove(cred); break; } } // // Check if the token is the current authorized user // if (AuthorizedUser != null && (!string.IsNullOrEmpty(AuthorizedUser.AccessToken) || !string.IsNullOrEmpty(AuthorizedUser.RefreshToken))) if (token == AuthorizedUser.AccessToken || token == AuthorizedUser.RefreshToken) { AuthorizedUser.AccessToken = string.Empty; AuthorizedUser.DateAcquiredUtc = new DateTime(); AuthorizedUser.DisplayName = string.Empty; AuthorizedUser.ExpiresIn = 0; AuthorizedUser.Id = string.Empty; AuthorizedUser.ProfileImageUrl = null; AuthorizedUser.RefreshToken = string.Empty; AuthorizedUser.TokenType = string.Empty; AuthorizedUser = TryGetDefaultAuthorizedUser(); } } } #endregion #region consolidation // // How PasswordCredential is stored (with PlusPersonResponse): // PasswordCredential.UserName = "PlusPersonResponse.DisplayName,PlusPersonResponse.Id,PlusPersonResponse.ProfileImageUrl" // PasswordCredential.Resource = "APP_NAME,TokenResponse.TokenType,PlusPersonResponse.Emails[0].Value" // PasswordCredential.Password = "TokenResponse.AccessToken,TokenResponse.RefreshToken,TokenResponse.ExpiresIn.ToString(),DateTime.UtcNow.ToString()" // // How PasswordCredential is stored (with UserInfoResponse): // this is the current usage model // PasswordCredential.UserName = "UserInfoResponse.GivenName,UserInfoResponse.Id,UserInfoResponse.Picture" // PasswordCredential.Resource = "APP_NAME,TokenResponse.TokenType,UserInfoResponse.Email" // PasswordCredential.Password = "TokenResponse.AccessToken,TokenResponse.RefreshToken,TokenResponse.ExpiresIn.ToString(),DateTime.UtcNow.ToString()" // AuthorizedUser PasswordCredentialToAuthorizedUser(PasswordCredential credential) { AuthorizedUser user = new AuthorizedUser(); // // Password // credential.RetrievePassword(); if (!string.IsNullOrEmpty(credential.Password)) { // // OAuthToken // var s = credential.Password.Split(',').ToList(); user.AccessToken = s[0]; user.RefreshToken = s[1]; user.ExpiresIn = int.Parse(s[2]); user.DateAcquiredUtc = DateTime.Parse(s[3]); } // // Resource // if (!string.IsNullOrEmpty(credential.Resource)) { var s = credential.Resource.Split(',').ToList(); if (s[0].Contains(APP_NAME)) { // // OAuthToken // user.TokenType = s[1]; // // UserInfo // if (s.Count > 2) user.Email = s[2]; } } // // UserName // if (!string.IsNullOrEmpty(credential.UserName)) { var s = credential.UserName.Split(',').ToList(); // // UserInfo // user.DisplayName = s[0]; user.Id = s[1]; user.ProfileImageUrl = s[2]; } return user; } // // // //PasswordCredential AuthorizedUserToPasswordCredential(AuthorizedUser user) //{ // PasswordCredential credential = new PasswordCredential(); // // // // OAuthToken // // // return credential; //} // // When you just used a refresh token for the current authorized user // PasswordCredential AuthorizedUserToPasswordCredential(AuthorizedUser user, OAuthTokenResponse response) { PasswordCredential cred = new PasswordCredential(); #region OAuthToken cred.Password = response.AccessToken + ',' + user.RefreshToken + ',' + response.ExpiresIn.ToString() + ',' + DateTime.UtcNow.ToString(); cred.Resource = APP_NAME + ',' + response.TokenType; #endregion #region UserInfo if (!string.IsNullOrEmpty(user.Email)) cred.Resource += ',' + user.Email; if (!string.IsNullOrEmpty(user.DisplayName)) { cred.UserName = user.DisplayName + ',' + user.Id + ',' + user.ProfileImageUrl; } #endregion return cred; } #region PasswordCredential from a response // // Call order -> // OAuthTokenResponse // UserInfoResponse // // Yes, I know this is unsavory. // void ResponseToPasswordCredential(OAuthTokenResponse response, ref PasswordCredential cred) { // // Resource // cred.Resource = APP_NAME + ',' + response.TokenType; // // Password // cred.Password = response.AccessToken + ',' + response.RefreshToken + ',' + response.ExpiresIn.ToString() + ',' + DateTime.UtcNow.ToString(); } void ResponseToPasswordCredential(UserInfoResponse response, ref PasswordCredential cred) { // // UserName // cred.UserName = response.GivenName + ',' + response.Id + ',' + response.Picture; // // Resource // if (!string.IsNullOrEmpty(response.Email)) cred.Resource += ',' + response.Email; } #endregion // // Check if the user already exists before storing in the vault. // Always compare by id, never by name. // async Task<bool> TryRemoveExistingUser(PasswordCredential credential) { string id = credential.UserName.Split(',').ElementAt(1); PasswordVault vault = new PasswordVault(); IReadOnlyList<PasswordCredential> credentials = vault.RetrieveAll(); if (credentials != null && credentials.Count > 0) foreach (var cred in credentials) { if (string.IsNullOrEmpty(cred.UserName)) continue; string credId = cred.UserName.Split(',').ElementAt(1); if (id == credId) { cred.RetrievePassword(); string accessToken = cred.Password.Split(',').ElementAt(0); // // Revoke, remove from the vault, and from the view, if applicable // await this.RevokeTokensAsync(accessToken); return true; } } // // Fall through // return false; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableModuloTests { #region Test methods [Fact] public static void CheckNullableByteModuloTest() { byte?[] array = new byte?[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteModuloTest() { sbyte?[] array = new sbyte?[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableUShortModuloTest() { ushort?[] array = new ushort?[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableShortModuloTest() { short?[] array = new short?[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableUIntModuloTest() { uint?[] array = new uint?[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableIntModuloTest() { int?[] array = new int?[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableULongModuloTest() { ulong?[] array = new ulong?[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableLongModuloTest() { long?[] array = new long?[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableFloatModuloTest() { float?[] array = new float?[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableDoubleModuloTest() { double?[] array = new double?[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableDecimalModuloTest() { decimal?[] array = new decimal?[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalModulo(array[i], array[j]); } } } [Fact] public static void CheckNullableCharModuloTest() { char?[] array = new char?[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharModulo(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableByteModulo(byte? a, byte? b) { Expression aExp = Expression.Constant(a, typeof(byte?)); Expression bExp = Expression.Constant(b, typeof(byte?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifyNullableSByteModulo(sbyte? a, sbyte? b) { Expression aExp = Expression.Constant(a, typeof(sbyte?)); Expression bExp = Expression.Constant(b, typeof(sbyte?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } private static void VerifyNullableUShortModulo(ushort? a, ushort? b) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Modulo( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(); // add with expression tree ushort? etResult = default(ushort?); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // add with real IL ushort? csResult = default(ushort?); Exception csException = null; try { csResult = (ushort?)(a % b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableShortModulo(short? a, short? b) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Modulo( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(); // add with expression tree short? etResult = default(short?); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // add with real IL short? csResult = default(short?); Exception csException = null; try { csResult = (short?)(a % b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableUIntModulo(uint? a, uint? b) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Modulo( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(); // add with expression tree uint? etResult = default(uint?); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // add with real IL uint? csResult = default(uint?); Exception csException = null; try { csResult = (uint?)(a % b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableIntModulo(int? a, int? b) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Modulo( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(); // add with expression tree int? etResult = default(int?); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // add with real IL int? csResult = default(int?); Exception csException = null; try { csResult = (int?)(a % b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableULongModulo(ulong? a, ulong? b) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Modulo( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(); // add with expression tree ulong? etResult = default(ulong?); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // add with real IL ulong? csResult = default(ulong?); Exception csException = null; try { csResult = (ulong?)(a % b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableLongModulo(long? a, long? b) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Modulo( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(); // add with expression tree long? etResult = default(long?); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // add with real IL long? csResult = default(long?); Exception csException = null; try { csResult = (long?)(a % b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableFloatModulo(float? a, float? b) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Modulo( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(); // add with expression tree float? etResult = default(float?); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // add with real IL float? csResult = default(float?); Exception csException = null; try { csResult = (float?)(a % b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableDoubleModulo(double? a, double? b) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Modulo( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(); // add with expression tree double? etResult = default(double?); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // add with real IL double? csResult = default(double?); Exception csException = null; try { csResult = (double?)(a % b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableDecimalModulo(decimal? a, decimal? b) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Modulo( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(); // add with expression tree decimal? etResult = default(decimal?); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // add with real IL decimal? csResult = default(decimal?); Exception csException = null; try { csResult = (decimal?)(a % b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableCharModulo(char? a, char? b) { Expression aExp = Expression.Constant(a, typeof(char?)); Expression bExp = Expression.Constant(b, typeof(char?)); Assert.Throws<InvalidOperationException>(() => Expression.Modulo(aExp, bExp)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Numerics; using Xunit; namespace System.Security.Cryptography.Rsa.Tests { public partial class ImportExport { [Fact] public static void ExportAutoKey() { RSAParameters privateParams; RSAParameters publicParams; int keySize; using (RSA rsa = RSAFactory.Create()) { keySize = rsa.KeySize; // We've not done anything with this instance yet, but it should automatically // create the key, because we'll now asked about it. privateParams = rsa.ExportParameters(true); publicParams = rsa.ExportParameters(false); // It shouldn't be changing things when it generated the key. Assert.Equal(keySize, rsa.KeySize); } Assert.Null(publicParams.D); Assert.NotNull(privateParams.D); ValidateParameters(ref publicParams); ValidateParameters(ref privateParams); Assert.Equal(privateParams.Modulus, publicParams.Modulus); Assert.Equal(privateParams.Exponent, publicParams.Exponent); } [Fact] public static void PaddedExport() { // OpenSSL's numeric type for the storage of RSA key parts disregards zero-valued // prefix bytes. // // The .NET 4.5 RSACryptoServiceProvider type verifies that all of the D breakdown // values (P, DP, Q, DQ, InverseQ) are exactly half the size of D (which is itself // the same size as Modulus). // // These two things, in combination, suggest that we ensure that all .NET // implementations of RSA export their keys to the fixed array size suggested by their // KeySize property. RSAParameters diminishedDPParamaters = TestData.DiminishedDPParamaters; RSAParameters exported; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(diminishedDPParamaters); exported = rsa.ExportParameters(true); } // DP is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(ref diminishedDPParamaters, ref exported); } [Fact] public static void LargeKeyImportExport() { RSAParameters imported = TestData.RSA16384Params; using (RSA rsa = RSAFactory.Create()) { try { rsa.ImportParameters(imported); } catch (CryptographicException) { // The key is pretty big, perhaps it was refused. return; } RSAParameters exported = rsa.ExportParameters(false); Assert.Equal(exported.Modulus, imported.Modulus); Assert.Equal(exported.Exponent, imported.Exponent); Assert.Null(exported.D); exported = rsa.ExportParameters(true); AssertKeyEquals(ref imported, ref exported); } } [Fact] public static void UnusualExponentImportExport() { // Most choices for the Exponent value in an RSA key use a Fermat prime. // Since a Fermat prime is 2^(2^m) + 1, it always only has two bits set, and // frequently has the form { 0x01, [some number of 0x00s], 0x01 }, which has the same // representation in both big- and little-endian. // // The only real requirement for an Exponent value is that it be coprime to (p-1)(q-1). // So here we'll use the (non-Fermat) prime value 433 (0x01B1) to ensure big-endian export. RSAParameters unusualExponentParameters = TestData.UnusualExponentParameters; RSAParameters exported; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(unusualExponentParameters); exported = rsa.ExportParameters(true); } // Exponent is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(ref unusualExponentParameters, ref exported); } [Fact] public static void ImportReset() { using (RSA rsa = RSAFactory.Create()) { RSAParameters exported = rsa.ExportParameters(true); RSAParameters imported; // Ensure that we cause the KeySize value to change. if (rsa.KeySize == 1024) { imported = TestData.RSA2048Params; } else { imported = TestData.RSA1024Params; } Assert.NotEqual(imported.Modulus.Length * 8, rsa.KeySize); Assert.NotEqual(imported.Modulus, exported.Modulus); rsa.ImportParameters(imported); Assert.Equal(imported.Modulus.Length * 8, rsa.KeySize); exported = rsa.ExportParameters(true); AssertKeyEquals(ref imported, ref exported); } } [Fact] public static void MultiExport() { RSAParameters imported = TestData.RSA1024Params; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); RSAParameters exportedPrivate = rsa.ExportParameters(true); RSAParameters exportedPrivate2 = rsa.ExportParameters(true); RSAParameters exportedPublic = rsa.ExportParameters(false); RSAParameters exportedPublic2 = rsa.ExportParameters(false); RSAParameters exportedPrivate3 = rsa.ExportParameters(true); RSAParameters exportedPublic3 = rsa.ExportParameters(false); AssertKeyEquals(ref imported, ref exportedPrivate); Assert.Equal(imported.Modulus, exportedPublic.Modulus); Assert.Equal(imported.Exponent, exportedPublic.Exponent); Assert.Null(exportedPublic.D); ValidateParameters(ref exportedPublic); AssertKeyEquals(ref exportedPrivate, ref exportedPrivate2); AssertKeyEquals(ref exportedPrivate, ref exportedPrivate3); AssertKeyEquals(ref exportedPublic, ref exportedPublic2); AssertKeyEquals(ref exportedPublic, ref exportedPublic3); } } [Fact] public static void PublicOnlyPrivateExport() { RSAParameters imported = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, Exponent = TestData.RSA1024Params.Exponent, }; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); Assert.ThrowsAny<CryptographicException>(() => rsa.ExportParameters(true)); } } [Fact] public static void ImportNoExponent() { RSAParameters imported = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, }; using (RSA rsa = RSAFactory.Create()) { Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } [Fact] public static void ImportNoModulus() { RSAParameters imported = new RSAParameters { Exponent = TestData.RSA1024Params.Exponent, }; using (RSA rsa = RSAFactory.Create()) { Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } [Fact] public static void ImportNoDP() { // Because RSAParameters is a struct, this is a copy, // so assigning DP is not destructive to other tests. RSAParameters imported = TestData.RSA1024Params; imported.DP = null; using (RSA rsa = RSAFactory.Create()) { Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } internal static void AssertKeyEquals(ref RSAParameters expected, ref RSAParameters actual) { Assert.Equal(expected.Modulus, actual.Modulus); Assert.Equal(expected.Exponent, actual.Exponent); Assert.Equal(expected.P, actual.P); Assert.Equal(expected.DP, actual.DP); Assert.Equal(expected.Q, actual.Q); Assert.Equal(expected.DQ, actual.DQ); Assert.Equal(expected.InverseQ, actual.InverseQ); if (expected.D == null) { Assert.Null(actual.D); } else { Assert.NotNull(actual.D); // If the value matched expected, take that as valid and shortcut the math. // If it didn't, we'll test that the value is at least legal. if (!expected.D.SequenceEqual(actual.D)) { VerifyDValue(ref actual); } } } internal static void ValidateParameters(ref RSAParameters rsaParams) { Assert.NotNull(rsaParams.Modulus); Assert.NotNull(rsaParams.Exponent); // Key compatibility: RSA as an algorithm is achievable using just N (Modulus), // E (public Exponent) and D (private exponent). Having all of the breakdowns // of D make the algorithm faster, and shipped versions of RSACryptoServiceProvider // have thrown if D is provided and the rest of the private key values are not. // So, here we're going to assert that none of them were null for private keys. if (rsaParams.D == null) { Assert.Null(rsaParams.P); Assert.Null(rsaParams.DP); Assert.Null(rsaParams.Q); Assert.Null(rsaParams.DQ); Assert.Null(rsaParams.InverseQ); } else { Assert.NotNull(rsaParams.P); Assert.NotNull(rsaParams.DP); Assert.NotNull(rsaParams.Q); Assert.NotNull(rsaParams.DQ); Assert.NotNull(rsaParams.InverseQ); } } private static void VerifyDValue(ref RSAParameters rsaParams) { if (rsaParams.P == null) { return; } // Verify that the formula (D * E) % LCM(p - 1, q - 1) == 1 // is true. // // This is NOT the same as saying D = ModInv(E, LCM(p - 1, q - 1)), // because D = ModInv(E, (p - 1) * (q - 1)) is a valid choice, but will // still work through this formula. BigInteger p = PositiveBigInteger(rsaParams.P); BigInteger q = PositiveBigInteger(rsaParams.Q); BigInteger e = PositiveBigInteger(rsaParams.Exponent); BigInteger d = PositiveBigInteger(rsaParams.D); BigInteger lambda = LeastCommonMultiple(p - 1, q - 1); BigInteger modProduct = (d * e) % lambda; Assert.Equal(BigInteger.One, modProduct); } private static BigInteger LeastCommonMultiple(BigInteger a, BigInteger b) { BigInteger gcd = BigInteger.GreatestCommonDivisor(a, b); return BigInteger.Abs(a) / gcd * BigInteger.Abs(b); } private static BigInteger PositiveBigInteger(byte[] bigEndianBytes) { byte[] littleEndianBytes; if (bigEndianBytes[0] >= 0x80) { // Insert a padding 00 byte so the number is treated as positive. littleEndianBytes = new byte[bigEndianBytes.Length + 1]; Buffer.BlockCopy(bigEndianBytes, 0, littleEndianBytes, 1, bigEndianBytes.Length); } else { littleEndianBytes = (byte[])bigEndianBytes.Clone(); } Array.Reverse(littleEndianBytes); return new BigInteger(littleEndianBytes); } } }
using System; using System.Linq; using log4net; using SoftFX.Extended; using SoftFX.Extended.Reports; namespace RHost { public static class FdkTradeReports { public static DataTrade Trade { get { return FdkHelper.Wrapper.ConnectLogic.TradeWrapper.Trade; } } public static string GetTradeTransactionReport(DateTime from, DateTime to) { try { Log.InfoFormat("FdkTradeReports.GetTradeTransactionReport( from: {0}, to: {1}", from, to); var tradeRecordsStream = Trade.Server.GetTradeTransactionReports(TimeDirection.Forward, false, from, to) .ToArray().ToList(); var tradeRecordList = tradeRecordsStream.ToArray(); var varName = FdkVars.RegisterVariable(tradeRecordList, "tradeReports"); return varName; } catch (Exception ex) { Log.Error(ex); throw; } } static readonly ILog Log = LogManager.GetLogger(typeof(FdkTradeReports)); public static string GetTradeTransactionReportAll() { var tradeRecordsStream = Trade.Server.GetTradeTransactionReports(TimeDirection.Forward, false, null, null) .ToArray().ToList(); var tradeRecordList = tradeRecordsStream.ToArray(); var varName = FdkVars.RegisterVariable(tradeRecordList, "tradeReports"); return varName; } public static double[] GetTradeAccountBalance(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.SelectToArray(it => it.AccountBalance); } public static double[] GetTradeAgentCommission(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.SelectToArray(it => it.AgentCommission); } public static string[] GetTradeClientId(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.SelectToArray(it => it.ClientId); } public static double[] GetTradeCloseConversionRate(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.SelectToArray(it => it.CloseConversionRate ?? -1.0); } public static string[] GetTradeInitialVolume(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.SelectToArray(it => it.CommCurrency); } public static string[] GetTradeComment(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.SelectToArray(it => it.Comment); } public static double[] GetTradeCommission(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.SelectToArray(it => it.Commission); } public static string[] GetTradeId(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.SelectToArray(it => it.Id); } public static double[] GetTradeLeavesQuantity(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.SelectToArray(it => it.LeavesQuantity); } public static double[] GetTradeOpenConversionRate(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.OpenConversionRate ?? -1).ToArray(); } public static DateTime[] GetTradeOrderCreated(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.OrderCreated.AddUtc()).ToArray(); } public static double[] GetTradeOrderFillPrice(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.OrderFillPrice ?? -1).ToArray(); } public static double[] GetTradeOrderLastFillAmount(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.OrderLastFillAmount ?? -1).ToArray(); } public static DateTime[] GetTradeOrderModified(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.OrderModified.AddUtc()).ToArray(); } public static double[] GetTradePosOpenPrice(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PosOpenPrice).ToArray(); } public static double[] GetTradePositionClosePrice(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PositionClosePrice).ToArray(); } public static double[] GetTradePositionCloseRequestedPrice(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PositionCloseRequestedPrice).ToArray(); } public static DateTime[] GetTradePositionClosed(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PositionClosed.AddUtc()).ToArray(); } public static string[] GetTradePositionId(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PositionId).ToArray(); } public static double[] GetTradePositionLastQuantity(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PositionLastQuantity).ToArray(); } public static double[] GetTradePositionLeavesQuantity(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PositionLeavesQuantity).ToArray(); } public static DateTime[] GetTradePositionModified(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PositionModified.AddUtc()).ToArray(); } public static DateTime[] GetTradePositionOpened(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PositionOpened.AddUtc()).ToArray(); } public static double[] GetTradePositionQuantity(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.PositionQuantity).ToArray(); } public static double[] GetTradePrice(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.Price).ToArray(); } public static double[] GetTradeQuantity(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.Quantity).ToArray(); } public static double[] GetTradeStopLoss(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.StopLoss).ToArray(); } public static double[] GetTradeStopPrice(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.StopPrice).ToArray(); } public static double[] GetTradeSwap(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.Swap).ToArray(); } public static string[] GetTradeSymbol(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.Symbol).ToArray(); } public static double[] GetTradeTakeProfit(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.TakeProfit).ToArray(); } public static string[] GetTradeTradeRecordSide(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.TradeRecordSide.ToString()).ToArray(); } public static string[] GetTradeTradeRecordType(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.TradeRecordType.ToString()).ToArray(); } public static string[] GetTradeTradeTransactionReason(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.TradeTransactionReason.ToString()).ToArray(); } public static string[] GetTradeTradeTransactionReportType(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.TradeTransactionReportType.ToString()).ToArray(); } public static double[] GetTradeTransactionAmount(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.TransactionAmount).ToArray(); } public static string[] GetTradeTransactionCurrency(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.TransactionCurrency).ToArray(); } public static DateTime[] GetTradeTransactionTime(string varName) { var tradeData = FdkVars.GetValue<TradeTransactionReport[]>(varName); return tradeData.Select(it => it.TransactionTime.AddUtc()).ToArray(); } } }
//--------------------------------------------------------------------- // <copyright file="CqlQuery.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.Common.EntitySql { using System; using System.Collections.Generic; using System.Data.Common.CommandTrees; using System.Data.Metadata.Edm; using System.Diagnostics; /// <summary> /// Provides eSQL text Parsing and Compilation services. /// </summary> /// <remarks> /// This class exposes services that perform syntactic and semantic analysis of eSQL commands. /// The syntactic validation ensures the given command conforms to eSQL formal grammar. The semantic analysis will /// perform (list not exhaustive): type resolution and validation, ensure semantic and scoping rules, etc. /// The services exposed by this class are: /// <list> /// <item>Translation from eSQL text commands to valid <see cref="DbCommandTree"/>s</item> /// <item>Translation from eSQL text commands to valid <see cref="DbExpression"/>s</item> /// </list> /// Queries can be formulated in O-Space, C-Space and S-Space and the services exposed by this class are agnostic of the especific typespace or /// metadata instance passed as required parameter in the semantic analysis by the perspective parameter. It is assumed that the perspective and /// metadata was properly initialized. /// Provided that the command is syntacticaly correct and meaningful within the given typespace, the result will be a valid <see cref="DbCommandTree"/> or /// <see cref="DbExpression"/> otherwise EntityException will be thrown indicating the reason(s) why the given command cannot be accepted. /// It is also possible that MetadataException and MappingException be thrown if mapping or metadata related problems are encountered during compilation. /// </remarks> /// <list> /// <item><seealso cref="ParserOptions"/></item> /// <item><seealso cref="DbCommandTree"/></item> /// <item><seealso cref="DbExpression"/></item> /// </list> internal static class CqlQuery { /// <summary> /// Compiles an eSQL command producing a validated <see cref="DbCommandTree"/>. /// </summary> /// <param name="commandText">eSQL command text</param> /// <param name="perspective">perspective</param> /// <param name="parserOptions">parser options<seealso cref="ParserOptions"/></param> /// <param name="parameters">ordinary parameters</param> /// <param name="parseResult"></param> /// <returns>A parse result with the command tree produced by parsing the given command.</returns> /// <exception cref="System.Data.EntityException">Thrown when Syntatic or Semantic rules are violated and the query cannot be accepted</exception> /// <exception cref="System.Data.MetadataException">Thrown when metadata related service requests fail</exception> /// <exception cref="System.Data.MappingException">Thrown when mapping related service requests fail</exception> /// <remarks> /// This method is not thread safe. /// </remarks> /// <seealso cref="ParserOptions"/> /// <seealso cref="DbCommandTree"/> internal static ParseResult Compile(string commandText, Perspective perspective, ParserOptions parserOptions, IEnumerable<DbParameterReferenceExpression> parameters) { ParseResult result = CompileCommon(commandText, perspective, parserOptions, (astCommand, validatedParserOptions) => { var parseResultInternal = AnalyzeCommandSemantics(astCommand, perspective, validatedParserOptions, parameters); Debug.Assert(parseResultInternal != null, "parseResultInternal != null post-condition FAILED"); Debug.Assert(parseResultInternal.CommandTree != null, "parseResultInternal.CommandTree != null post-condition FAILED"); TypeHelpers.AssertEdmType(parseResultInternal.CommandTree); return parseResultInternal; }); return result; } /// <summary> /// Compiles an eSQL query command producing a validated <see cref="DbLambda"/>. /// </summary> /// <param name="queryCommandText">eSQL query command text</param> /// <param name="perspective">perspective</param> /// <param name="parserOptions">parser options<seealso cref="ParserOptions"/></param> /// <param name="parameters">ordinary command parameters</param> /// <param name="variables">command free variables</param> /// <returns>The query expression tree produced by parsing the given query command.</returns> /// <exception cref="System.Data.EntityException">Thrown when Syntatic or Semantic rules are violated and the query expression cannot be accepted</exception> /// <exception cref="System.Data.MetadataException">Thrown when metadata related service requests fail</exception> /// <exception cref="System.Data.MappingException">Thrown when mapping related service requests fail</exception> /// <remarks> /// This method is not thread safe. /// </remarks> /// <seealso cref="ParserOptions"/> /// <seealso cref="DbExpression"/> internal static DbLambda CompileQueryCommandLambda(string queryCommandText, Perspective perspective, ParserOptions parserOptions, IEnumerable<DbParameterReferenceExpression> parameters, IEnumerable<DbVariableReferenceExpression> variables) { return CompileCommon(queryCommandText, perspective, parserOptions, (astCommand, validatedParserOptions) => { DbLambda lambda = AnalyzeQueryExpressionSemantics(astCommand, perspective, validatedParserOptions, parameters, variables); TypeHelpers.AssertEdmType(lambda.Body.ResultType); Debug.Assert(lambda != null, "lambda != null post-condition FAILED"); return lambda; }); } #region Private /// <summary> /// Parse eSQL command string into an AST /// </summary> /// <param name="commandText">eSQL command</param> /// <param name="parserOptions">parser options<seealso cref="ParserOptions"/></param> /// <returns>Ast</returns> /// <exception cref="System.Data.EntityException">Thrown when Syntatic or Semantic rules are violated and the query cannot be accepted</exception> /// <remarks> /// This method is not thread safe. /// </remarks> /// <seealso cref="ParserOptions"/> private static AST.Node Parse(string commandText, ParserOptions parserOptions) { AST.Node astExpr = null; // // commandText and parserOptions are validated inside of CqlParser // // // Create Parser // CqlParser cqlParser = new CqlParser(parserOptions, true); // // Invoke parser // astExpr = cqlParser.Parse(commandText); if (null == astExpr) { throw EntityUtil.EntitySqlError(commandText, System.Data.Entity.Strings.InvalidEmptyQuery, 0); } return astExpr; } private static TResult CompileCommon<TResult>(string commandText, Perspective perspective, ParserOptions parserOptions, Func<AST.Node, ParserOptions, TResult> compilationFunction) where TResult : class { TResult result = null; // // Validate arguments // EntityUtil.CheckArgumentNull(perspective, "commandText"); EntityUtil.CheckArgumentNull(perspective, "perspective"); // // Validate parser options - if null, give default options // parserOptions = parserOptions ?? new ParserOptions(); // // Invoke Parser // AST.Node astCommand = Parse(commandText, parserOptions); // // Perform Semantic Analysis/Conversion // result = compilationFunction(astCommand, parserOptions); return result; } /// <summary> /// Performs semantic conversion, validation on a command AST and creates a <see cref="DbCommandTree"/> /// </summary> /// <param name="astExpr">Abstract Syntax Tree of the command</param> /// <param name="perspective">perspective</param> /// <param name="parserOptions">parser options<seealso cref="ParserOptions"/></param> /// <param name="parameters">ordinary command parameters</param> /// <returns>a parse result with a valid command tree</returns> /// <remarks>Parameters name/types must be bound before invoking this method</remarks> /// <exception cref="System.Data.EntityException">Thrown when Syntatic or Semantic rules are violated and the query cannot be accepted.</exception> /// <exception cref="System.Data.MetadataException">Thrown as inner exception of a EntityException when metadata related service requests fail.</exception> /// <exception cref="System.Data.MappingException">Thrown as inner exception of a EntityException when mapping related service requests fail.</exception> /// <remarks> /// This method is not thread safe. /// </remarks> /// <seealso cref="ParserOptions"/> /// <seealso cref="DbCommandTree"/> private static ParseResult AnalyzeCommandSemantics(AST.Node astExpr, Perspective perspective, ParserOptions parserOptions, IEnumerable<DbParameterReferenceExpression> parameters) { ParseResult result = AnalyzeSemanticsCommon(astExpr, perspective, parserOptions, parameters, null/*variables*/, (analyzer, astExpression) => { var parseResultInternal = analyzer.AnalyzeCommand(astExpression); Debug.Assert(parseResultInternal != null, "parseResultInternal != null post-condition FAILED"); Debug.Assert(parseResultInternal.CommandTree != null, "parseResultInternal.CommandTree != null post-condition FAILED"); return parseResultInternal; }); return result; } /// <summary> /// Performs semantic conversion, validation on a query command AST and creates a <see cref="DbLambda"/> /// </summary> /// <param name="astQueryCommand">Abstract Syntax Tree of the query command</param> /// <param name="perspective">perspective</param> /// <param name="parserOptions">parser options<seealso cref="ParserOptions"/></param> /// <param name="parameters">ordinary command parameters</param> /// <param name="variables">command free variables</param> /// <remarks>Parameters name/types must be bound before invoking this method</remarks> /// <exception cref="System.Data.EntityException">Thrown when Syntatic or Semantic rules are violated and the query cannot be accepted.</exception> /// <exception cref="System.Data.MetadataException">Thrown as inner exception of a EntityException when metadata related service requests fail.</exception> /// <exception cref="System.Data.MappingException">Thrown as inner exception of a EntityException when mapping related service requests fail.</exception> /// <remarks> /// This method is not thread safe. /// </remarks> /// <seealso cref="ParserOptions"/> /// <seealso cref="DbExpression"/> private static DbLambda AnalyzeQueryExpressionSemantics(AST.Node astQueryCommand, Perspective perspective, ParserOptions parserOptions, IEnumerable<DbParameterReferenceExpression> parameters, IEnumerable<DbVariableReferenceExpression> variables) { return AnalyzeSemanticsCommon( astQueryCommand, perspective, parserOptions, parameters, variables, (analyzer, astExpr) => { DbLambda lambda = analyzer.AnalyzeQueryCommand(astExpr); Debug.Assert(null != lambda, "null != lambda post-condition FAILED"); return lambda; }); } private static TResult AnalyzeSemanticsCommon<TResult>(AST.Node astExpr, Perspective perspective, ParserOptions parserOptions, IEnumerable<DbParameterReferenceExpression> parameters, IEnumerable<DbVariableReferenceExpression> variables, Func<SemanticAnalyzer, AST.Node, TResult> analysisFunction) where TResult : class { TResult result = null; try { // // Validate arguments // EntityUtil.CheckArgumentNull(astExpr, "astExpr"); EntityUtil.CheckArgumentNull(perspective, "perspective"); // // Invoke semantic analysis // SemanticAnalyzer analyzer = (new SemanticAnalyzer(SemanticResolver.Create(perspective, parserOptions, parameters, variables))); result = analysisFunction(analyzer, astExpr); } // // Wrap MetadataException as EntityException inner exception // catch (System.Data.MetadataException metadataException) { throw EntityUtil.EntitySqlError(System.Data.Entity.Strings.GeneralExceptionAsQueryInnerException("Metadata"), metadataException); } // // Wrap MappingException as EntityException inner exception // catch (System.Data.MappingException mappingException) { throw EntityUtil.EntitySqlError(System.Data.Entity.Strings.GeneralExceptionAsQueryInnerException("Mapping"), mappingException); } return result; } #endregion } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. extern alias pythontools; extern alias util; using System; using System.Windows; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Text; using TestUtilities.UI.Python; using util::TestUtilities.UI; namespace PythonToolsUITests { public class SignatureHelpUITests { public void Signatures(PythonVisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\Signatures.sln")); var item = project.ProjectItems.Item("sigs.py"); var window = item.Open(); window.Activate(); var doc = app.GetDocument(item.Document.FullName); doc.SetFocus(); ((UIElement)doc.TextView).Dispatcher.Invoke((Action)(() => { doc.TextView.Caret.MoveTo(new SnapshotPoint(doc.TextView.TextBuffer.CurrentSnapshot, doc.TextView.TextBuffer.CurrentSnapshot.Length)); ((UIElement)doc.TextView).Focus(); })); //doc.WaitForAnalysisAtCaretAsync().WaitAndUnwrapExceptions(); Keyboard.Type("f"); Keyboard.Type(System.Windows.Input.Key.Escape); // for now, to dismiss completion list System.Threading.Thread.Sleep(500); Keyboard.Type("("); using (var sh = doc.WaitForSession<ISignatureHelpSession>()) { var session = sh.Session; Assert.IsNotNull(session, "No session active"); Assert.IsNotNull(session.SelectedSignature, "No signature selected"); WaitForCurrentParameter(session, "a"); Assert.AreEqual("a", session.SelectedSignature.CurrentParameter.Name); window.Activate(); System.Threading.Thread.Sleep(500); Keyboard.Type("1,"); WaitForCurrentParameter(session, "b"); Assert.AreEqual("b", session.SelectedSignature.CurrentParameter.Name); window.Activate(); System.Threading.Thread.Sleep(500); Keyboard.Type("2,"); WaitForCurrentParameter(session, "c"); Assert.AreEqual("c", session.SelectedSignature.CurrentParameter.Name); window.Activate(); System.Threading.Thread.Sleep(500); Keyboard.Type("3,"); WaitForCurrentParameter(session, "d"); Assert.AreEqual("d", session.SelectedSignature.CurrentParameter.Name); window.Activate(); System.Threading.Thread.Sleep(500); Keyboard.Type("4,"); WaitForNoCurrentParameter(session); Assert.AreEqual(null, session.SelectedSignature.CurrentParameter); System.Threading.Thread.Sleep(500); Keyboard.Press(System.Windows.Input.Key.Left); WaitForCurrentParameter(session); Assert.AreEqual("d", session.SelectedSignature.CurrentParameter.Name); //Keyboard.Backspace(); //WaitForCurrentParameter(session); //Assert.AreEqual("d", session.SelectedSignature.CurrentParameter.Name); } } public void SignaturesByName(PythonVisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\Signatures.sln")); var item = project.ProjectItems.Item("sigs.py"); var window = item.Open(); window.Activate(); var doc = app.GetDocument(item.Document.FullName); doc.SetFocus(); ((UIElement)doc.TextView).Dispatcher.Invoke((Action)(() => { doc.TextView.Caret.MoveTo(new SnapshotPoint(doc.TextView.TextBuffer.CurrentSnapshot, doc.TextView.TextBuffer.CurrentSnapshot.Length)); ((UIElement)doc.TextView).Focus(); })); //doc.WaitForAnalysisAtCaretAsync().WaitAndUnwrapExceptions(); Keyboard.Type("f"); System.Threading.Thread.Sleep(500); Keyboard.Type("("); using (var sh = doc.WaitForSession<ISignatureHelpSession>()) { var session = sh.Session; Assert.IsNotNull(session, "No session active"); Assert.IsNotNull(session.SelectedSignature, "No signature selected"); WaitForCurrentParameter(session, "a"); Assert.AreEqual("a", session.SelectedSignature.CurrentParameter.Name); Keyboard.Type("b="); WaitForCurrentParameter(session, "b"); Assert.AreEqual("b", session.SelectedSignature.CurrentParameter.Name); window.Activate(); Keyboard.Type("42,"); WaitForNoCurrentParameter(session); Assert.AreEqual(null, session.SelectedSignature.CurrentParameter); Keyboard.Backspace(); WaitForCurrentParameter(session); Assert.AreEqual("b", session.SelectedSignature.CurrentParameter.Name); } } public void SignaturesMultiLine(PythonVisualStudioApp app) { var project = app.OpenProject(app.CopyProjectForTest(@"TestData\Signatures.sln")); var item = project.ProjectItems.Item("multilinesigs.py"); var window = item.Open(); window.Activate(); var doc = app.GetDocument(item.Document.FullName); doc.SetFocus(); ((UIElement)doc.TextView).Dispatcher.Invoke((Action)(() => { var point = doc.TextView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(5 - 1).Start; doc.TextView.Caret.MoveTo(point); ((UIElement)doc.TextView).Focus(); })); //doc.WaitForAnalysisAtCaretAsync().WaitAndUnwrapExceptions(); app.ExecuteCommand("Edit.ParameterInfo"); using (var sh = doc.WaitForSession<ISignatureHelpSession>()) { var session = sh.Session; Assert.IsNotNull(session, "No session active"); Assert.IsNotNull(session.SelectedSignature, "No signature selected"); WaitForCurrentParameter(session); Assert.AreEqual("b", session.SelectedSignature.CurrentParameter.Name); } } private static void WaitForCurrentParameter(ISignatureHelpSession session, string name) { for (int i = 0; i < 10; i++) { if (session.SelectedSignature.CurrentParameter != null && session.SelectedSignature.CurrentParameter.Name == name) { break; } System.Threading.Thread.Sleep(1000); } } private static void WaitForNoCurrentParameter(ISignatureHelpSession session) { for (int i = 0; i < 10; i++) { if (session.SelectedSignature.CurrentParameter == null) { break; } System.Threading.Thread.Sleep(1000); } } private static void WaitForCurrentParameter(ISignatureHelpSession session) { for (int i = 0; i < 10; i++) { if (session.SelectedSignature.CurrentParameter != null) { break; } System.Threading.Thread.Sleep(1000); } } } }
//--------------------------------------------------------------------------- // // <copyright file="GlyphRunDrawing.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { sealed partial class GlyphRunDrawing : Drawing { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new GlyphRunDrawing Clone() { return (GlyphRunDrawing)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new GlyphRunDrawing CloneCurrentValue() { return (GlyphRunDrawing)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void GlyphRunPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { GlyphRunDrawing target = ((GlyphRunDrawing) d); GlyphRun oldV = (GlyphRun) e.OldValue; GlyphRun newV = (GlyphRun) e.NewValue; System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher; if (dispatcher != null) { DUCE.IResource targetResource = (DUCE.IResource)target; using (CompositionEngineLock.Acquire()) { int channelCount = targetResource.GetChannelCount(); for (int channelIndex = 0; channelIndex < channelCount; channelIndex++) { DUCE.Channel channel = targetResource.GetChannel(channelIndex); Debug.Assert(!channel.IsOutOfBandChannel); Debug.Assert(!targetResource.GetHandle(channel).IsNull); target.ReleaseResource(oldV,channel); target.AddRefResource(newV,channel); } } } target.PropertyChanged(GlyphRunProperty); } private static void ForegroundBrushPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { // The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children) // will promote the property value from a default value to a local value. This is technically a sub-property // change because the collection was changed and not a new collection set (GeometryGroup.Children. // Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled // the default value to the compositor. If the property changes from a default value, the new local value // needs to be marshalled to the compositor. We detect this scenario with the second condition // e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be // Default and the NewValueSource will be Local. if (e.IsASubPropertyChange && (e.OldValueSource == e.NewValueSource)) { return; } GlyphRunDrawing target = ((GlyphRunDrawing) d); Brush oldV = (Brush) e.OldValue; Brush newV = (Brush) e.NewValue; System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher; if (dispatcher != null) { DUCE.IResource targetResource = (DUCE.IResource)target; using (CompositionEngineLock.Acquire()) { int channelCount = targetResource.GetChannelCount(); for (int channelIndex = 0; channelIndex < channelCount; channelIndex++) { DUCE.Channel channel = targetResource.GetChannel(channelIndex); Debug.Assert(!channel.IsOutOfBandChannel); Debug.Assert(!targetResource.GetHandle(channel).IsNull); target.ReleaseResource(oldV,channel); target.AddRefResource(newV,channel); } } } target.PropertyChanged(ForegroundBrushProperty); } #region Public Properties /// <summary> /// GlyphRun - GlyphRun. Default value is null. /// </summary> public GlyphRun GlyphRun { get { return (GlyphRun) GetValue(GlyphRunProperty); } set { SetValueInternal(GlyphRunProperty, value); } } /// <summary> /// ForegroundBrush - Brush. Default value is null. /// </summary> public Brush ForegroundBrush { get { return (Brush) GetValue(ForegroundBrushProperty); } set { SetValueInternal(ForegroundBrushProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new GlyphRunDrawing(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Read values of properties into local variables GlyphRun vGlyphRun = GlyphRun; Brush vForegroundBrush = ForegroundBrush; // Obtain handles for properties that implement DUCE.IResource DUCE.ResourceHandle hGlyphRun = vGlyphRun != null ? ((DUCE.IResource)vGlyphRun).GetHandle(channel) : DUCE.ResourceHandle.Null; DUCE.ResourceHandle hForegroundBrush = vForegroundBrush != null ? ((DUCE.IResource)vForegroundBrush).GetHandle(channel) : DUCE.ResourceHandle.Null; // Pack & send command packet DUCE.MILCMD_GLYPHRUNDRAWING data; unsafe { data.Type = MILCMD.MilCmdGlyphRunDrawing; data.Handle = _duceResource.GetHandle(channel); data.hGlyphRun = hGlyphRun; data.hForegroundBrush = hForegroundBrush; // Send packed command structure channel.SendCommand( (byte*)&data, sizeof(DUCE.MILCMD_GLYPHRUNDRAWING)); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_GLYPHRUNDRAWING)) { GlyphRun vGlyphRun = GlyphRun; if (vGlyphRun != null) ((DUCE.IResource)vGlyphRun).AddRefOnChannel(channel); Brush vForegroundBrush = ForegroundBrush; if (vForegroundBrush != null) ((DUCE.IResource)vForegroundBrush).AddRefOnChannel(channel); AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { GlyphRun vGlyphRun = GlyphRun; if (vGlyphRun != null) ((DUCE.IResource)vGlyphRun).ReleaseOnChannel(channel); Brush vForegroundBrush = ForegroundBrush; if (vForegroundBrush != null) ((DUCE.IResource)vForegroundBrush).ReleaseOnChannel(channel); ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the GlyphRunDrawing.GlyphRun property. /// </summary> public static readonly DependencyProperty GlyphRunProperty; /// <summary> /// The DependencyProperty for the GlyphRunDrawing.ForegroundBrush property. /// </summary> public static readonly DependencyProperty ForegroundBrushProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static GlyphRunDrawing() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(GlyphRunDrawing); GlyphRunProperty = RegisterProperty("GlyphRun", typeof(GlyphRun), typeofThis, null, new PropertyChangedCallback(GlyphRunPropertyChanged), null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); ForegroundBrushProperty = RegisterProperty("ForegroundBrush", typeof(Brush), typeofThis, null, new PropertyChangedCallback(ForegroundBrushPropertyChanged), null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); } #endregion Constructors } }
#if !SILVERLIGHT using NUnit.Framework; #else using Microsoft.Silverlight.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; #endif using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Collections.Generic; using System.Collections; using System.Windows.Controls.Primitives; using DevExpress.Mvvm.DataAnnotations; using System.Reflection; using DevExpress.Mvvm.UI.ViewInjection; using DevExpress.Mvvm.UI.Interactivity; using System.Windows.Data; namespace DevExpress.Mvvm.UI.ViewInjection.Tests { public class TestView1 : Grid { } public class TestView2 : Grid { } [TestFixture] public class ViewInjectionManagerTests : BaseWpfFixture { class VM { public int NavigatedCount { get; private set; } public int NavigatedAwayCount { get; private set; } public int ViewModelClosingCount { get; private set; } public bool CancelViewModelClosing { get; set; } public VM() { NavigatedCount = 0; NavigatedAwayCount = 0; ViewModelClosingCount = 0; CancelViewModelClosing = false; ViewInjectionManager.Default.RegisterNavigatedEventHandler(this, () => NavigatedCount++); ViewInjectionManager.Default.RegisterNavigatedAwayEventHandler(this, () => NavigatedAwayCount++); ViewInjectionManager.Default.RegisterViewModelClosingEventHandler(this, x => { ViewModelClosingCount++; x.Cancel = CancelViewModelClosing; }); } } [Test] public void DefaultViewInjectionManager() { var _default = ViewInjectionManager.Default; Assert.IsNotNull(ViewInjectionManager.Default); var _custom = new ViewInjectionManager(ViewInjectionMode.Default); ViewInjectionManager.Default = _custom; Assert.AreSame(_custom, ViewInjectionManager.Default); ViewInjectionManager.Default = null; Assert.AreSame(_default, ViewInjectionManager.Default); } [Test, Asynchronous] public void GetService() { Grid container = new Grid(); Window.Content = container; ViewInjectionService service1 = new ViewInjectionService(); ContentPresenter target1 = new ContentPresenter(); Interactivity.Interaction.GetBehaviors(target1).Add(service1); Assert.IsNull(ViewInjectionManager.Default.GetService(service1.RegionName)); ViewInjectionService service2 = new ViewInjectionService() { RegionName = "region2" }; ContentPresenter target2 = new ContentPresenter(); Interactivity.Interaction.GetBehaviors(target2).Add(service2); Assert.IsNull(ViewInjectionManager.Default.GetService(service2.RegionName)); ViewInjectionService service3 = new ViewInjectionService() { RegionName = "region3" }; ContentPresenter target3 = new ContentPresenter(); Interactivity.Interaction.GetBehaviors(target3).Add(service3); EnqueueShowWindow(); EnqueueCallback(() => { container.Children.Add(target1); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.IsNull(ViewInjectionManager.Default.GetService(service1.RegionName)); container.Children.Add(target2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(service2, ViewInjectionManager.Default.GetService("region2")); container.Children.Add(target3); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(service2, ViewInjectionManager.Default.GetService("region2")); Assert.AreSame(service3, ViewInjectionManager.Default.GetService("region3")); }); EnqueueTestComplete(); } [Test, Asynchronous] public void RegisterUnregister() { Grid container = new Grid(); Window.Content = container; ViewInjectionService service1 = new ViewInjectionService() { RegionName = "region1" }; ContentPresenter target1 = new ContentPresenter(); container.Children.Add(target1); Interactivity.Interaction.GetBehaviors(target1).Add(service1); ViewInjectionService service2 = new ViewInjectionService() { RegionName = "region2" }; ContentPresenter target2 = new ContentPresenter(); container.Children.Add(target2); Interactivity.Interaction.GetBehaviors(target2).Add(service2); EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreSame(service1, ViewInjectionManager.Default.GetService("region1")); Assert.AreSame(service2, ViewInjectionManager.Default.GetService("region2")); Interactivity.Interaction.GetBehaviors(target1).Remove(service1); container.Children.Remove(target2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.IsNull(ViewInjectionManager.Default.GetService("region1")); Assert.IsNull(ViewInjectionManager.Default.GetService("region2")); }); EnqueueTestComplete(); } [Test, Asynchronous] public void CannotRegisterTwoRegions() { Grid container = new Grid(); Window.Content = container; ViewInjectionService service1 = new ViewInjectionService() { RegionName = "region1" }; ContentPresenter target1 = new ContentPresenter(); container.Children.Add(target1); Interactivity.Interaction.GetBehaviors(target1).Add(service1); ViewInjectionService service2 = new ViewInjectionService() { RegionName = "region1" }; ContentPresenter target2 = new ContentPresenter(); container.Children.Add(target2); EnqueueShowWindow(); EnqueueCallback(() => { AssertHelper.AssertThrows<InvalidOperationException>(() => { Interactivity.Interaction.GetBehaviors(target2).Add(service2); }, x => Assert.AreEqual("Cannot register services with the same RegionName", x.Message)); }); EnqueueTestComplete(); } [Test, Asynchronous] public void InjectRemove() { var refs = InjectRemove_Core(); EnqueueLastCallback(() => { MemoryLeaksHelper.CollectOptional(refs); MemoryLeaksHelper.EnsureCollected(refs); }); } WeakReference[] InjectRemove_Core() { Grid container = new Grid(); Window.Content = container; object vm1 = null; object vm2 = null; object vm3 = null; ViewInjectionManager.Default.Inject("region1", null, () => vm1 = new object(), "TestView1"); ViewInjectionManager.Default.Inject("region2", null, () => vm2 = new object()); ViewInjectionService service1 = new ViewInjectionService() { RegionName = "region1" }; ContentPresenter target1 = new ContentPresenter(); container.Children.Add(target1); Interactivity.Interaction.GetBehaviors(target1).Add(service1); ViewInjectionService service2 = new ViewInjectionService() { RegionName = "region2" }; ContentPresenter target2 = new ContentPresenter(); container.Children.Add(target2); Interactivity.Interaction.GetBehaviors(target2).Add(service2); Assert.IsNull(vm1); Assert.IsNull(vm2); Assert.IsNull(vm3); EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreSame(vm1, target1.Content); Assert.AreSame(vm2, target2.Content); ViewInjectionManager.Default.Inject("region2", null, () => vm3 = new object(), typeof(TestView1)); Assert.AreSame(vm1, target1.Content); Assert.AreSame(vm3, target2.Content); Assert.AreEqual(2, ((IViewInjectionService)service2).ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { ViewInjectionManager.Default.Remove("region1", vm1); ViewInjectionManager.Default.Remove("region2", vm2); ViewInjectionManager.Default.Remove("region2", vm3); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(0, ViewInjectionManager.Default.GetService("region1").ViewModels.Count()); Assert.AreEqual(0, ViewInjectionManager.Default.GetService("region2").ViewModels.Count()); }); EnqueueTestComplete(); WeakReference target1Reference = new WeakReference(target1); WeakReference target2Reference = new WeakReference(target2); WeakReference service1Reference = new WeakReference(service1); WeakReference service2Reference = new WeakReference(service2); WeakReference vm1Reference = new WeakReference(vm1); WeakReference vm2Reference = new WeakReference(vm2); WeakReference vm3Reference = new WeakReference(vm3); Interaction.GetBehaviors(target1).Remove(service1); Interaction.GetBehaviors(target2).Remove(service2); Window.Content = null; return new WeakReference[] { target1Reference, target2Reference, service1Reference, service2Reference, vm1Reference, vm2Reference, vm3Reference }; } [Test, Asynchronous] public void Navigate_SimpleTest() { var refs = Navigate_SimpleTest_Core(); EnqueueLastCallback(() => { MemoryLeaksHelper.CollectOptional(refs); MemoryLeaksHelper.EnsureCollected(refs); }); } WeakReference[] Navigate_SimpleTest_Core() { TabControl target = new TabControl(); object vm1 = new object(); object vm2 = new object(); object vm3 = new object(); ViewInjectionManager.Default.Inject("region1", null, () => vm1); ViewInjectionManager.Default.Inject("region1", null, () => vm2); ViewInjectionManager.Default.Navigate("region1", vm2); ViewInjectionService service = new ViewInjectionService() { RegionName = "region1" }; Interaction.GetBehaviors(target).Add(service); Window.Content = target; EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreEqual(2, target.Items.Count); Assert.AreSame(vm2, target.SelectedItem); Assert.AreEqual(1, target.SelectedIndex); ViewInjectionManager.Default.Navigate("region1", vm3); ViewInjectionManager.Default.Inject("region1", null, () => vm3); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(3, target.Items.Count); Assert.AreSame(vm3, target.SelectedItem); Assert.AreEqual(2, target.SelectedIndex); }); EnqueueTestComplete(); WeakReference targetReference = new WeakReference(target); WeakReference serviceReference = new WeakReference(service); WeakReference vm1Reference = new WeakReference(vm1); WeakReference vm2Reference = new WeakReference(vm2); WeakReference vm3Reference = new WeakReference(vm3); Interaction.GetBehaviors(target).Remove(service); Window.Content = null; return new WeakReference[] { targetReference, serviceReference, vm1Reference, vm2Reference, vm3Reference }; } [Test, Asynchronous] public void NavigatedEvent_NavigatedAwayEvent() { var refs = NavigatedEvent_NavigatedAwayEvent_Core(); EnqueueLastCallback(() => { MemoryLeaksHelper.CollectOptional(refs); MemoryLeaksHelper.EnsureCollected(refs); }); } WeakReference[] NavigatedEvent_NavigatedAwayEvent_Core() { TabControl target = new TabControl(); VM vm1 = new VM(); VM vm2 = new VM(); VM vm3 = new VM(); ViewInjectionManager.Default.Inject("region1", null, () => vm1); ViewInjectionManager.Default.Inject("region1", null, () => vm2); ViewInjectionManager.Default.Navigate("region1", vm2); ViewInjectionService service = new ViewInjectionService() { RegionName = "region1" }; Interaction.GetBehaviors(target).Add(service); Window.Content = target; EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreEqual(1, vm1.NavigatedCount); Assert.AreEqual(1, vm1.NavigatedAwayCount); Assert.AreEqual(1, vm2.NavigatedCount); Assert.AreEqual(0, vm2.NavigatedAwayCount); Assert.AreEqual(0, vm3.NavigatedCount); Assert.AreEqual(0, vm3.NavigatedAwayCount); ViewInjectionManager.Default.Navigate("region1", vm3); ViewInjectionManager.Default.Inject("region1", null, () => vm3); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, vm1.NavigatedCount); Assert.AreEqual(1, vm1.NavigatedAwayCount); Assert.AreEqual(1, vm2.NavigatedCount); Assert.AreEqual(1, vm2.NavigatedAwayCount); Assert.AreEqual(1, vm3.NavigatedCount); Assert.AreEqual(0, vm3.NavigatedAwayCount); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { target.SelectedItem = vm1; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(2, vm1.NavigatedCount); Assert.AreEqual(1, vm1.NavigatedAwayCount); Assert.AreEqual(1, vm2.NavigatedCount); Assert.AreEqual(1, vm2.NavigatedAwayCount); Assert.AreEqual(1, vm3.NavigatedCount); Assert.AreEqual(1, vm3.NavigatedAwayCount); }); EnqueueTestComplete(); WeakReference targetReference = new WeakReference(target); WeakReference serviceReference = new WeakReference(service); WeakReference vm1Reference = new WeakReference(vm1); WeakReference vm2Reference = new WeakReference(vm2); WeakReference vm3Reference = new WeakReference(vm3); Interaction.GetBehaviors(target).Remove(service); Window.Content = null; return new WeakReference[] { targetReference, serviceReference, vm1Reference, vm2Reference, vm3Reference }; } [Test, Asynchronous] public void ViewModelClosingEvent() { var refs = ViewModelClosingEvent_Core(); EnqueueLastCallback(() => { MemoryLeaksHelper.CollectOptional(refs); MemoryLeaksHelper.EnsureCollected(refs); }); } WeakReference[] ViewModelClosingEvent_Core() { TabControl target = new TabControl(); VM vm1 = new VM(); VM vm2 = new VM(); VM vm3 = new VM(); ViewInjectionManager.Default.Inject("region1", null, () => vm1); ViewInjectionManager.Default.Inject("region1", null, () => vm2); ViewInjectionManager.Default.Inject("region1", null, () => vm3); ViewInjectionService service = new ViewInjectionService() { RegionName = "region1" }; Interaction.GetBehaviors(target).Add(service); Window.Content = target; EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreSame(vm1, target.SelectedItem); ViewInjectionManager.Default.Remove("region1", vm1); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm2, target.SelectedItem); Assert.AreEqual(1, vm1.ViewModelClosingCount); vm2.CancelViewModelClosing = true; ViewInjectionManager.Default.Remove("region1", vm2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm2, target.SelectedItem); Assert.AreEqual(1, vm2.ViewModelClosingCount); }); EnqueueTestComplete(); WeakReference targetReference = new WeakReference(target); WeakReference serviceReference = new WeakReference(service); WeakReference vm1Reference = new WeakReference(vm1); WeakReference vm2Reference = new WeakReference(vm2); WeakReference vm3Reference = new WeakReference(vm3); Interaction.GetBehaviors(target).Remove(service); Window.Content = null; return new WeakReference[] { targetReference, serviceReference, vm1Reference, vm2Reference, vm3Reference }; } [Test, Asynchronous] public void PersistentMode_InjectRemove() { object vm = new object(); Func<object> vmFactory = () => vm; WeakReference refVM = new WeakReference(vm); var refs = PersistentMode_InjectRemove_Core(vmFactory, vm); vm = null; vmFactory = null; EnqueueLastCallback(() => { Window.Content = null; MemoryLeaksHelper.CollectOptional(refs); MemoryLeaksHelper.EnsureCollected(refs); MemoryLeaksHelper.CollectOptional(refVM); MemoryLeaksHelper.EnsureCollected(refVM); }); } WeakReference[] PersistentMode_InjectRemove_Core(Func<object> vmFactory, object vm) { Grid container = new Grid(); Window.Content = container; ViewInjectionManager.PersistentManager.Inject("region", null, vmFactory, typeof(TestView1)); ViewInjectionService service1 = new ViewInjectionService() { RegionName = "region", ViewInjectionManager = ViewInjectionManager.PersistentManager }; ContentPresenter target1 = new ContentPresenter(); container.Children.Add(target1); Interactivity.Interaction.GetBehaviors(target1).Add(service1); ViewInjectionService service2 = new ViewInjectionService() { RegionName = "region", ViewInjectionManager = ViewInjectionManager.PersistentManager }; ItemsControl target2 = new ItemsControl(); EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreSame(vm, target1.Content); Assert.AreEqual(1, ((IViewInjectionService)service1).ViewModels.Count()); container.Children.Remove(target1); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(0, ((IViewInjectionService)service1).ViewModels.Count()); container.Children.Add(target1); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm, target1.Content); Assert.AreEqual(1, ((IViewInjectionService)service1).ViewModels.Count()); container.Children.Remove(target1); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Interactivity.Interaction.GetBehaviors(target2).Add(service2); container.Children.Add(target2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm, target2.Items[0]); Assert.AreEqual(0, ((IViewInjectionService)service1).ViewModels.Count()); Assert.AreEqual(1, ((IViewInjectionService)service2).ViewModels.Count()); Interaction.GetBehaviors(target1).Remove(service1); Interaction.GetBehaviors(target2).Remove(service2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { service1.ViewInjectionManager = null; service2.ViewInjectionManager = null; Assert.AreEqual(0, ((IViewInjectionService)service1).ViewModels.Count()); Assert.AreEqual(0, ((IViewInjectionService)service2).ViewModels.Count()); }); EnqueueTestComplete(); WeakReference target1Reference = new WeakReference(target1); WeakReference target2Reference = new WeakReference(target2); WeakReference service1Reference = new WeakReference(service1); WeakReference service2Reference = new WeakReference(service2); return new WeakReference[] { target1Reference, target2Reference, service1Reference, service2Reference }; } } [TestFixture] public class StrategyManagerTests : BaseWpfFixture { [Test] public void DefaultStrategyManager() { var _default = StrategyManager.Default; Assert.IsNotNull(StrategyManager.Default); var _custom = new StrategyManager(); StrategyManager.Default = _custom; Assert.AreSame(_custom, StrategyManager.Default); StrategyManager.Default = null; Assert.AreSame(_default, StrategyManager.Default); } [Test] public void SelectStrategy() { Assert.IsTrue(StrategyManager.Default.CreateStrategy(new ContentPresenter()) is ContentPresenterStrategy<ContentPresenter, ContentPresenterWrapper>); Assert.IsTrue(StrategyManager.Default.CreateStrategy(new ContentControl()) is ContentPresenterStrategy<ContentControl, ContentControlWrapper>); Assert.IsTrue(StrategyManager.Default.CreateStrategy(new HeaderedContentControl()) is ContentPresenterStrategy<ContentControl, ContentControlWrapper>); Assert.IsTrue(StrategyManager.Default.CreateStrategy(new StackPanel()) is PanelStrategy<Panel, PanelWrapper>); Assert.IsTrue(StrategyManager.Default.CreateStrategy(new TabControl()) is SelectorStrategy<TabControl, TabControlWrapper>); AssertHelper.AssertThrows<InvalidOperationException>(() => { StrategyManager.Default.CreateStrategy(new ViewInjectionService()); }, x => Assert.AreEqual("Cannot find an appropriate strategy for the ViewInjectionService container type.", x.Message)); } [Test] public void CustomStrategy() { IStrategyManager _defaultSM; _defaultSM = StrategyManager.Default; StrategyManager.Default = new StrategyManager(); ((StrategyManager)StrategyManager.Default).RegisterDefaultStrategies(); StrategyManager.Default.RegisterStrategy<HeaderedContentControl, CustomStrategy1>(); Assert.IsTrue(StrategyManager.Default.CreateStrategy(new HeaderedContentControl()) is CustomStrategy1); StrategyManager.Default.RegisterStrategy<ContentControl, CustomStrategy2>(); Assert.IsTrue(StrategyManager.Default.CreateStrategy(new ContentControl()) is CustomStrategy2); StrategyManager.Default = null; } class HeaderedContentControlWrapper : ContentControlWrapper, IContentPresenterWrapper<HeaderedContentControl> { public new HeaderedContentControl Target { get { return (HeaderedContentControl)base.Target; } set { base.Target = value; } } } class CustomStrategy1 : ContentPresenterStrategy<HeaderedContentControl, HeaderedContentControlWrapper> { } class CustomStrategy2 : ContentPresenterStrategy<ContentControl, ContentControlWrapper> { } } [TestFixture] public class ViewInjectionServiceTests : BaseWpfFixture { [Test] public void NullServiceTest() { IViewInjectionService iService = null; AssertHelper.AssertThrows<ArgumentNullException>(() => { iService.Inject(null, null); }); AssertHelper.AssertThrows<ArgumentNullException>(() => { iService.Inject(null, null, string.Empty); }); AssertHelper.AssertThrows<ArgumentNullException>(() => { iService.Inject(null, null, typeof(string)); }); AssertHelper.AssertThrows<ArgumentNullException>(() => { iService.GetViewModel(null); }); } [Test, Asynchronous] public void ViewModelKeyTest() { ViewInjectionService service = new ViewInjectionService(); IViewInjectionService iService = service; ContentControl target = new ContentControl(); Interaction.GetBehaviors(target).Add(service); object vm1 = new object(); object vm2 = new object(); Window.Content = target; EnqueueShowWindow(); EnqueueCallback(() => { iService.Inject(null, null); iService.Inject(null, vm1); Assert.AreEqual(1, iService.ViewModels.Count()); Assert.AreSame(vm1, iService.ViewModels.ElementAt(0)); Assert.AreEqual(vm1, iService.GetKey(vm1)); Assert.AreSame(vm1, iService.GetViewModel(vm1)); AssertHelper.AssertThrows<InvalidOperationException>(() => iService.Inject(null, vm1), x => Assert.AreEqual("A view model with the same key already exists in the ViewInjectionService region.", x.Message)); service.RegionName = "Test"; AssertHelper.AssertThrows<InvalidOperationException>(() => iService.Inject(null, vm1), x => Assert.AreEqual("A view model with the same key already exists in the Test region.", x.Message)); iService.Inject("New", vm2); Assert.AreEqual(2, iService.ViewModels.Count()); Assert.AreSame(vm2, iService.ViewModels.ElementAt(1)); Assert.AreEqual("New", iService.GetKey(vm2)); Assert.AreSame(vm2, iService.GetViewModel("New")); iService.Remove(vm1); Assert.AreEqual(1, iService.ViewModels.Count()); iService.Remove(vm2); Assert.AreEqual(0, iService.ViewModels.Count()); }); EnqueueTestComplete(); } #region ContentPresenter and ContentControl [Test, Asynchronous] public void ContentPresenter_InvalidInitialization() { ContentPresenter control = new ContentPresenter() { Content = new object() }; ContentPresenter_InvalidInitializationTest_Core(control, "It is impossible to use ViewInjectionService for the control that has the Content property set."); } [Test, Asynchronous] public void ContentPresenter_InjectMethods() { ViewInjectionService service; ContentPresenterWrapper target; InitContentPresenterTest(out service, out target); ContentPresenter_InjectMethods_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ContentControl_InjectMethods() { ViewInjectionService service; ContentControlWrapper target; InitContentControlTest(out service, out target); ContentPresenter_InjectMethods_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ContentPresenter_InjectWithContentTemplate() { ViewInjectionService service; ContentPresenterWrapper target; InitContentPresenterTest(out service, out target); ContentPresenter_InjectWithContentTemplate_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ContentControl_InjectWithContentTemplate() { ViewInjectionService service; ContentControlWrapper target; InitContentControlTest(out service, out target); ContentPresenter_InjectWithContentTemplate_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ContentPresenter_SelectedViewModel() { ViewInjectionService service; ContentPresenterWrapper target; InitContentPresenterTest(out service, out target); ContentPresenter_SelectedViewModel_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ContentControl_SelectedViewModel() { ViewInjectionService service; ContentControlWrapper target; InitContentControlTest(out service, out target); ContentPresenter_SelectedViewModel_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ContentPresenter_RemoveViewModel() { ViewInjectionService service; ContentPresenterWrapper target; InitContentPresenterTest(out service, out target); ContentPresenter_RemoveViewModelSimpleTest_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ContentControl_RemoveViewModel() { ViewInjectionService service; ContentControlWrapper target; InitContentControlTest(out service, out target); ContentPresenter_RemoveViewModelSimpleTest_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ContentPresenter_CancelRemoveViewModel() { ViewInjectionService service; ContentPresenterWrapper target; InitContentPresenterTest(out service, out target); ContentPresenter_CancelRemoveViewModelTest_Core(service); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ContentControl_CancelRemoveViewModel() { ViewInjectionService service; ContentControlWrapper target; InitContentControlTest(out service, out target); ContentPresenter_CancelRemoveViewModelTest_Core(service); service = null; target = null; ContentPresenter_TestMemoryReleased(); } void InitContentPresenterTest(out ViewInjectionService service, out ContentPresenterWrapper target) { ContentPresenter control = new ContentPresenter(); service = new ViewInjectionService(); Interaction.GetBehaviors(control).Add(service); target = new ContentPresenterWrapper() { Target = control }; } void InitContentControlTest(out ViewInjectionService service, out ContentControlWrapper target) { ContentControl control = new ContentControl(); service = new ViewInjectionService(); Interaction.GetBehaviors(control).Add(service); target = new ContentControlWrapper() { Target = control }; } void ContentPresenter_InvalidInitializationTest_Core(FrameworkElement target, string exception) { ViewInjectionService service = new ViewInjectionService(); Interaction.GetBehaviors(target).Add(service); EnqueueShowWindow(); EnqueueCallback(() => { AssertHelper.AssertThrows<InvalidOperationException>(() => { Window.Content = target; }, x => Assert.AreEqual(exception, x.Message)); }); EnqueueTestComplete(); } void ContentPresenter_InjectMethods_Core<T>(ViewInjectionService service, IContentPresenterWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Inject(null, vm1); Assert.AreSame(vm1, target.Content); iService.Inject(null, vm2, typeof(TestView1)); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm2, target.Content); Assert.AreSame(vm2, LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<TestView1>().First().DataContext); }); EnqueueTestComplete(); } void ContentPresenter_InjectWithContentTemplate_Core<T>(ViewInjectionService service, IContentPresenterWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; target.ContentTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(TextBox)) }; object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Inject(null, vm1); Assert.AreSame(vm1, target.Content); Assert.AreSame(vm1, LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<TextBox>().First().DataContext); AssertHelper.AssertThrows<InvalidOperationException>(() => { iService.Inject(null, vm2, typeof(TestView1)); }, x => Assert.AreEqual("ViewInjectionService cannot create view by name or type, because the target control has the ContentTemplate/ContentTemplateSelector property set.", x.Message)); iService.Inject(null, vm2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm2, target.Content); Assert.AreSame(vm2, LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<TextBox>().First().DataContext); }); EnqueueTestComplete(); } void ContentPresenter_SelectedViewModel_Core<T>(ViewInjectionService service, IContentPresenterWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; int selectedViewModelChangedCount = 0; service.SelectedViewModelChangedCommand = new DelegateCommand(() => selectedViewModelChangedCount++); object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Inject(null, vm1); Assert.AreEqual(1, selectedViewModelChangedCount); Assert.AreSame(vm1, target.Content); iService.Inject(null, vm2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(2, selectedViewModelChangedCount); Assert.AreSame(vm2, target.Content); iService.SelectedViewModel = vm1; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(3, selectedViewModelChangedCount); Assert.AreSame(vm1, target.Content); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { AssertHelper.AssertThrows<InvalidOperationException>(() => { iService.SelectedViewModel = new object(); }, x => Assert.AreEqual("Cannot set the SelectedViewModel property to a value that does not exist in the ViewModels collection. Inject the view model before selecting it.", x.Message)); }); EnqueueTestComplete(); } void ContentPresenter_RemoveViewModelSimpleTest_Core<T>(ViewInjectionService service, IContentPresenterWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; int viewModelClosingCommandCount = 0; service.ViewModelClosingCommand = new DelegateCommand(() => viewModelClosingCommandCount++); object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Remove(new object()); iService.Inject(null, vm1); Assert.AreSame(vm1, target.Content); iService.Inject(null, vm2); iService.Remove(new object()); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm2, target.Content); iService.SelectedViewModel = vm1; iService.Remove(vm1); Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, viewModelClosingCommandCount); Assert.IsNull(iService.SelectedViewModel); Assert.IsNull(target.Content); iService.Inject(null, vm1); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm1, iService.SelectedViewModel); iService.Remove(vm2); Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(2, viewModelClosingCommandCount); Assert.AreSame(vm1, iService.SelectedViewModel); iService.Remove(vm1); Assert.AreEqual(0, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(3, viewModelClosingCommandCount); Assert.IsNull(iService.SelectedViewModel); }); EnqueueTestComplete(); } void ContentPresenter_CancelRemoveViewModelTest_Core(ViewInjectionService service) { IViewInjectionService iService = service; bool cancel = false; service.ViewModelClosingCommand = new DelegateCommand<ViewModelClosingEventArgs>(x => x.Cancel = cancel); object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Inject(null, vm1); iService.Inject(null, vm2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { iService.Remove(vm1); Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { iService.Inject(null, vm1); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { cancel = true; iService.Remove(vm1); iService.Remove(vm2); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { cancel = false; iService.Remove(vm1); iService.Remove(vm2); Assert.AreEqual(0, iService.ViewModels.Count()); }); EnqueueTestComplete(); } void ContentPresenter_TestMemoryReleased() { EnqueueLastCallback(() => { ViewInjectionService service = Interaction.GetBehaviors((DependencyObject)Window.Content).OfType<ViewInjectionService>().First(); Interaction.GetBehaviors((DependencyObject)Window.Content).Remove(service); WeakReference controlReference = new WeakReference(Window.Content); WeakReference serviceReference = new WeakReference(service); service = null; Window.Content = null; MemoryLeaksHelper.CollectOptional(controlReference, serviceReference); MemoryLeaksHelper.EnsureCollected(controlReference, serviceReference); }); } #endregion #region Panel [Test, Asynchronous] public void Panel_InjectMethods() { ViewInjectionService service; PanelWrapper target; InitPanelTest(out service, out target); Panel_InjectMethods_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void Panel_RemoveViewModel() { ViewInjectionService service; PanelWrapper target; InitPanelTest(out service, out target); Panel_RemoveViewModelSimpleTest_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void Panel_CancelRemoveViewModel() { ViewInjectionService service; PanelWrapper target; InitPanelTest(out service, out target); ContentPresenter_CancelRemoveViewModelTest_Core(service); service = null; target = null; ContentPresenter_TestMemoryReleased(); } void InitPanelTest(out ViewInjectionService service, out PanelWrapper target) { Grid control = new Grid(); service = new ViewInjectionService(); Interaction.GetBehaviors(control).Add(service); target = new PanelWrapper() { Target = control }; } void Panel_InjectMethods_Core<T>(ViewInjectionService service, IPanelWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; object vm1 = new object(); object vm2 = new object(); UIElementCollection children = (UIElementCollection)target.Children; Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Inject(null, vm1); iService.Inject(null, vm2, typeof(TestView1)); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm1, ((ContentPresenter)children[0]).Content); Assert.AreSame(vm2, ((ContentPresenter)children[1]).Content); Assert.AreSame(vm2, LayoutTreeHelper.GetVisualChildren(children[1]).OfType<TestView1>().First().DataContext); }); EnqueueTestComplete(); } void Panel_RemoveViewModelSimpleTest_Core<T>(ViewInjectionService service, IPanelWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; int viewModelClosingCommandCount = 0; service.ViewModelClosingCommand = new DelegateCommand(() => viewModelClosingCommandCount++); object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Remove(new object()); iService.Inject(null, vm1); iService.Inject(null, vm2); iService.Remove(new object()); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { iService.SelectedViewModel = vm1; iService.Remove(vm1); Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, viewModelClosingCommandCount); Assert.IsNull(iService.SelectedViewModel); iService.Inject(null, vm1); iService.SelectedViewModel = vm1; Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm1, iService.SelectedViewModel); iService.Remove(vm2); Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(2, viewModelClosingCommandCount); Assert.AreSame(vm1, iService.SelectedViewModel); iService.Remove(vm1); Assert.AreEqual(0, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(3, viewModelClosingCommandCount); Assert.IsNull(iService.SelectedViewModel); }); EnqueueTestComplete(); } #endregion #region ItemsControl [Test, Asynchronous] public void ItemsControl_InvalidInitialization() { ItemsControl control = new ItemsControl() { ItemsSource = new List<object>() }; ContentPresenter_InvalidInitializationTest_Core(control, "It is impossible to use ViewInjectionService for the control that has the ItemsSource property set."); } [Test, Asynchronous] public void ItemsControl_InjectMethods() { ViewInjectionService service; ItemsControlWrapper target; InitItemsControlTest(out service, out target); ItemsControl_InjectMethods_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ItemsControl_InjectWithItemTemplate() { ViewInjectionService service; ItemsControlWrapper target; InitItemsControlTest(out service, out target); ItemsControl_InjectWithItemTemplate_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ItemsControl_SelectedViewModel() { ViewInjectionService service; ItemsControlWrapper target; InitItemsControlTest(out service, out target); ItemsControl_SelectedViewModel_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ItemsControl_RemoveViewModel() { ViewInjectionService service; ItemsControlWrapper target; InitItemsControlTest(out service, out target); ItemsControl_RemoveViewModelSimpleTest_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void ItemsControl_CancelRemoveViewModel() { ViewInjectionService service; ItemsControlWrapper target; InitItemsControlTest(out service, out target); ContentPresenter_CancelRemoveViewModelTest_Core(service); service = null; target = null; ContentPresenter_TestMemoryReleased(); } void InitItemsControlTest(out ViewInjectionService service, out ItemsControlWrapper target) { ItemsControl control = new ItemsControl(); service = new ViewInjectionService(); Interaction.GetBehaviors(control).Add(service); target = new ItemsControlWrapper() { Target = control }; } void ItemsControl_InjectMethods_Core<T>(ViewInjectionService service, IItemsControlWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreSame(service.Strategy.ViewModels, target.ItemsSource); iService.Inject(null, vm1); Assert.AreEqual(1, iService.ViewModels.Count()); iService.Inject(null, vm2, typeof(TestView1)); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm1, LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<ContentPresenter>().First().DataContext); Assert.AreSame(vm2, LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<TestView1>().First().DataContext); }); EnqueueTestComplete(); } void ItemsControl_InjectWithItemTemplate_Core<T>(ViewInjectionService service, IItemsControlWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; target.ItemTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(TextBox)) }; object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Inject(null, vm1); AssertHelper.AssertThrows<InvalidOperationException>(() => { iService.Inject(null, vm2, typeof(TestView1)); }, x => Assert.AreEqual("ViewInjectionService cannot create view by name or type, because the target control has the ItemTemplate/ItemTemplateSelector property set.", x.Message)); iService.Inject(null, vm2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm1, LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<TextBox>().First(x => x.DataContext == vm1).DataContext); Assert.AreSame(vm2, LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<TextBox>().First(x => x.DataContext == vm2).DataContext); }); EnqueueTestComplete(); } void ItemsControl_SelectedViewModel_Core<T>(ViewInjectionService service, IItemsControlWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; int selectedViewModelChangedCount = 0; service.SelectedViewModelChangedCommand = new DelegateCommand(() => selectedViewModelChangedCount++); object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Inject(null, vm1); iService.Inject(null, vm2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(0, selectedViewModelChangedCount); Assert.IsNull(iService.SelectedViewModel); iService.SelectedViewModel = vm1; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, selectedViewModelChangedCount); Assert.AreSame(vm1, iService.SelectedViewModel); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { AssertHelper.AssertThrows<InvalidOperationException>(() => { iService.SelectedViewModel = new object(); }, x => Assert.AreEqual("Cannot set the SelectedViewModel property to a value that does not exist in the ViewModels collection. Inject the view model before selecting it.", x.Message)); }); EnqueueTestComplete(); } void ItemsControl_RemoveViewModelSimpleTest_Core<T>(ViewInjectionService service, IItemsControlWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; int viewModelClosingCommandCount = 0; service.ViewModelClosingCommand = new DelegateCommand(() => viewModelClosingCommandCount++); object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Remove(new object()); iService.Inject(null, vm1); Assert.AreEqual(1, iService.ViewModels.Count()); iService.Inject(null, vm2); iService.Remove(new object()); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { iService.SelectedViewModel = vm1; iService.Remove(vm1); Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, viewModelClosingCommandCount); Assert.IsNull(iService.SelectedViewModel); iService.Inject(null, vm1); Assert.AreEqual(2, iService.ViewModels.Count()); iService.SelectedViewModel = vm1; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { iService.Remove(vm2); Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(2, viewModelClosingCommandCount); Assert.AreSame(vm1, iService.SelectedViewModel); iService.Remove(vm1); Assert.AreEqual(0, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(3, viewModelClosingCommandCount); Assert.IsNull(iService.SelectedViewModel); }); EnqueueTestComplete(); } #endregion #region Selector [Test, Asynchronous] public void Selector_InvalidInitialization() { TabControl control = new TabControl() { ItemsSource = new List<object>() }; ContentPresenter_InvalidInitializationTest_Core(control, "It is impossible to use ViewInjectionService for the control that has the ItemsSource property set."); } [Test, Asynchronous] public void Selector_SelectedViewModel() { ViewInjectionService service; SelectorWrapper target; InitSelectorTest(out service, out target); Selector_SelectedViewModel_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void Selector_RemoveViewModel() { ViewInjectionService service; SelectorWrapper target; InitSelectorTest(out service, out target); Selector_RemoveViewModelSimpleTest_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void Selector_CancelRemoveViewModel() { ViewInjectionService service; SelectorWrapper target; InitSelectorTest(out service, out target); ContentPresenter_CancelRemoveViewModelTest_Core(service); service = null; target = null; ContentPresenter_TestMemoryReleased(); } void InitSelectorTest(out ViewInjectionService service, out SelectorWrapper target) { TabControl control = new TabControl(); service = new ViewInjectionService(); Interaction.GetBehaviors(control).Add(service); target = new SelectorWrapper() { Target = control }; } void Selector_SelectedViewModel_Core<T>(ViewInjectionService service, ISelectorWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; int selectedViewModelChangedCount = 0; service.SelectedViewModelChangedCommand = new DelegateCommand(() => selectedViewModelChangedCount++); object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Inject(null, vm1); iService.Inject(null, vm2); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, selectedViewModelChangedCount); Assert.AreSame(vm1, iService.SelectedViewModel); Assert.AreSame(vm1, target.SelectedItem); iService.SelectedViewModel = vm2; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(2, selectedViewModelChangedCount); Assert.AreSame(vm2, iService.SelectedViewModel); Assert.AreSame(vm2, target.SelectedItem); target.SelectedItem = vm1; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(3, selectedViewModelChangedCount); Assert.AreSame(vm1, iService.SelectedViewModel); Assert.AreSame(vm1, target.SelectedItem); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { AssertHelper.AssertThrows<InvalidOperationException>(() => { iService.SelectedViewModel = new object(); }, x => Assert.AreEqual("Cannot set the SelectedViewModel property to a value that does not exist in the ViewModels collection. Inject the view model before selecting it.", x.Message)); }); EnqueueTestComplete(); } void Selector_RemoveViewModelSimpleTest_Core<T>(ViewInjectionService service, ISelectorWrapper<T> target) where T : FrameworkElement { IViewInjectionService iService = service; int viewModelClosingCommandCount = 0; service.ViewModelClosingCommand = new DelegateCommand(() => viewModelClosingCommandCount++); object vm1 = new object(); object vm2 = new object(); Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { iService.Remove(new object()); iService.Inject(null, vm1); Assert.AreEqual(1, iService.ViewModels.Count()); iService.Inject(null, vm2); iService.Remove(new object()); Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { iService.SelectedViewModel = vm1; iService.Remove(vm1); Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, viewModelClosingCommandCount); Assert.AreSame(vm2, iService.SelectedViewModel); iService.Inject(null, vm1); Assert.AreEqual(2, iService.ViewModels.Count()); iService.SelectedViewModel = vm1; }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { iService.Remove(vm2); Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(2, viewModelClosingCommandCount); Assert.AreSame(vm1, iService.SelectedViewModel); iService.Remove(vm1); Assert.AreEqual(0, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(3, viewModelClosingCommandCount); Assert.IsNull(iService.SelectedViewModel); }); EnqueueTestComplete(); } #endregion #region TabControl [Test, Asynchronous] public void TabControl_InjectMethods() { ViewInjectionService service; TabControlWrapper target; InitTabControlTest(out service, out target); TabControl_InjectMethods_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void TabControl_InjectWithItemTemplate() { ViewInjectionService service; TabControlWrapper target; InitTabControlTest(out service, out target); TabControl_InjectWithItemTemplate_Core(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void TabControl_SelectedViewModel() { ViewInjectionService service; TabControlWrapper target; InitTabControlTest(out service, out target); Selector_SelectedViewModel_Core<Selector>(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void TabControl_RemoveViewModel() { ViewInjectionService service; TabControlWrapper target; InitTabControlTest(out service, out target); Selector_RemoveViewModelSimpleTest_Core<Selector>(service, target); service = null; target = null; ContentPresenter_TestMemoryReleased(); } [Test, Asynchronous] public void TabControl_CancelRemoveViewModel() { ViewInjectionService service; TabControlWrapper target; InitTabControlTest(out service, out target); ContentPresenter_CancelRemoveViewModelTest_Core(service); service = null; target = null; ContentPresenter_TestMemoryReleased(); } void InitTabControlTest(out ViewInjectionService service, out TabControlWrapper target) { TabControl control = new TabControl() { ItemTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(TextBox)) } }; service = new ViewInjectionService(); Interaction.GetBehaviors(control).Add(service); target = new TabControlWrapper() { Target = control }; } void TabControl_InjectMethods_Core(ViewInjectionService service, TabControlWrapper target) { CommonTabControl_InjectMethods_Core(service, target, "PART_SelectedContentHost", "HeaderPanel"); } void CommonTabControl_InjectMethods_Core(ViewInjectionService service, ItemsControlWrapper target, string contentHostElementName, string headerPanelElementName) { IViewInjectionService iService = service; object vm1 = new object(); object vm2 = new object(); FrameworkElement contentHost = null; FrameworkElement headerPanel = null; Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreSame(service.Strategy.ViewModels, target.ItemsSource); contentHost = LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<FrameworkElement>().First(x => x.Name == contentHostElementName); headerPanel = LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<FrameworkElement>().First(x => x.Name == headerPanelElementName); iService.Inject(null, vm1); iService.SelectedViewModel = vm1; Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm1, LayoutTreeHelper.GetVisualChildren(headerPanel).OfType<TextBox>().First(x => x.DataContext == vm1).DataContext); Assert.AreSame(vm1, LayoutTreeHelper.GetVisualChildren(contentHost).OfType<FrameworkElement>().First(x => x.DataContext == vm1).DataContext); iService.Inject(null, vm2, typeof(TestView1)); iService.SelectedViewModel = vm2; Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm2, LayoutTreeHelper.GetVisualChildren(headerPanel).OfType<TextBox>().First(x => x.DataContext == vm2).DataContext); Assert.AreSame(vm2, LayoutTreeHelper.GetVisualChildren(contentHost).OfType<TestView1>().First().DataContext); iService.SelectedViewModel = vm2; }); EnqueueTestComplete(); } void TabControl_InjectWithItemTemplate_Core(ViewInjectionService service, TabControlWrapper target) { CommonTabControl_InjectWithItemTemplate_Core(service, target, "PART_SelectedContentHost", "HeaderPanel"); } void CommonTabControl_InjectWithItemTemplate_Core(ViewInjectionService service, ItemsControlWrapper target, string contentHostElementName, string headerPanelElementName) { IViewInjectionService iService = service; target.ItemTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(TextBox)) }; object vm1 = new object(); object vm2 = new object(); FrameworkElement contentHost = null; FrameworkElement headerPanel = null; Window.Content = service.AssociatedObject; EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreSame(service.Strategy.ViewModels, target.ItemsSource); contentHost = LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<FrameworkElement>().First(x => x.Name == contentHostElementName); headerPanel = LayoutTreeHelper.GetVisualChildren(service.AssociatedObject).OfType<FrameworkElement>().First(x => x.Name == headerPanelElementName); iService.Inject(null, vm1); iService.SelectedViewModel = vm1; Assert.AreEqual(1, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm1, LayoutTreeHelper.GetVisualChildren(headerPanel).OfType<TextBox>().First(x => x.DataContext == vm1).DataContext); Assert.AreSame(vm1, LayoutTreeHelper.GetVisualChildren(contentHost).OfType<TextBox>().First(x => x.DataContext == vm1).DataContext); AssertHelper.AssertThrows<InvalidOperationException>(() => { iService.Inject(null, vm2, typeof(TestView1)); }, x => Assert.AreEqual("ViewInjectionService cannot create view by name or type, because the target control has the ItemTemplate/ItemTemplateSelector property set.", x.Message)); iService.Inject(null, vm2); iService.SelectedViewModel = vm2; Assert.AreEqual(2, iService.ViewModels.Count()); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreSame(vm2, LayoutTreeHelper.GetVisualChildren(headerPanel).OfType<TextBox>().First(x => x.DataContext == vm2).DataContext); Assert.AreSame(vm2, LayoutTreeHelper.GetVisualChildren(contentHost).OfType<TextBox>().First().DataContext); iService.SelectedViewModel = vm2; }); EnqueueTestComplete(); } #endregion } [TestFixture] public class ViewInjectionServiceComplexTests : BaseWpfFixture { class VMBase : ViewModelBase { public int NavigatedCount { get; private set; } public int NavigatedAwayCount { get; private set; } public int ViewModelClosingCount { get; private set; } public bool CancelViewModelClosing { get; set; } public VMBase() { NavigatedCount = 0; NavigatedAwayCount = 0; ViewModelClosingCount = 0; CancelViewModelClosing = false; ViewInjectionManager.Default.RegisterNavigatedEventHandler(this, () => NavigatedCount++); ViewInjectionManager.Default.RegisterNavigatedAwayEventHandler(this, () => NavigatedAwayCount++); ViewInjectionManager.Default.RegisterViewModelClosingEventHandler(this, x => { ViewModelClosingCount++; x.Cancel = CancelViewModelClosing; }); } } class TabViewModel : VMBase { public string RegionName { get { return GetProperty(() => RegionName); } set { SetProperty(() => RegionName, value); } } } class TabView : Grid { public TabView() { ViewInjectionService service = new ViewInjectionService(); BindingOperations.SetBinding(service, ViewInjectionService.RegionNameProperty, new Binding("RegionName")); Interaction.GetBehaviors(this).Add(service); } } class TabContentViewModel : VMBase { } class TabContentView : Grid { } [Test, Asynchronous] public void ComplexTest1() { TabViewModel tab1VM = null; TabViewModel tab2VM = null; TabContentViewModel tab1ContentVM = null; TabContentViewModel tab2ContentVM = null; ViewInjectionManager.Default.Inject("mainRegion", "tab1", () => tab1VM = new TabViewModel() { RegionName = "tab1ContentRegion" }, typeof(TabView)); ViewInjectionManager.Default.Inject("mainRegion", "tab2", () => tab2VM = new TabViewModel() { RegionName = "tab2ContentRegion" }, typeof(TabView)); ViewInjectionManager.Default.Inject("tab1ContentRegion", "tab1Content", () => tab1ContentVM = new TabContentViewModel(), typeof(TabContentView)); ViewInjectionManager.Default.Inject("tab2ContentRegion", "tab2Content", () => tab2ContentVM = new TabContentViewModel(), typeof(TabContentView)); TabControl tabControl = new TabControl(); ViewInjectionService mainService = new ViewInjectionService() { RegionName = "mainRegion" }; Interaction.GetBehaviors(tabControl).Add(mainService); Window.Content = tabControl; EnqueueShowWindow(); EnqueueCallback(() => { Assert.AreEqual(1, tab1VM.NavigatedCount); Assert.AreEqual(0, tab1ContentVM.NavigatedCount); Assert.IsNull(tab2ContentVM); LayoutTreeHelper.GetVisualChildren(tabControl).OfType<TabContentView>().First(x => x.DataContext == tab1ContentVM); ViewInjectionManager.Default.Navigate("tab2ContentRegion", "tab2Content"); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, tab1VM.NavigatedCount); Assert.AreEqual(0, tab1ContentVM.NavigatedCount); Assert.IsNull(tab2ContentVM); ViewInjectionManager.Default.Navigate("mainRegion", "tab2"); ViewInjectionManager.Default.Navigate("tab2ContentRegion", "tab2Content"); }); EnqueueWindowUpdateLayout(); EnqueueCallback(() => { Assert.AreEqual(1, tab1VM.NavigatedCount); Assert.AreEqual(1, tab1VM.NavigatedAwayCount); Assert.AreEqual(1, tab2VM.NavigatedCount); Assert.AreEqual(0, tab1ContentVM.NavigatedCount); Assert.AreEqual(0, tab1ContentVM.NavigatedAwayCount); Assert.AreEqual(1, tab2ContentVM.NavigatedCount); LayoutTreeHelper.GetVisualChildren(tabControl).OfType<TabContentView>().First(x => x.DataContext == tab2ContentVM); }); EnqueueTestComplete(); } } }
/* Copyright (c) 2005-2006 Tomas Matousek and Martin Maly. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ /* not implemented yet: # mb_ check_ encoding # mb_ convert_ case # mb_ convert_ encoding # mb_ convert_ kana # mb_ convert_ variables # mb_ decode_ mimeheader # mb_ decode_ numericentity # mb_ detect_ encoding # mb_ detect_ order # mb_ encode_ mimeheader # mb_ encode_ numericentity # mb_ encoding_ aliases # mb_ ereg_ match # mb_ ereg_ replace # mb_ ereg_ search_ getpos # mb_ ereg_ search_ getregs # mb_ ereg_ search_ init # mb_ ereg_ search_ pos # mb_ ereg_ search_ regs # mb_ ereg_ search_ setpos # mb_ ereg_ search # mb_ ereg # mb_ eregi_ replace # mb_ eregi # mb_ get_ info # mb_ http_ input # mb_ http_ output # mb_ output_ handler */ using System; using System.Data; using System.Collections; using System.Text; using System.Data.SqlClient; using PHP.Core; using System.Collections.Generic; namespace PHP.Library.Strings { /// <summary> /// Implements PHP functions provided by multi-byte-string extension. /// </summary> public static class MultiByteString { #region GlobalInfo private class StaticInfo { public Encoding InternalEncoding = null; public Encoding RegexEncoding = null; public RegexOptions RegexOptions = RegexOptions.DotMatchesNewLine | RegexOptions.ConvertMatchBeginEnd; public RegexSyntaxModes RegexSyntaxMode = RegexSyntaxModes.POSIXExtendedRegex; //public string MailLanguage = null; public static StaticInfo Get { get { StaticInfo info; var properties = ThreadStatic.Properties; if (properties.TryGetProperty<StaticInfo>(out info) == false || info == null) { properties.SetProperty(info = new StaticInfo()); } return info; } } } #endregion #region Constants [Flags] public enum OverloadConstants { [ImplementsConstant("MB_OVERLOAD_MAIL")] MB_OVERLOAD_MAIL = 1, [ImplementsConstant("MB_OVERLOAD_STRING")] MB_OVERLOAD_STRING = 2, [ImplementsConstant("MB_OVERLOAD_REGEX")] MB_OVERLOAD_REGEX = 4, } [Flags] public enum CaseConstants { [ImplementsConstant("MB_CASE_UPPER")] MB_CASE_UPPER = 0, [ImplementsConstant("MB_CASE_LOWER")] MB_CASE_LOWER = 1, [ImplementsConstant("MB_CASE_TITLE")] MB_CASE_TITLE = 2, } #endregion #region Encodings private static Dictionary<string, Encoding> _encodings = null; public static Dictionary<string, Encoding>/*!*/Encodings { get { if (_encodings == null) { Dictionary<string, Encoding> enc = new Dictionary<string, Encoding>(180, StringComparer.OrdinalIgnoreCase); // encoding names used in PHP //enc["pass"] = Encoding.Default; // TODO: "pass" encoding enc["auto"] = Configuration.Application.Globalization.PageEncoding; enc["wchar"] = Encoding.Unicode; //byte2be //byte2le //byte4be //byte4le //BASE64 //UUENCODE //HTML-ENTITIES //Quoted-Printable //7bit //8bit //UCS-4 //UCS-4BE //UCS-4LE //UCS-2 //UCS-2BE //UCS-2LE //UTF-32 //UTF-32BE //UTF-32LE //UTF-16 //UTF-16BE enc["UTF-16LE"] = Encoding.Unicode; // alias UTF-16 //UTF-8 //UTF-7 //UTF7-IMAP enc["ASCII"] = Encoding.ASCII; // alias us-ascii //EUC-JP //SJIS //eucJP-win //SJIS-win //CP51932 //JIS //ISO-2022-JP //ISO-2022-JP-MS //Windows-1252 //Windows-1254 //ISO-8859-1 //ISO-8859-2 //ISO-8859-3 //ISO-8859-4 //ISO-8859-5 //ISO-8859-6 //ISO-8859-7 //ISO-8859-8 //ISO-8859-9 //ISO-8859-10 //ISO-8859-13 //ISO-8859-14 //ISO-8859-15 //ISO-8859-16 //EUC-CN //CP936 //HZ //EUC-TW //BIG-5 //EUC-KR //UHC //ISO-2022-KR //Windows-1251 //CP866 //KOI8-R //KOI8-U //ArmSCII-8 //CP850 // .NET encodings foreach (var encoding in Encoding.GetEncodings()) enc[encoding.Name] = encoding.GetEncoding(); _encodings = enc; } return _encodings; } } /// <summary> /// Get encoding based on the PHP name. Can return null is such encoding is not defined. /// </summary> /// <param name="encodingName"></param> /// <returns></returns> public static Encoding GetEncoding(string encodingName) { Encoding encoding; if (!Encodings.TryGetValue(encodingName, out encoding)) return null; return encoding; } #endregion #region Object conversion using specified encoding private delegate Encoding getEncoding(); /// <summary> /// Converts PhpBytes using specified encoding. If any other object is provided, encoding is not performed. /// </summary> /// <param name="str"></param> /// <param name="encodingGetter"></param> /// <returns></returns> private static string ObjectToString(object str, getEncoding encodingGetter) { if (str is PhpBytes) { PhpBytes bytes = (PhpBytes)str; Encoding encoding = encodingGetter(); if (encoding == null) return null; return encoding.GetString(bytes.ReadonlyData, 0, bytes.Length); } else { // .NET String should be always UTF-16, given encoding is irrelevant return PHP.Core.Convert.ObjectToString(str); } } #endregion #region mb_internal_encoding, mb_preferred_mime_name /// <summary> /// Multi Byte String Internal Encoding. /// </summary> public static Encoding/*!*/InternalEncoding { get { return StaticInfo.Get.InternalEncoding ?? Configuration.Application.Globalization.PageEncoding; } private set { StaticInfo.Get.InternalEncoding = value; } } /// <summary> /// Multi Byte String Internal Encoding IANA name. /// </summary> public static string InternalEncodingName { get { return InternalEncoding.WebName; } } /// <summary> /// Get encoding used by default in the extension. /// </summary> /// <returns></returns> [ImplementsFunction("mb_internal_encoding")] public static string GetInternalEncoding() { return InternalEncoding.WebName; } /// <summary> /// Set the encoding used by the extension. /// </summary> /// <param name="encodingName"></param> /// <returns>True is encoding was set, otherwise false.</returns> [ImplementsFunction("mb_internal_encoding")] public static bool SetInternalEncoding(string encodingName) { Encoding enc = GetEncoding(encodingName); if (enc != null) { InternalEncoding = enc; return true; } else { return false; } } /// <summary> /// Get a MIME charset string for a specific encoding. /// </summary> /// <param name="encoding_name">The encoding being checked. Its WebName or PHP/Phalanger name.</param> /// <returns>The MIME charset string for given character encoding.</returns> [ImplementsFunction("mb_preferred_mime_name")] public static string GetPreferredMimeName(string encoding_name) { Encoding encoding; if ( (encoding = Encoding.GetEncoding(encoding_name)) == null && // .NET encodings (by their WebName) (encoding = GetEncoding(encoding_name)) == null //try PHP internal encodings too (by PHP/Phalanger name) ) { PhpException.ArgumentValueNotSupported("encoding_name", encoding); return null; } return encoding.BodyName; // it seems to return right MIME } #endregion #region mb_regex_encoding, mb_regex_set_options /// <summary> /// Multi Byte String Internal Encoding. /// </summary> public static Encoding/*!*/RegexEncoding { get { return StaticInfo.Get.RegexEncoding ?? Configuration.Application.Globalization.PageEncoding; } private set { StaticInfo.Get.RegexEncoding = value; } } /// <summary> /// Multi Byte String regex Encoding IANA name. /// </summary> public static string RegexEncodingName { get { return RegexEncoding.WebName; } } /// <summary> /// Get encoding used by regex in the extension. /// </summary> /// <returns></returns> [ImplementsFunction("mb_regex_encoding")] public static string GetRegexEncoding() { return RegexEncoding.WebName; } /// <summary> /// Set the encoding used by the extension in regex functions. /// </summary> /// <param name="encodingName"></param> /// <returns>True is encoding was set, otherwise false.</returns> [ImplementsFunction("mb_regex_encoding")] public static bool SetRegexEncoding(string encodingName) { Encoding enc = GetEncoding(encodingName); if (enc != null) { RegexEncoding = enc; return true; } else { return false; } } #region regex options [Flags] private enum RegexOptions { None = 0, /// <summary> /// i /// </summary> AmbiguityMatch = 1, /// <summary> /// x /// </summary> ExtendedPatternForm = 2, /// <summary> /// m /// </summary> DotMatchesNewLine = 4, /// <summary> /// s /// </summary> ConvertMatchBeginEnd = 8, /// <summary> /// l /// </summary> FindLongestMatch = 16, /// <summary> /// n /// </summary> IgnoreEmptyMatch = 32, /// <summary> /// e /// </summary> EvalResultingCode = 64, } private enum RegexSyntaxModes { /// <summary> /// d /// </summary> POSIXExtendedRegex, } /// <summary> /// Determines if given combination of options is enabled. /// </summary> /// <param name="opt">Option or mask of options to test.</param> /// <returns>True if given option mask is enabled.</returns> private static bool OptionEnabled(RegexOptions opt) { return (StaticInfo.Get.RegexOptions & opt) != 0; } /// <summary> /// Determines if given syntax mode is set. /// </summary> /// <param name="opt">Syntax mode to test.</param> /// <returns>True if given syntax mode is enabled.</returns> private static bool OptionEnabled(RegexSyntaxModes opt) { return (StaticInfo.Get.RegexSyntaxMode == opt); } #endregion /// <summary> /// Get currently set regex options. /// </summary> /// <returns>Option string.</returns> [ImplementsFunction("mb_regex_set_options")] public static string GetRegexOptions() { string optionString = string.Empty; if (OptionEnabled(RegexOptions.AmbiguityMatch)) optionString += 'i'; if (OptionEnabled(RegexOptions.ExtendedPatternForm)) optionString += 'x'; if (OptionEnabled(RegexOptions.DotMatchesNewLine)) optionString += 'm'; if (OptionEnabled(RegexOptions.ConvertMatchBeginEnd)) optionString += 's'; if (OptionEnabled(RegexOptions.FindLongestMatch)) optionString += 'l'; if (OptionEnabled(RegexOptions.IgnoreEmptyMatch)) optionString += 'n'; if (OptionEnabled(RegexOptions.EvalResultingCode)) optionString += 'e'; if (OptionEnabled(RegexSyntaxModes.POSIXExtendedRegex)) optionString += 'd'; else throw new NotImplementedException("syntax mode not catch by mb_regex_set_options()!"); return optionString; } /// <summary> /// Set new regex options. /// </summary> /// <param name="options">Option string.</param> /// <returns>New option string.</returns> /// <remarks> /// Regex options: /// Option Meaning /// i Ambiguity match on /// x Enables extended pattern form /// m '.' matches with newlines /// s '^' -> '\A', '$' -> '\Z' /// p Same as both the m and s options /// l Finds longest matches /// n Ignores empty matches /// e eval() resulting code /// /// Regex syntax modes: /// Mode Meaning /// j (not supported) Java (Sun java.util.regex) /// u (not supported) GNU regex /// g (not supported) grep /// c (not supported) Emacs /// r (not supported) Ruby /// z (not supported) Perl /// b (not supported) POSIX Basic regex /// d POSIX Extended regex /// </remarks> [ImplementsFunction("mb_regex_set_options")] public static string SetRegexOptions(string options) { RegexOptions newRegexOptions = RegexOptions.None; RegexSyntaxModes newRegexSyntaxModes = RegexSyntaxModes.POSIXExtendedRegex; foreach (char c in options) { switch (c) { case 'i': newRegexOptions |= RegexOptions.AmbiguityMatch; break; case 'x': newRegexOptions |= RegexOptions.ExtendedPatternForm; break; case 'm': newRegexOptions |= RegexOptions.DotMatchesNewLine; break; case 's': newRegexOptions |= RegexOptions.ConvertMatchBeginEnd; break; case 'p': newRegexOptions |= RegexOptions.DotMatchesNewLine | RegexOptions.ConvertMatchBeginEnd; break; case 'l': newRegexOptions |= RegexOptions.FindLongestMatch; break; case 'n': newRegexOptions |= RegexOptions.IgnoreEmptyMatch; break; case 'e': newRegexOptions |= RegexOptions.EvalResultingCode; break; case 'd': newRegexSyntaxModes = RegexSyntaxModes.POSIXExtendedRegex; break; default: PhpException.ArgumentValueNotSupported("options", c); break; } } // StaticInfo.Get.RegexOptions = newRegexOptions; StaticInfo.Get.RegexSyntaxMode = newRegexSyntaxModes; return GetRegexOptions(); } #endregion #region mb_substr, mb_strcut #region mb_substr implementation [ImplementsFunction("mb_substr")] [return: CastToFalse] public static string SubString(object str, int start) { return SubString(str, start, -1, () => InternalEncoding); } [ImplementsFunction("mb_substr")] [return: CastToFalse] public static string SubString(object str, int start, int length) { return SubString(str, start, length, () => InternalEncoding); } [ImplementsFunction("mb_substr")] [return:CastToFalse] public static string SubString(object str, int start, int length, string encoding) { return SubString(str, start, length, () => GetEncoding(encoding)); } #endregion #region mb_strcut (in PHP it behaves differently, but in .NET it is an alias for mb_substr) [ImplementsFunction("mb_strcut")] [return: CastToFalse] public static string CutString(object str, int start) { return SubString(str, start, -1, () => InternalEncoding); } [ImplementsFunction("mb_strcut")] [return: CastToFalse] public static string CutString(object str, int start, int length) { return SubString(str, start, length, () => InternalEncoding); } [ImplementsFunction("mb_strcut")] [return: CastToFalse] public static string CutString(object str, int start, int length, string encoding) { return SubString(str, start, length, () => GetEncoding(encoding)); } #endregion private static string SubString(object str, int start, int length, getEncoding encodingGetter) { // get the Unicode representation of the string string ustr = ObjectToString(str, encodingGetter); if (ustr == null) return null; // start counting from the end of the string if (start < 0) start = ustr.Length + start; // can result in negative start again -> invalid if (length == -1) length = ustr.Length; // check boundaries if (start >= ustr.Length || length < 0 || start < 0) return null; if (length == 0) return string.Empty; // return the substring return (start + length > ustr.Length) ? ustr.Substring(start) : ustr.Substring(start, length); } #endregion #region mb_substr_count [ImplementsFunction("mb_substr_count")] public static int SubStringCount(string haystack , string needle ) { return SubStringCount(haystack, needle, () => InternalEncoding); } [ImplementsFunction("mb_substr_count")] public static int SubStringCount(string haystack, string needle, string encoding) { return SubStringCount(haystack, needle, () => GetEncoding(encoding)); } private static int SubStringCount(string haystack, string needle, getEncoding encodingGetter) { string uhaystack = ObjectToString(haystack, encodingGetter); string uneedle = ObjectToString(needle, encodingGetter); if (uhaystack == null || uneedle == null) return 0; return PhpStrings.SubstringCount(uhaystack, uneedle); } #endregion #region mb_substitute_character [ImplementsFunction("mb_substitute_character")] public static object GetSubstituteCharacter() { PhpException.FunctionNotSupported(); return false; } [ImplementsFunction("mb_substitute_character")] public static object SetSubstituteCharacter(object substrchar) { PhpException.FunctionNotSupported(); return "none"; } #endregion #region mb_strwidth, mb_strimwidth /// <summary> /// Determines the char width. /// </summary> /// <param name="c">Character.</param> /// <returns>The width of the character.</returns> private static int CharWidth(char c) { //Chars Width //U+0000 - U+0019 0 //U+0020 - U+1FFF 1 //U+2000 - U+FF60 2 //U+FF61 - U+FF9F 1 //U+FFA0 - 2 if (c <= 0x0019) return 0; else if (c <= 0x1fff) return 1; else if (c <= 0xff60) return 2; else if (c <= 0xff9f) return 1; else return 2; } private static int StringWidth(string str) { if (str == null) return 0; int width = 0; foreach (char c in str) width += CharWidth(c); return width; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="width">Characters remaining.</param> /// <returns></returns> private static string StringTrimByWidth(string/*!*/str, ref int width) { if (str == null) return null; int i = 0; foreach (char c in str) { int w = CharWidth(c); if (w < width) { ++i; width -= w; } else if (w == width) { ++i; width = 0; break; } else break; } return (i < str.Length) ? str.Remove(i) : str; } #region mb_strwidth implementation [ImplementsFunction("mb_strwidth")] public static int StringWidth(object str) { return StringWidth(str, () => InternalEncoding); } /// <summary> /// The string width. Not the string length. /// Multi-byte characters are usually twice the width of single byte characters. /// </summary> /// <param name="str">The string being decoded. </param> /// <param name="encoding">The encoding parameter is the character encoding in case of PhpBytes is used. If it is omitted, the internal character encoding value will be used.</param> /// <returns>The width of string str.</returns> /// <remarks> /// Chars Width /// U+0000 - U+0019 0 /// U+0020 - U+1FFF 1 /// U+2000 - U+FF60 2 /// U+FF61 - U+FF9F 1 /// U+FFA0 - 2 /// </remarks> [ImplementsFunction("mb_strwidth")] public static int StringWidth(object str, string encoding) { return StringWidth(str, () =>GetEncoding(encoding)); } private static int StringWidth(object str, getEncoding encodingGetter) { return StringWidth(ObjectToString(str, encodingGetter)); } #endregion #region mb_strimwidth implementation [ImplementsFunction("mb_strimwidth")] public static string STrimWidth(object str, int start, int width) { return StringTrimByWidth(str, start, width, null, () => InternalEncoding); } [ImplementsFunction("mb_strimwidth")] public static string STrimWidth(object str, int start, int width, string trimmarker) { return StringTrimByWidth(str, start, width, trimmarker, () => InternalEncoding); } [ImplementsFunction("mb_strimwidth")] public static string STrimWidth(object str, int start, int width, string trimmarker, string encoding) { return StringTrimByWidth(str, start, width, trimmarker, () => GetEncoding(encoding)); } private static string StringTrimByWidth(object str, int start, int width, string trimmarker, getEncoding encodingGetter) { string ustr = ObjectToString(str, encodingGetter); if (start >= ustr.Length) return string.Empty; ustr = ustr.Substring(start); int ustrWidth = StringWidth(ustr); if (ustrWidth <= width) return ustr; // trim the string int trimmarkerWidth = StringWidth(trimmarker); width -= trimmarkerWidth; string trimmedStr = StringTrimByWidth(ustr, ref width); width += trimmarkerWidth; string trimmedTrimMarker = StringTrimByWidth(trimmarker, ref width); // return trimmedStr + trimmedTrimMarker; } #endregion #endregion #region mb_strtoupper, mb_strtolower [ImplementsFunction("mb_strtoupper")] public static string StrToUpper(object str) { return StrToUpper(str, () => InternalEncoding); } [ImplementsFunction("mb_strtoupper")] public static string StrToUpper(object str, string encoding) { return StrToUpper(str, () => GetEncoding(encoding)); } private static string StrToUpper(object str, getEncoding encodingGetter) { string ustr = ObjectToString(str, encodingGetter); return ustr.ToUpperInvariant(); } [ImplementsFunction("mb_strtolower")] public static string StrToLower(object str) { return StrToLower(str, () => InternalEncoding); } [ImplementsFunction("mb_strtolower")] public static string StrToLower(object str, string encoding) { return StrToLower(str, () => GetEncoding(encoding)); } private static string StrToLower(object str, getEncoding encodingGetter) { string ustr = ObjectToString(str, encodingGetter); return ustr.ToLowerInvariant(); } #endregion #region mb_strstr, mb_stristr [ImplementsFunction("mb_strstr")] [return:CastToFalse] public static string StrStr(object haystack, object needle) { return StrStr(haystack, needle, false, () => InternalEncoding, false); } [ImplementsFunction("mb_strstr")] [return: CastToFalse] public static string StrStr(object haystack, object needle, bool part/*=FALSE*/) { return StrStr(haystack, needle, part, () => InternalEncoding, false); } [ImplementsFunction("mb_strstr")] [return: CastToFalse] public static string StrStr(object haystack, object needle, bool part/*=FALSE*/, string encoding) { return StrStr(haystack, needle, part, () => GetEncoding(encoding), false); } [ImplementsFunction("mb_stristr")] [return: CastToFalse] public static string StriStr(object haystack, object needle) { return StrStr(haystack, needle, false, () => InternalEncoding, true); } [ImplementsFunction("mb_stristr")] [return: CastToFalse] public static string StriStr(object haystack, object needle, bool part/*=FALSE*/) { return StrStr(haystack, needle, part, () => InternalEncoding, true); } [ImplementsFunction("mb_stristr")] [return: CastToFalse] public static string StriStr(object haystack, object needle, bool part/*=FALSE*/, string encoding) { return StrStr(haystack, needle, part, () => GetEncoding(encoding), true); } /// <summary> /// mb_strstr() finds the first occurrence of needle in haystack and returns the portion of haystack. If needle is not found, it returns FALSE. /// </summary> /// <param name="haystack">The string from which to get the first occurrence of needle</param> /// <param name="needle">The string to find in haystack</param> /// <param name="part">Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle. If set to FALSE, it returns all of haystack from the first occurrence of needle to the end.</param> /// <param name="encodingGetter">Character encoding name to use. If it is omitted, internal character encoding is used. </param> /// <param name="ignoreCase">Case insensitive.</param> /// <returns>Returns the portion of haystack, or FALSE (-1) if needle is not found.</returns> private static string StrStr(object haystack, object needle, bool part/* = false*/ , getEncoding encodingGetter, bool ignoreCase) { string uhaystack = ObjectToString(haystack, encodingGetter); string uneedle = ObjectToString(needle, encodingGetter); if (uhaystack == null || uneedle == null) // never happen return null; if (uneedle == String.Empty) { PhpException.InvalidArgument("needle", LibResources.GetString("arg:empty")); return null; } int index = (ignoreCase) ? uhaystack.ToLower().IndexOf(uneedle.ToLower()) : uhaystack.IndexOf(uneedle); return (index == -1) ? null : (part ? uhaystack.Substring(0, index) : uhaystack.Substring(index)); } #endregion #region mb_strpos, mb_stripos, mb_strrpos, mb_strripos #region mb_strpos stub [ImplementsFunction("mb_strpos")] [return: CastToFalse] public static int Strpos(object haystack, object needle) { return Strpos(haystack, needle, 0, () => InternalEncoding, false); } [ImplementsFunction("mb_strpos")] [return: CastToFalse] public static int Strpos(object haystack, object needle, int offset) { return Strpos(haystack, needle, offset, () => InternalEncoding, false); } [ImplementsFunction("mb_strpos")] [return:CastToFalse] public static int Strpos(object haystack, object needle, int offset, string encoding) { return Strpos(haystack, needle, offset, () => GetEncoding(encoding), false); } #endregion #region mb_stripos stub [ImplementsFunction("mb_stripos")] [return: CastToFalse] public static int Stripos(object haystack, object needle) { return Strpos(haystack, needle, 0, () => InternalEncoding, true); } [ImplementsFunction("mb_stripos")] [return: CastToFalse] public static int Stripos(object haystack, object needle, int offset) { return Strpos(haystack, needle, offset, () => InternalEncoding, true); } [ImplementsFunction("mb_stripos")] [return: CastToFalse] public static int Stripos(object haystack, object needle, int offset, string encoding) { return Strpos(haystack, needle, offset, () => GetEncoding(encoding), true); } #endregion #region mb_strrpos stub [ImplementsFunction("mb_strrpos")] [return: CastToFalse] public static int Strrpos(object haystack, object needle) { return Strrpos(haystack, needle, 0, () => InternalEncoding, false); } [ImplementsFunction("mb_strrpos")] [return: CastToFalse] public static int Strrpos(object haystack, object needle, int offset) { return Strrpos(haystack, needle, offset, () => InternalEncoding, false); } [ImplementsFunction("mb_strrpos")] [return: CastToFalse] public static int Strrpos(object haystack, object needle, int offset, string encoding) { return Strrpos(haystack, needle, offset, () => GetEncoding(encoding), false); } #endregion #region mb_strripos stub [ImplementsFunction("mb_strripos")] [return: CastToFalse] public static int Strripos(object haystack, object needle) { return Strrpos(haystack, needle, 0, () => InternalEncoding, true); } [ImplementsFunction("mb_strripos")] [return: CastToFalse] public static int Strripos(object haystack, object needle, int offset) { return Strrpos(haystack, needle, offset, () => InternalEncoding, true); } [ImplementsFunction("mb_strripos")] [return: CastToFalse] public static int Strripos(object haystack, object needle, int offset, string encoding) { return Strrpos(haystack, needle, offset, () => GetEncoding(encoding), true); } #endregion /// <summary> /// Implementation of <c>mb_str[i]pos</c> functions. /// </summary> private static int Strpos(object haystack, object needle, int offset, getEncoding encodingGetter, bool ignoreCase) { string uhaystack = ObjectToString(haystack, encodingGetter); string uneedle = ObjectToString(needle, encodingGetter); if (uhaystack == null || uneedle == null) return -1; if (offset < 0 || offset >= uhaystack.Length) { if (offset != uhaystack.Length) PhpException.InvalidArgument("offset", LibResources.GetString("arg:out_of_bounds")); return -1; } if (uneedle == String.Empty) { PhpException.InvalidArgument("needle", LibResources.GetString("arg:empty")); return -1; } if (ignoreCase) return uhaystack.ToLower().IndexOf(uneedle.ToLower(), offset); else return uhaystack.IndexOf(uneedle, offset); } /// <summary> /// Implementation of <c>mb_strr[i]pos</c> functions. /// </summary> private static int Strrpos(object haystack, object needle, int offset, getEncoding encodingGetter, bool ignoreCase) { string uhaystack = ObjectToString(haystack, encodingGetter); string uneedle = ObjectToString(needle, encodingGetter); if (uhaystack == null || uneedle == null) return -1; int end = uhaystack.Length - 1; if (offset > end || offset < -end - 1) { PhpException.InvalidArgument("offset", LibResources.GetString("arg:out_of_bounds")); return -1; } if (offset < 0) { end += uneedle.Length + offset; offset = 0; } if (uneedle.Length == 0) { PhpException.InvalidArgument("needle", LibResources.GetString("arg:empty")); return -1; } if (ignoreCase) return uhaystack.ToLower().LastIndexOf(uneedle.ToLower(), end, end - offset + 1); else return uhaystack.LastIndexOf(uneedle, end, end - offset + 1); } #endregion #region mb_strlen [ImplementsFunction("mb_strlen")] public static int StrLen(object str) { return StrLen(str, () => InternalEncoding); } [ImplementsFunction("mb_strlen")] public static int StrLen(object str, string encoding) { return StrLen(str, ()=>GetEncoding(encoding)); } /// <summary> /// Counts characters in a Unicode string or multi-byte string in PhpBytes. /// </summary> /// <param name="str">String or PhpBytes to use.</param> /// <param name="encodingGetter">Encoding used to encode PhpBytes</param> /// <returns>Number of unicode characters in given object.</returns> private static int StrLen(object str, getEncoding encodingGetter) { if (str == null) return 0; if (str.GetType() == typeof(string)) { return ((string)str).Length; } else if (str.GetType() == typeof(PhpBytes)) { Encoding encoding = encodingGetter(); if (encoding == null) throw new NotImplementedException(); return encoding.GetCharCount(((PhpBytes)str).ReadonlyData); } else { return (ObjectToString(str, encodingGetter) ?? string.Empty).Length; } } #endregion #region mb_strrchr, mb_strrichr #region mb_strrchr stub [ImplementsFunction("mb_strrchr")] [return: CastToFalse] public static string StrrChr(object haystack, object needle) { return StrrChr(haystack, needle, false, () => InternalEncoding, false); } [ImplementsFunction("mb_strrchr")] [return: CastToFalse] public static string StrrChr(object haystack, object needle, bool part/*=false*/) { return StrrChr(haystack, needle, part, () => InternalEncoding, false); } [ImplementsFunction("mb_strrchr")] [return:CastToFalse] public static string StrrChr(object haystack, object needle, bool part/*=false*/, string encoding) { return StrrChr(haystack, needle, part, () => GetEncoding(encoding), false); } #endregion #region mb_strrichr stub [ImplementsFunction("mb_strrichr")] [return: CastToFalse] public static string StrriChr(object haystack, object needle) { return StrrChr(haystack, needle, false, () => InternalEncoding, true); } [ImplementsFunction("mb_strrichr")] [return: CastToFalse] public static string StrriChr(object haystack, object needle, bool part/*=false*/) { return StrrChr(haystack, needle, part, () => InternalEncoding, true); } [ImplementsFunction("mb_strrichr")] [return: CastToFalse] public static string StrriChr(object haystack, object needle, bool part/*=false*/, string encoding) { return StrrChr(haystack, needle, part, () => GetEncoding(encoding), true); } #endregion private static string StrrChr(object haystack, object needle, bool beforeNeedle/*=false*/, getEncoding encodingGetter, bool ignoreCase) { string uhaystack = ObjectToString(haystack, encodingGetter); char cneedle; { string uneedle; if (needle is string) uneedle = (string)needle; else if (needle is PhpString) uneedle = ((IPhpConvertible)needle).ToString(); else if (needle is PhpBytes) { Encoding encoding = encodingGetter(); if (encoding == null) return null; PhpBytes bytes = (PhpBytes)needle; uneedle = encoding.GetString(bytes.ReadonlyData, 0, bytes.Length); } else { // needle as a character number Encoding encoding = encodingGetter(); if (encoding == null) return null; uneedle = encoding.GetString(new byte[] { unchecked((byte)Core.Convert.ObjectToInteger(needle)) }, 0, 1); } if (string.IsNullOrEmpty(uneedle)) return null; cneedle = uneedle[0]; } int index = (ignoreCase) ? uhaystack.ToLower().LastIndexOf(char.ToLower(cneedle)) : uhaystack.LastIndexOf(cneedle); if (index < 0) return null; return (beforeNeedle) ? uhaystack.Remove(index) : uhaystack.Substring(index); } #endregion #region mb_split [ImplementsFunction("mb_split")] public static PhpArray Split(object pattern, object str) { return Split(pattern,str,-1); } [ImplementsFunction("mb_split")] public static PhpArray Split(object pattern, object str, int limit /*= -1*/) { return Library.PosixRegExp.DoSplit( ObjectToString(pattern, ()=>RegexEncoding), ObjectToString(str, ()=>RegexEncoding), limit, limit != -1, false); } #endregion #region mb_language, mb_send_mail /*/// <summary> /// Multi Byte String language used by mail functions. /// </summary> public static string MailLanguage { get { return GlobalInfo.Get(ScriptContext.CurrentContext).MailLanguage ?? "uni"; } set { GlobalInfo.Get(ScriptContext.CurrentContext).MailLanguage = value; // TODO: check the value } }*/ /// <summary> /// Get language used by mail functions. /// </summary> /// <returns></returns> [ImplementsFunction("mb_language")] public static string GetMailLanguage() { return "uni";//MailLanguage; } /// <summary> /// Set the language used by mail functions. /// </summary> /// <param name="language"></param> /// <returns>True if language was set, otherwise false.</returns> [ImplementsFunction("mb_language")] public static bool SetMailLanguage(string language) { PhpException.FunctionNotSupported(); return false; //try //{ // MailLanguage = language; // return true; //} //catch //{ // return false; //} } #region mb_send_mail(), TODO: use mb_language [ImplementsFunction("mb_send_mail")] public static bool SendMail(string to, string subject, string message ) { return PHP.Library.Mailer.Mail(to, subject, message); } [ImplementsFunction("mb_send_mail")] public static bool SendMail(string to, string subject, string message, string additional_headers /*= NULL*/ ) { return PHP.Library.Mailer.Mail(to, subject, message, additional_headers); } [ImplementsFunction("mb_send_mail")] public static bool SendMail( string to, string subject, string message , string additional_headers /*= NULL*/, string additional_parameter /*= NULL*/ ) { return PHP.Library.Mailer.Mail(to, subject, message, additional_headers, additional_parameter); } #endregion #endregion #region mb_parse_str [ImplementsFunction("mb_parse_str")] public static bool ParseStr(string encoded_string, PhpReference array) { try { PhpArray result = new PhpArray(); foreach (var x in ParseUrlEncodedGetParameters(encoded_string)) result.Add(x.Key, x.Value); array.Value = result; return true; } catch { return false; } } [ImplementsFunction("mb_parse_str")] public static bool ParseStr(string encoded_string) { try { PhpArray result = ScriptContext.CurrentContext.GlobalVariables; foreach (var x in ParseUrlEncodedGetParameters(encoded_string)) result.Add(x.Key, x.Value); return true; } catch { return false; } } /// <summary> /// Decodes URL encoded string and parses GET parameters. /// </summary> /// <param name="getParams">URL encoded GET parameters string.</param> /// <returns>Enumerator of decoded and parsed GET parameters as pairs of (name, value).</returns> private static IEnumerable<KeyValuePair<string,string>> ParseUrlEncodedGetParameters(string getParams) { foreach (var str in System.Web.HttpUtility.UrlDecode(getParams).Split(new char[]{'&'})) { if (str.Length == 0) continue; int eqPos = str.IndexOf('='); if (eqPos > 0) { // name = value yield return new KeyValuePair<string, string>(str.Substring(0, eqPos), str.Substring(eqPos + 1)); } else if (eqPos == 0) { // ignore, no variable name } else { // just variable name yield return new KeyValuePair<string, string>(str, null); } } } #endregion } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geoprocessing; namespace GeoprocessorEventHelper { //declare the event argument classes for the different GP events public sealed class GPMessageEventArgs : EventArgs { private string m_message = string.Empty; private esriGPMessageType m_messageType = esriGPMessageType.esriGPMessageTypeEmpty; private int m_errorCode = -1; #region class constructors public GPMessageEventArgs() : base() { } public GPMessageEventArgs(string message, esriGPMessageType messageType, int errorCode) : this() { m_message = message; m_messageType = messageType; m_errorCode = errorCode; } #endregion #region properties public string Message { get { return m_message; } set { m_message = value; } } public esriGPMessageType MessageType { get { return m_messageType; } set { m_messageType = value; } } public int ErrorCode { get { return m_errorCode; } set { m_errorCode = value; } } #endregion } public sealed class GPPostToolExecuteEventArgs : EventArgs { #region class members private GPMessageEventArgs[] m_messages; private int m_result = 0; private string m_displayName = string.Empty; private string m_name = string.Empty; private string m_pathName = string.Empty; private string m_toolbox = string.Empty; private string m_toolCategory = string.Empty; private esriGPToolType m_toolType = esriGPToolType.esriGPCustomTool; private string m_description = string.Empty; #endregion #region calss constructor public GPPostToolExecuteEventArgs() : base() { } #endregion #region properties public GPMessageEventArgs[] Messages { get { return m_messages; } set { m_messages = value; } } public int Result { get { return m_result; } set { m_result = value; } } public string DisplayName { get { return m_displayName; } set { m_displayName = value; } } public string Name { get { return m_name; } set { m_name = value; } } public string Toolbox { get { return m_toolbox; } set { m_toolbox = value; } } public string ToolCategory { get { return m_toolCategory; } set { m_toolCategory = value; } } public esriGPToolType ToolType { get { return m_toolType; } set { m_toolType = value; } } public string Description { get { return m_description; } set { m_description = value; } } public string PathName { get { return m_pathName; } set { m_pathName = value; } } #endregion } public sealed class GPPreToolExecuteEventArgs : EventArgs { #region class members private int m_processID = 0; private string m_displayName = string.Empty; private string m_name = string.Empty; private string m_pathName = string.Empty; private string m_toolbox = string.Empty; private string m_toolCategory = string.Empty; private esriGPToolType m_toolType = esriGPToolType.esriGPCustomTool; private string m_description = string.Empty; #endregion #region calss constructor public GPPreToolExecuteEventArgs() : base() { } #endregion #region properties public int ProcessID { get { return m_processID; } set { m_processID = value; } } public string DisplayName { get { return m_displayName; } set { m_displayName = value; } } public string Name { get { return m_name; } set { m_name = value; } } public string Toolbox { get { return m_toolbox; } set { m_toolbox = value; } } public string ToolCategory { get { return m_toolCategory; } set { m_toolCategory = value; } } public esriGPToolType ToolType { get { return m_toolType; } set { m_toolType = value; } } public string Description { get { return m_description; } set { m_description = value; } } public string PathName { get { return m_pathName; } set { m_pathName = value; } } #endregion } // A delegate type for hooking up change notifications. public delegate void MessageEventHandler(object sender, GPMessageEventArgs e); public delegate void ToolboxChangedEventHandler(object sender, EventArgs e); public delegate void PostToolExecuteEventHandler(object sender, GPPostToolExecuteEventArgs e); public delegate void PreToolExecuteEventHandler(object sender, GPPreToolExecuteEventArgs e); [ Guid("0CC39861-B4FE-45ea-8919-8295AF25F311"), ProgId("GeoprocessorEventHelper.GPMessageEventHandler"), ComVisible(true), Serializable ] /// <summary> ///A class that sends event notifications whenever the Messages are added. /// </summary> public class GPMessageEventHandler : IGeoProcessorEvents { // An event that clients can use to be notified whenever a GP message is posted. public event MessageEventHandler GPMessage; //an event notifying that a toolbox has changed public event ToolboxChangedEventHandler GPToolboxChanged; //an event which gets fired right after a tool finish execute public event PostToolExecuteEventHandler GPPostToolExecute; //an event which gets fired before a tool gets executed public event PreToolExecuteEventHandler GPPreToolExecute; #region IGeoProcessorEvents Members /// <summary> /// Called when a message has been posted while executing a SchematicGeoProcessing /// </summary> /// <param name="message"></param> void IGeoProcessorEvents.OnMessageAdded(IGPMessage message) { //fire the GPMessage event if (GPMessage != null) GPMessage(this, new GPMessageEventArgs(message.Description, message.Type, message.ErrorCode)); } /// <summary> /// Called immediately after a tool is executed by the GeoProcessor. /// </summary> /// <param name="Tool"></param> /// <param name="Values"></param> /// <param name="result"></param> /// <param name="Messages"></param> void IGeoProcessorEvents.PostToolExecute(IGPTool Tool, IArray Values, int result, IGPMessages Messages) { GPMessageEventArgs[] messages = new GPMessageEventArgs[Messages.Count]; IGPMessage gpMessage = null; for (int i = 0; i < Messages.Count; i++) { gpMessage = Messages.GetMessage(i); GPMessageEventArgs message = new GPMessageEventArgs(gpMessage.Description, gpMessage.Type, gpMessage.ErrorCode); messages[i] = message; } //create a new instance of GPPostToolExecuteEventArgs GPPostToolExecuteEventArgs e = new GPPostToolExecuteEventArgs(); e.DisplayName = Tool.DisplayName; e.Name = Tool.Name; e.PathName = Tool.PathName; e.Toolbox = Tool.Toolbox.Alias; e.ToolCategory = Tool.ToolCategory; e.ToolType = Tool.ToolType; e.Description = Tool.Description; e.Result = result; //fire the Post tool event if (null != GPPostToolExecute) GPPostToolExecute(this, e); } /// <summary> /// Called immediately prior to the GeoProcessor executing a tool. /// </summary> /// <param name="Tool"></param> /// <param name="Values"></param> /// <param name="processID"></param> void IGeoProcessorEvents.PreToolExecute(IGPTool Tool, IArray Values, int processID) { //create a new instance of GPPreToolExecuteEventArgs GPPreToolExecuteEventArgs e = new GPPreToolExecuteEventArgs(); e.DisplayName = Tool.DisplayName; e.Name = Tool.Name; e.PathName = Tool.PathName; e.Toolbox = Tool.Toolbox.Alias; e.ToolCategory = Tool.ToolCategory; e.ToolType = Tool.ToolType; e.Description = Tool.Description; e.ProcessID = processID; //fire the PreTool event if (null != GPPreToolExecute) GPPreToolExecute(this, e); } /// <summary> /// Called when a toolbox is added or removed from the GeoProcessor. /// </summary> void IGeoProcessorEvents.ToolboxChange() { if (GPToolboxChanged != null) GPToolboxChanged(this, new EventArgs()); } #endregion } }
/* * Copyright 2011-2015 Numeric Technology * * 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; using System.Collections.Specialized; using System.Security.Permissions; using System.Web; using System.Collections.Generic; using System.Web.UI; namespace KPComponents.Generic { /// <summary> /// <para>Authors: Juliano Tiago Rinaldi and /// Tiago Antonio Jacobi</para> /// </summary> public abstract class StateManagedCollection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IStateManager, IList, ICollection where T : class, IStateManagedItem, new() { #region Fields private List<T> items = new List<T>(); private bool saveAll; private bool tracking; #endregion #region Methods #endregion #region IList<T> Members public int IndexOf(T item) { return items.IndexOf(item); } public void Insert(int index, T item) { items.Insert(index, item); if (this.tracking) { this.saveAll = true; } } public void RemoveAt(int index) { items.RemoveAt(index); if (this.tracking) { this.saveAll = true; } } public T this[int index] { get { return items[index]; } set { items[index] = value; } } #endregion #region ICollection<T> Members public void Add(T item) { items.Add(item); } public void Clear() { items.Clear(); if (this.tracking) { this.saveAll = true; } } public bool Contains(T item) { return items.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { items.CopyTo(array, arrayIndex); } public int Count { get { return items.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { return items.Remove(item); } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return items.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)items).GetEnumerator(); } #endregion #region IStateManager Members public bool IsTrackingViewState { get { return tracking; } } public bool IsSaveAll { get { return this.saveAll; } } public void LoadViewState(object state) { if (state != null) { Pair p = state as Pair; if (p != null) { int count = (int)p.First; object[] savedItems = (object[])p.Second; foreach (object savedState in savedItems) { T item = new T(); item.TrackViewState(); item.LoadViewState(savedState); items.Add(item); } } } } public object SaveViewState() { object[] saveList = new object[items.Count]; for (int i = 0; i < items.Count; i++) { T item = items[i]; SetItemDirty(item); saveList[i] = item.SaveViewState(); } return new Pair(items.Count, saveList); } public void TrackViewState() { this.tracking = true; foreach (IStateManager item in this.items) { item.TrackViewState(); } } public void SetDirty() { foreach (T item in items) { SetItemDirty(item); } } protected virtual void SetItemDirty(T item) { item.SetDirty(); } #endregion #region IList Members int IList.Add(object value) { Add(value as T); return Count - 1; } void IList.Clear() { Clear(); } bool IList.Contains(object value) { return Contains(value as T); } int IList.IndexOf(object value) { return IndexOf(value as T); } void IList.Insert(int index, object value) { Insert(index, value as T); } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return IsReadOnly; } } void IList.Remove(object value) { Remove(value as T); } void IList.RemoveAt(int index) { RemoveAt(index); } object IList.this[int index] { get { return this[index]; } set { this[index] = value as T; } } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { } int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return null; } } #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.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Validation; namespace System.Collections.Immutable { /// <content> /// Contains the inner Builder class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableSortedSet<T> { /// <summary> /// A sorted set that mutates with little or no memory allocations, /// can produce and/or build on immutable sorted set instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableSortedSet&lt;T&gt;.Union"/> and other bulk change methods /// already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableSortedSetBuilderDebuggerProxy<>))] public sealed class Builder : ISortKeyCollection<T>, IReadOnlyCollection<T>, ISet<T>, ICollection { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private ImmutableSortedSet<T>.Node root = ImmutableSortedSet<T>.Node.EmptyNode; /// <summary> /// The comparer to use for sorting the set. /// </summary> private IComparer<T> comparer = Comparer<T>.Default; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableSortedSet<T> immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int version; /// <summary> /// The object callers may use to synchronize access to this collection. /// </summary> private object syncRoot; /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> /// <param name="set">A set to act as the basis for a new set.</param> internal Builder(ImmutableSortedSet<T> set) { Requires.NotNull(set, "set"); this.root = set.root; this.comparer = set.KeyComparer; this.immutable = set; } #region ISet<T> Properties /// <summary> /// Gets the number of elements in this set. /// </summary> public int Count { get { return this.Root.Count; } } /// <summary> /// Gets a value indicating whether this instance is read-only. /// </summary> /// <value>Always <c>false</c>.</value> bool ICollection<T>.IsReadOnly { get { return false; } } #endregion /// <summary> /// Gets the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>The element at the given position.</returns> /// <remarks> /// No index setter is offered because the element being replaced may not sort /// to the same position in the sorted collection as the replacing element. /// </remarks> public T this[int index] { get { return this.root[index]; } } /// <summary> /// Gets the maximum value in the collection, as defined by the comparer. /// </summary> /// <value>The maximum value in the set.</value> public T Max { get { return this.root.Max; } } /// <summary> /// Gets the minimum value in the collection, as defined by the comparer. /// </summary> /// <value>The minimum value in the set.</value> public T Min { get { return this.root.Min; } } /// <summary> /// Gets or sets the System.Collections.Generic.IComparer&lt;T&gt; object that is used to determine equality for the values in the System.Collections.Generic.SortedSet&lt;T&gt;. /// </summary> /// <value>The comparer that is used to determine equality for the values in the set.</value> /// <remarks> /// When changing the comparer in such a way as would introduce collisions, the conflicting elements are dropped, /// leaving only one of each matching pair in the collection. /// </remarks> public IComparer<T> KeyComparer { get { return this.comparer; } set { Requires.NotNull(value, "value"); if (value != this.comparer) { var newRoot = Node.EmptyNode; foreach (T item in this) { bool mutated; newRoot = newRoot.Add(item, value, out mutated); } this.immutable = null; this.comparer = value; this.Root = newRoot; } } } /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return this.version; } } /// <summary> /// Gets or sets the root node that represents the data in this collection. /// </summary> private Node Root { get { return this.root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. this.version++; if (this.root != value) { this.root = value; // Clear any cached value for the immutable view since it is now invalidated. this.immutable = null; } } } #region ISet<T> Methods /// <summary> /// Adds an element to the current set and returns a value to indicate if the /// element was successfully added. /// </summary> /// <param name="item">The element to add to the set.</param> /// <returns>true if the element is added to the set; false if the element is already in the set.</returns> public bool Add(T item) { bool mutated; this.Root = this.Root.Add(item, this.comparer, out mutated); return mutated; } /// <summary> /// Removes all elements in the specified collection from the current set. /// </summary> /// <param name="other">The collection of items to remove from the set.</param> public void ExceptWith(IEnumerable<T> other) { Requires.NotNull(other, "other"); foreach (T item in other) { bool mutated; this.Root = this.Root.Remove(item, this.comparer, out mutated); } } /// <summary> /// Modifies the current set so that it contains only elements that are also in a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void IntersectWith(IEnumerable<T> other) { Requires.NotNull(other, "other"); var result = ImmutableSortedSet<T>.Node.EmptyNode; foreach (T item in other) { if (this.Contains(item)) { bool mutated; result = result.Add(item, this.comparer, out mutated); } } this.Root = result; } /// <summary> /// Determines whether the current set is a proper (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of other; otherwise, false.</returns> public bool IsProperSubsetOf(IEnumerable<T> other) { return this.ToImmutable().IsProperSubsetOf(other); } /// <summary> /// Determines whether the current set is a proper (strict) superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsProperSupersetOf(IEnumerable<T> other) { return this.ToImmutable().IsProperSupersetOf(other); } /// <summary> /// Determines whether the current set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of other; otherwise, false.</returns> public bool IsSubsetOf(IEnumerable<T> other) { return this.ToImmutable().IsSubsetOf(other); } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsSupersetOf(IEnumerable<T> other) { return this.ToImmutable().IsSupersetOf(other); } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and other share at least one common element; otherwise, false.</returns> public bool Overlaps(IEnumerable<T> other) { return this.ToImmutable().Overlaps(other); } /// <summary> /// Determines whether the current set and the specified collection contain the same elements. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is equal to other; otherwise, false.</returns> public bool SetEquals(IEnumerable<T> other) { return this.ToImmutable().SetEquals(other); } /// <summary> /// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void SymmetricExceptWith(IEnumerable<T> other) { this.Root = this.ToImmutable().SymmetricExcept(other).root; } /// <summary> /// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void UnionWith(IEnumerable<T> other) { Requires.NotNull(other, "other"); foreach (T item in other) { bool mutated; this.Root = this.Root.Add(item, this.comparer, out mutated); } } /// <summary> /// Adds an element to the current set and returns a value to indicate if the /// element was successfully added. /// </summary> /// <param name="item">The element to add to the set.</param> void ICollection<T>.Add(T item) { this.Add(item); } /// <summary> /// Removes all elements from this set. /// </summary> public void Clear() { this.Root = ImmutableSortedSet<T>.Node.EmptyNode; } /// <summary> /// Determines whether the set contains a specific value. /// </summary> /// <param name="item">The object to locate in the set.</param> /// <returns>true if item is found in the set; false otherwise.</returns> public bool Contains(T item) { return this.Root.Contains(item, this.comparer); } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { this.root.CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the set. /// </summary> /// <param name="item">The object to remove from the set.</param> /// <returns><c>true</c> if the item was removed from the set; <c>false</c> if the item was not found in the set.</returns> public bool Remove(T item) { bool mutated; this.Root = this.Root.Remove(item, this.comparer, out mutated); return mutated; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A enumerator that can be used to iterate through the collection.</returns> public ImmutableSortedSet<T>.Enumerator GetEnumerator() { return this.Root.GetEnumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A enumerator that can be used to iterate through the collection.</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.Root.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A enumerator that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Returns an System.Collections.Generic.IEnumerable&lt;T&gt; that iterates over this /// collection in reverse order. /// </summary> /// <returns> /// An enumerator that iterates over the System.Collections.Generic.SortedSet&lt;T&gt; /// in reverse order. /// </returns> [Pure] public IEnumerable<T> Reverse() { return new ReverseEnumerable(this.root); } /// <summary> /// Creates an immutable sorted set based on the contents of this instance. /// </summary> /// <returns>An immutable set.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableSortedSet<T> ToImmutable() { // Creating an instance of ImmutableSortedSet<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (this.immutable == null) { this.immutable = ImmutableSortedSet<T>.Wrap(this.Root, this.comparer); } return this.immutable; } #region ICollection members /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> /// <exception cref="System.NotImplementedException"></exception> void ICollection.CopyTo(Array array, int arrayIndex) { this.Root.CopyTo(array, arrayIndex); } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe); otherwise, false.</returns> /// <exception cref="System.NotImplementedException"></exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />.</returns> /// <exception cref="System.NotImplementedException"></exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { if (this.syncRoot == null) { Threading.Interlocked.CompareExchange<Object>(ref this.syncRoot, new Object(), null); } return this.syncRoot; } } #endregion } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> [ExcludeFromCodeCoverage] internal class ImmutableSortedSetBuilderDebuggerProxy<T> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableSortedSet<T>.Builder set; /// <summary> /// The simple view of the collection. /// </summary> private T[] contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSetBuilderDebuggerProxy&lt;T&gt;"/> class. /// </summary> /// <param name="builder">The collection to display in the debugger</param> public ImmutableSortedSetBuilderDebuggerProxy(ImmutableSortedSet<T>.Builder builder) { Requires.NotNull(builder, "builder"); this.set = builder; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Contents { get { if (this.contents == null) { this.contents = this.set.ToArray(this.set.Count); } return this.contents; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Internal.TypeSystem; namespace Internal.JitInterface { internal unsafe partial class CorInfoImpl { private struct IntrinsicKey { public string MethodName; public string TypeNamespace; public string TypeName; public bool Equals(IntrinsicKey other) { return (MethodName == other.MethodName) && (TypeNamespace == other.TypeNamespace) && (TypeName == other.TypeName); } public override int GetHashCode() { return MethodName.GetHashCode() + ((TypeNamespace != null) ? TypeNamespace.GetHashCode() : 0) + ((TypeName != null) ? TypeName.GetHashCode() : 0); } } private class IntrinsicEntry { public IntrinsicKey Key; public CorInfoIntrinsics Id; } private class IntrinsicHashtable : LockFreeReaderHashtable<IntrinsicKey, IntrinsicEntry> { protected override bool CompareKeyToValue(IntrinsicKey key, IntrinsicEntry value) { return key.Equals(value.Key); } protected override bool CompareValueToValue(IntrinsicEntry value1, IntrinsicEntry value2) { return value1.Key.Equals(value2.Key); } protected override IntrinsicEntry CreateValueFromKey(IntrinsicKey key) { Debug.Fail("CreateValueFromKey not supported"); return null; } protected override int GetKeyHashCode(IntrinsicKey key) { return key.GetHashCode(); } protected override int GetValueHashCode(IntrinsicEntry value) { return value.Key.GetHashCode(); } public void Add(CorInfoIntrinsics id, string methodName, string typeNamespace, string typeName) { var entry = new IntrinsicEntry(); entry.Id = id; entry.Key.MethodName = methodName; entry.Key.TypeNamespace = typeNamespace; entry.Key.TypeName = typeName; AddOrGetExisting(entry); } } static IntrinsicHashtable InitializeIntrinsicHashtable() { IntrinsicHashtable table = new IntrinsicHashtable(); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sin, "Sin", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sin, "Sin", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cos, "Cos", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cos, "Cos", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cbrt, "Cbrt", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cbrt, "Cbrt", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sqrt, "Sqrt", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sqrt, "Sqrt", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Abs, "Abs", "System", "Math"); // No System.MathF entry for CORINFO_INTRTINSIC_Abs as System.Math exposes and handles both float and double table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Round, "Round", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Round, "Round", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cosh, "Cosh", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Cosh, "Cosh", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sinh, "Sinh", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Sinh, "Sinh", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tan, "Tan", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tan, "Tan", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tanh, "Tanh", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Tanh, "Tanh", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Asin, "Asin", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Asin, "Asin", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Asinh, "Asinh", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Asinh, "Asinh", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Acos, "Acos", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Acos, "Acos", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Acosh, "Acosh", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Acosh, "Acosh", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan, "Atan", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan, "Atan", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan2, "Atan2", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atan2, "Atan2", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atanh, "Atanh", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Atanh, "Atanh", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Log10, "Log10", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Log10, "Log10", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Pow, "Pow", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Pow, "Pow", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Exp, "Exp", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Exp, "Exp", "System", "MathF"); #if !READYTORUN // These are normally handled via the SSE4.1 instructions ROUNDSS/ROUNDSD. // However, we don't know the ISAs the target machine supports so we should // fallback to the method call implementation instead. table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Ceiling, "Ceiling", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Ceiling, "Ceiling", "System", "MathF"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Floor, "Floor", "System", "Math"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Floor, "Floor", "System", "MathF"); #endif // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetChar, null, null, null); // unused // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_GetDimLength, "GetLength", "System", "Array"); // not handled table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Get, "Get", null, null); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Address, "Address", null, null); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Set, "Set", null, null); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StringGetChar, "get_Chars", "System", "String"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StringLength, "get_Length", "System", "String"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InitializeArray, "InitializeArray", "System.Runtime.CompilerServices", "RuntimeHelpers"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetTypeFromHandle, "GetTypeFromHandle", "System", "Type"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_RTH_GetValueInternal, "GetValueInternal", "System", "RuntimeTypeHandle"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeEQ, "op_Equality", "System", "Type"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_TypeNEQ, "op_Inequality", "System", "Type"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Object_GetType, "GetType", "System", "Object"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContext, "GetStubContext", "System.StubHelpers", "StubHelpers"); // interop-specific // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetStubContextAddr, "GetStubContextAddr", "System.StubHelpers", "StubHelpers"); // interop-specific // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_StubHelpers_GetNDirectTarget, "GetNDirectTarget", "System.StubHelpers", "StubHelpers"); // interop-specific // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedAdd32, "Add", System.Threading", "Interlocked"); // unused // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedAdd64, "Add", System.Threading", "Interlocked"); // unused table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32, "ExchangeAdd", "System.Threading", "Interlocked"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd64, "ExchangeAdd", "System.Threading", "Interlocked"); // ambiguous match table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32, "Exchange", "System.Threading", "Interlocked"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg64, "Exchange", "System.Threading", "Interlocked"); // ambiguous match table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32, "CompareExchange", "System.Threading", "Interlocked"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg64, "CompareExchange", "System.Threading", "Interlocked"); // ambiguous match table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_MemoryBarrier, "MemoryBarrier", "System.Threading", "Interlocked"); // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetCurrentManagedThread, "GetCurrentThreadNative", "System", "Thread"); // not in .NET Core // table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetManagedThreadId, "get_ManagedThreadId", "System", "Thread"); // not in .NET Core table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_ByReference_Ctor, ".ctor", "System", "ByReference`1"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_ByReference_Value, "get_Value", "System", "ByReference`1"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_Span_GetItem, "get_Item", "System", "Span`1"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_ReadOnlySpan_GetItem, "get_Item", "System", "ReadOnlySpan`1"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetRawHandle, "EETypePtrOf", "System", "EETypePtr"); table.Add(CorInfoIntrinsics.CORINFO_INTRINSIC_GetRawHandle, "DefaultConstructorOf", "System", "Activator"); // If this assert fails, make sure to add the new intrinsics to the table above and update the expected count below. Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_Count == 54); return table; } static IntrinsicHashtable s_IntrinsicHashtable = InitializeIntrinsicHashtable(); private CorInfoIntrinsics getIntrinsicID(CORINFO_METHOD_STRUCT_* ftn, byte* pMustExpand) { var method = HandleToObject(ftn); return getIntrinsicID(method, pMustExpand); } private CorInfoIntrinsics getIntrinsicID(MethodDesc method, byte* pMustExpand) { if (pMustExpand != null) *pMustExpand = 0; Debug.Assert(method.IsIntrinsic); IntrinsicKey key = new IntrinsicKey(); key.MethodName = method.Name; var metadataType = method.OwningType as MetadataType; if (metadataType != null) { key.TypeNamespace = metadataType.Namespace; key.TypeName = metadataType.Name; } IntrinsicEntry entry; if (!s_IntrinsicHashtable.TryGetValue(key, out entry)) return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal; // Some intrinsics need further disambiguation CorInfoIntrinsics id = entry.Id; switch (id) { case CorInfoIntrinsics.CORINFO_INTRINSIC_Abs: { // RyuJIT handles floating point overloads only var returnTypeCategory = method.Signature.ReturnType.Category; if (returnTypeCategory != TypeFlags.Double && returnTypeCategory != TypeFlags.Single) return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal; } break; case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Get: case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Address: case CorInfoIntrinsics.CORINFO_INTRINSIC_Array_Set: if (!method.OwningType.IsArray) return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal; break; case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32: case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32: case CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32: { // RyuJIT handles int32 and int64 overloads only var returnTypeCategory = method.Signature.ReturnType.Category; if (returnTypeCategory != TypeFlags.Int32 && returnTypeCategory != TypeFlags.Int64 && returnTypeCategory != TypeFlags.IntPtr) return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal; // int64 overloads have different ids if (returnTypeCategory == TypeFlags.Int64) { Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXAdd64); Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedXchg64); Debug.Assert((int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg32 + 1 == (int)CorInfoIntrinsics.CORINFO_INTRINSIC_InterlockedCmpXchg64); id = (CorInfoIntrinsics)((int)id + 1); } } break; case CorInfoIntrinsics.CORINFO_INTRINSIC_RTH_GetValueInternal: #if !READYTORUN case CorInfoIntrinsics.CORINFO_INTRINSIC_InitializeArray: #endif case CorInfoIntrinsics.CORINFO_INTRINSIC_ByReference_Ctor: case CorInfoIntrinsics.CORINFO_INTRINSIC_ByReference_Value: if (pMustExpand != null) *pMustExpand = 1; break; case CorInfoIntrinsics.CORINFO_INTRINSIC_GetRawHandle: if (pMustExpand != null) *pMustExpand = 1; break; case CorInfoIntrinsics.CORINFO_INTRINSIC_Span_GetItem: case CorInfoIntrinsics.CORINFO_INTRINSIC_ReadOnlySpan_GetItem: { // RyuJIT handles integer overload only var argumentTypeCategory = method.Signature[0].Category; if (argumentTypeCategory != TypeFlags.Int32) return CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal; } break; default: break; } return id; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.ServiceBus.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.ServiceBus.Fluent.Models; using Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition; using Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update; using System.Collections.Generic; using System; internal partial class TopicImpl { /// <summary> /// Gets the manager client of this resource type. /// </summary> Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusManager Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasManager<Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusManager>.Manager { get { return this.Manager; } } /// <summary> /// Gets the resource ID string. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId.Id { get { return this.Id; } } /// <summary> /// Gets the name of the resource. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name { get { return this.Name; } } /// <summary> /// The idle interval after which the topic is automatically deleted. /// Note: unless it is explicitly overridden the default delete on idle duration /// is infinite (TimeSpan.Max). /// </summary> /// <param name="durationInMinutes">Idle duration in minutes.</param> /// <return>The next stage of topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithDeleteOnIdle.WithDeleteOnIdleDurationInMinutes(int durationInMinutes) { return this.WithDeleteOnIdleDurationInMinutes(durationInMinutes); } /// <summary> /// The idle interval after which the topic is automatically deleted. /// </summary> /// <param name="durationInMinutes">Idle duration in minutes.</param> /// <return>The next stage of topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithDeleteOnIdle.WithDeleteOnIdleDurationInMinutes(int durationInMinutes) { return this.WithDeleteOnIdleDurationInMinutes(durationInMinutes); } /// <summary> /// Specifies that the default batching should be disabled on this topic. /// With batching Service Bus can batch multiple message when it write or delete messages /// from it's internal store. /// </summary> /// <return>The next stage of topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithMessageBatching.WithoutMessageBatching() { return this.WithoutMessageBatching(); } /// <summary> /// Specifies that batching of messages should be disabled when Service Bus write messages to /// or delete messages from it's internal store. /// </summary> /// <return>The next stage of topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithMessageBatching.WithoutMessageBatching() { return this.WithoutMessageBatching(); } /// <summary> /// Specifies that service bus can batch multiple message when it write messages to or delete /// messages from it's internal store. This increases the throughput. /// </summary> /// <return>The next stage of topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithMessageBatching.WithMessageBatching() { return this.WithMessageBatching(); } /// <summary> /// Specifies the duration of the duplicate message detection history. /// </summary> /// <param name="duplicateDetectionHistoryDuration">Duration of the history.</param> /// <return>The next stage of topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithDuplicateMessageDetection.WithDuplicateMessageDetection(TimeSpan duplicateDetectionHistoryDuration) { return this.WithDuplicateMessageDetection(duplicateDetectionHistoryDuration); } /// <summary> /// Specifies that duplicate message detection needs to be disabled. /// </summary> /// <return>The next stage of topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithDuplicateMessageDetection.WithoutDuplicateMessageDetection() { return this.WithoutDuplicateMessageDetection(); } /// <summary> /// Specifies the duration of the duplicate message detection history. /// </summary> /// <param name="duration">Duration of the history.</param> /// <return>The next stage of topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithDuplicateMessageDetection.WithDuplicateMessageDetectionHistoryDuration(TimeSpan duration) { return this.WithDuplicateMessageDetectionHistoryDuration(duration); } /// <summary> /// Specifies that partitioning should be enabled on this topic. /// </summary> /// <return>The next stage of topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithPartitioning.WithPartitioning() { return this.WithPartitioning(); } /// <summary> /// Specifies that the default partitioning should be disabled on this topic. /// Note: if the parent Service Bus is Premium SKU then partition cannot be /// disabled. /// </summary> /// <return>The next stage of topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithPartitioning.WithoutPartitioning() { return this.WithoutPartitioning(); } /// <summary> /// Creates a send authorization rule for the topic. /// </summary> /// <param name="name">Rule name.</param> /// <return>Next stage of the topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithAuthorizationRule.WithNewSendRule(string name) { return this.WithNewSendRule(name); } /// <summary> /// Creates a manage authorization rule for the topic. /// </summary> /// <param name="name">Rule name.</param> /// <return>Next stage of the topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithAuthorizationRule.WithNewManageRule(string name) { return this.WithNewManageRule(name); } /// <summary> /// Creates a listen authorization rule for the topic. /// </summary> /// <param name="name">Rule name.</param> /// <return>Next stage of the topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithAuthorizationRule.WithNewListenRule(string name) { return this.WithNewListenRule(name); } /// <summary> /// Creates a send authorization rule for the topic. /// </summary> /// <param name="name">Rule name.</param> /// <return>Next stage of the topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithAuthorizationRule.WithNewSendRule(string name) { return this.WithNewSendRule(name); } /// <summary> /// Creates a manage authorization rule for the topic. /// </summary> /// <param name="name">Rule name.</param> /// <return>Next stage of the topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithAuthorizationRule.WithNewManageRule(string name) { return this.WithNewManageRule(name); } /// <summary> /// Creates a listen authorization rule for the topic. /// </summary> /// <param name="name">Rule name.</param> /// <return>Next stage of the topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithAuthorizationRule.WithNewListenRule(string name) { return this.WithNewListenRule(name); } /// <summary> /// Removes an authorization rule for the topic. /// </summary> /// <param name="name">Rule name.</param> /// <return>Next stage of the topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithAuthorizationRule.WithoutAuthorizationRule(string name) { return this.WithoutAuthorizationRule(name); } /// <summary> /// Creates a subscription entity for the Service Bus topic. /// </summary> /// <param name="name">Queue name.</param> /// <return>The next stage of topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithSubscription.WithNewSubscription(string name) { return this.WithNewSubscription(name); } /// <summary> /// Creates a subscription entity for the Service Bus topic. /// </summary> /// <param name="name">Queue name.</param> /// <return>Next stage of the Service Bus topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithSubscription.WithNewSubscription(string name) { return this.WithNewSubscription(name); } /// <summary> /// Removes a subscription entity associated with the Service Bus topic. /// </summary> /// <param name="name">Subscription name.</param> /// <return>Next stage of the Service Bus topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithSubscription.WithoutSubscription(string name) { return this.WithoutSubscription(name); } /// <summary> /// Specifies the duration after which the message expires. /// Note: unless it is explicitly overridden the default ttl is infinite (TimeSpan.Max). /// </summary> /// <param name="ttl">Time to live duration.</param> /// <return>The next stage of topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithDefaultMessageTTL.WithDefaultMessageTTL(TimeSpan ttl) { return this.WithDefaultMessageTTL(ttl); } /// <summary> /// Specifies the duration after which the message expires. /// </summary> /// <param name="ttl">Time to live duration.</param> /// <return>The next stage of topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithDefaultMessageTTL.WithDefaultMessageTTL(TimeSpan ttl) { return this.WithDefaultMessageTTL(ttl); } /// <summary> /// Gets number of subscriptions for the topic. /// </summary> int Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.SubscriptionCount { get { return this.SubscriptionCount(); } } /// <summary> /// Gets number of messages transferred to another topic, topic, or subscription. /// </summary> long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.TransferMessageCount { get { return this.TransferMessageCount(); } } /// <summary> /// Gets the maximum size of memory allocated for the topic in megabytes. /// </summary> long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.MaxSizeInMB { get { return this.MaxSizeInMB(); } } /// <summary> /// Gets the exact time the topic was created. /// </summary> System.DateTime Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.CreatedAt { get { return this.CreatedAt(); } } /// <summary> /// Gets number of messages sent to the topic that are yet to be released /// for consumption. /// </summary> long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.ScheduledMessageCount { get { return this.ScheduledMessageCount(); } } /// <summary> /// Gets indicates whether express entities are enabled. /// </summary> bool Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.IsExpressEnabled { get { return this.IsExpressEnabled(); } } /// <summary> /// Gets current size of the topic, in bytes. /// </summary> long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.CurrentSizeInBytes { get { return this.CurrentSizeInBytes(); } } /// <summary> /// Gets number of active messages in the topic. /// </summary> long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.ActiveMessageCount { get { return this.ActiveMessageCount(); } } /// <summary> /// Gets entry point to manage subscriptions associated with the topic. /// </summary> Microsoft.Azure.Management.ServiceBus.Fluent.ISubscriptions Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.Subscriptions { get { return this.Subscriptions(); } } /// <summary> /// Gets the current status of the topic. /// </summary> Microsoft.Azure.Management.ServiceBus.Fluent.Models.EntityStatus Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.Status { get { return this.Status(); } } /// <summary> /// Gets the duration after which the message expires, starting from when the message is sent to topic. /// </summary> System.TimeSpan Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.DefaultMessageTtlDuration { get { return this.DefaultMessageTtlDuration(); } } /// <summary> /// Gets entry point to manage authorization rules for the Service Bus topic. /// </summary> Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRules Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.AuthorizationRules { get { return this.AuthorizationRules(); } } /// <summary> /// Gets last time a message was sent, or the last time there was a receive request to this topic. /// </summary> System.DateTime Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.AccessedAt { get { return this.AccessedAt(); } } /// <summary> /// Gets indicates whether the topic is to be partitioned across multiple message brokers. /// </summary> bool Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.IsPartitioningEnabled { get { return this.IsPartitioningEnabled(); } } /// <summary> /// Gets number of messages transferred into dead letters. /// </summary> long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.TransferDeadLetterMessageCount { get { return this.TransferDeadLetterMessageCount(); } } /// <summary> /// Gets the idle duration after which the topic is automatically deleted. /// </summary> long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.DeleteOnIdleDurationInMinutes { get { return this.DeleteOnIdleDurationInMinutes(); } } /// <summary> /// Gets indicates whether server-side batched operations are enabled. /// </summary> bool Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.IsBatchedOperationsEnabled { get { return this.IsBatchedOperationsEnabled(); } } /// <summary> /// Gets indicates if this topic requires duplicate detection. /// </summary> bool Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.IsDuplicateDetectionEnabled { get { return this.IsDuplicateDetectionEnabled(); } } /// <summary> /// Gets number of messages in the dead-letter topic. /// </summary> long Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.DeadLetterMessageCount { get { return this.DeadLetterMessageCount(); } } /// <summary> /// Gets the exact time the topic was updated. /// </summary> System.DateTime Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.UpdatedAt { get { return this.UpdatedAt(); } } /// <summary> /// Gets the duration of the duplicate detection history. /// </summary> System.TimeSpan Microsoft.Azure.Management.ServiceBus.Fluent.ITopic.DuplicateMessageDetectionHistoryDuration { get { return this.DuplicateMessageDetectionHistoryDuration(); } } /// <summary> /// Gets the name of the region the resource is in. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.RegionName { get { return this.RegionName; } } /// <summary> /// Gets the type of the resource. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Type { get { return this.Type; } } /// <summary> /// Gets the region the resource is in. /// </summary> Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Region { get { return this.Region; } } /// <summary> /// Gets the tags for the resource. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string, string> Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Tags { get { return this.Tags; } } /// <summary> /// Specifies the maximum size of memory allocated for the topic. /// </summary> /// <param name="sizeInMB">Size in MB.</param> /// <return>The next stage of topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithSize.WithSizeInMB(long sizeInMB) { return this.WithSizeInMB(sizeInMB); } /// <summary> /// Specifies the maximum size of memory allocated for the topic. /// </summary> /// <param name="sizeInMB">Size in MB.</param> /// <return>The next stage of topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithSize.WithSizeInMB(long sizeInMB) { return this.WithSizeInMB(sizeInMB); } /// <summary> /// Specifies that messages in this topic are express hence they can be cached in memory /// for some time before storing it in messaging store. /// Note: By default topic is not express. /// </summary> /// <return>The next stage of topic definition.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Definition.IWithExpressMessage.WithExpressMessage() { return this.WithExpressMessage(); } /// <summary> /// Specifies that messages in this topic are not express hence they should be cached in memory. /// </summary> /// <return>The next stage of topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithExpressMessage.WithoutExpressMessage() { return this.WithoutExpressMessage(); } /// <summary> /// Specifies that messages in this topic are express hence they can be cached in memory /// for some time before storing it in messaging store. /// </summary> /// <return>The next stage of topic update.</return> Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.Topic.Update.IWithExpressMessage.WithExpressMessage() { return this.WithExpressMessage(); } /// <summary> /// Gets the name of the resource group. /// </summary> string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasResourceGroup.ResourceGroupName { get { return this.ResourceGroupName; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace CppSharp { public enum NewLineKind { Never, Always, BeforeNextBlock, IfNotEmpty } public enum BlockKind { Unknown, BlockComment, InlineComment, Header, Footer, Usings, Namespace, Enum, EnumItem, Typedef, Class, InternalsClass, InternalsClassMethod, InternalsClassField, Functions, Function, Method, Event, Variable, Property, Field, VTableDelegate, Region, Interface, Finalizer, Includes, IncludesForwardReferences, ForwardReferences, MethodBody, FunctionsClass, Template, Destructor, AccessSpecifier, Fields, } [DebuggerDisplay("{BlockKind} | {Object}")] public class Block : ITextGenerator { public TextGenerator Text { get; set; } public BlockKind Kind { get; set; } public NewLineKind NewLineKind { get; set; } public object Object { get; set; } public Block Parent { get; set; } public List<Block> Blocks { get; set; } private bool hasIndentChanged; private bool isSubBlock; public Func<bool> CheckGenerate; public Block() : this(BlockKind.Unknown) { } public Block(BlockKind kind) { Kind = kind; Blocks = new List<Block>(); Text = new TextGenerator(); hasIndentChanged = false; isSubBlock = false; } public void AddBlock(Block block) { if (Text.StringBuilder.Length != 0 || hasIndentChanged) { hasIndentChanged = false; var newBlock = new Block { Text = Text.Clone(), isSubBlock = true }; Text.StringBuilder.Clear(); AddBlock(newBlock); } block.Parent = this; Blocks.Add(block); } public IEnumerable<Block> FindBlocks(BlockKind kind) { foreach (var block in Blocks) { if (block.Kind == kind) yield return block; foreach (var childBlock in block.FindBlocks(kind)) yield return childBlock; } } public virtual string Generate() { if (CheckGenerate != null && !CheckGenerate()) return ""; if (Blocks.Count == 0) return Text.ToString(); var builder = new StringBuilder(); uint totalIndent = 0; Block previousBlock = null; var blockIndex = 0; foreach (var childBlock in Blocks) { var childText = childBlock.Generate(); var nextBlock = (++blockIndex < Blocks.Count) ? Blocks[blockIndex] : null; var skipBlock = false; if (nextBlock != null) { var nextText = nextBlock.Generate(); if (string.IsNullOrEmpty(nextText) && childBlock.NewLineKind == NewLineKind.IfNotEmpty) skipBlock = true; } if (skipBlock) continue; if (string.IsNullOrEmpty(childText)) continue; var lines = childText.SplitAndKeep(Environment.NewLine).ToList(); if (previousBlock != null && previousBlock.NewLineKind == NewLineKind.BeforeNextBlock) builder.AppendLine(); if (childBlock.isSubBlock) totalIndent = 0; foreach (var line in lines) { if (string.IsNullOrEmpty(line)) continue; if (!string.IsNullOrWhiteSpace(line)) builder.Append(new string(' ', (int)totalIndent)); builder.Append(line); if (!line.EndsWith(Environment.NewLine, StringComparison.Ordinal)) builder.AppendLine(); } if (childBlock.NewLineKind == NewLineKind.Always) builder.AppendLine(); totalIndent += childBlock.Text.Indent; previousBlock = childBlock; } if (Text.StringBuilder.Length != 0) builder.Append(Text.StringBuilder); return builder.ToString(); } public bool IsEmpty { get { if (Blocks.Any(block => !block.IsEmpty)) return false; return string.IsNullOrEmpty(Text.ToString()); } } #region ITextGenerator implementation public uint Indent { get { return Text.Indent; } } public void Write(string msg, params object[] args) { Text.Write(msg, args); } public void WriteLine(string msg, params object[] args) { Text.WriteLine(msg, args); } public void WriteLineIndent(string msg, params object[] args) { Text.WriteLineIndent(msg, args); } public void NewLine() { Text.NewLine(); } public void NewLineIfNeeded() { Text.NewLineIfNeeded(); } public void NeedNewLine() { Text.NeedNewLine(); } public void ResetNewLine() { Text.ResetNewLine(); } public void PushIndent(uint indent = 4u) { hasIndentChanged = true; Text.PushIndent(indent); } public void PopIndent() { hasIndentChanged = true; Text.PopIndent(); } public void WriteStartBraceIndent() { Text.WriteStartBraceIndent(); } public void WriteCloseBraceIndent() { Text.WriteCloseBraceIndent(); } #endregion } public abstract class BlockGenerator : ITextGenerator { public Block RootBlock { get; private set; } public Block ActiveBlock { get; private set; } protected BlockGenerator() { RootBlock = new Block(); ActiveBlock = RootBlock; } public virtual string Generate() { return RootBlock.Generate(); } #region Block helpers public void AddBlock(Block block) { ActiveBlock.AddBlock(block); } public void PushBlock(BlockKind kind = BlockKind.Unknown, object obj = null) { var block = new Block { Kind = kind, Object = obj }; PushBlock(block); } public void PushBlock(Block block) { block.Parent = ActiveBlock; ActiveBlock.AddBlock(block); ActiveBlock = block; } public Block PopBlock(NewLineKind newLineKind = NewLineKind.Never) { var block = ActiveBlock; ActiveBlock.NewLineKind = newLineKind; ActiveBlock = ActiveBlock.Parent; return block; } public IEnumerable<Block> FindBlocks(BlockKind kind) { return RootBlock.FindBlocks(kind); } public Block FindBlock(BlockKind kind) { return FindBlocks(kind).SingleOrDefault(); } #endregion #region ITextGenerator implementation public uint Indent { get { return ActiveBlock.Indent; } } public void Write(string msg, params object[] args) { ActiveBlock.Write(msg, args); } public void WriteLine(string msg, params object[] args) { ActiveBlock.WriteLine(msg, args); } public void WriteLineIndent(string msg, params object[] args) { ActiveBlock.WriteLineIndent(msg, args); } public void NewLine() { ActiveBlock.NewLine(); } public void NewLineIfNeeded() { ActiveBlock.NewLineIfNeeded(); } public void NeedNewLine() { ActiveBlock.NeedNewLine(); } public void ResetNewLine() { ActiveBlock.ResetNewLine(); } public void PushIndent(uint indent = 4u) { ActiveBlock.PushIndent(indent); } public void PopIndent() { ActiveBlock.PopIndent(); } public void WriteStartBraceIndent() { ActiveBlock.WriteStartBraceIndent(); } public void WriteCloseBraceIndent() { ActiveBlock.WriteCloseBraceIndent(); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using System; using System.Collections.Generic; namespace OpenSim.Framework { public class InventoryFolderImpl : InventoryFolderBase { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static readonly string PATH_DELIMITER = "/"; /// <summary> /// Items that are contained in this folder /// </summary> public Dictionary<UUID, InventoryItemBase> Items = new Dictionary<UUID, InventoryItemBase>(); /// <summary> /// Child folders that are contained in this folder /// </summary> protected Dictionary<UUID, InventoryFolderImpl> m_childFolders = new Dictionary<UUID, InventoryFolderImpl>(); // Constructors public InventoryFolderImpl(InventoryFolderBase folderbase) { Owner = folderbase.Owner; ID = folderbase.ID; Name = folderbase.Name; ParentID = folderbase.ParentID; Type = folderbase.Type; Version = folderbase.Version; } public InventoryFolderImpl() { } /// <value> /// The total number of items in this folder and in the immediate child folders (though not from other /// descendants). /// </value> public int TotalCount { get { int total = Items.Count; foreach (InventoryFolderImpl folder in m_childFolders.Values) { total = total + folder.TotalCount; } return total; } } /// <summary> /// Add a folder that already exists. /// </summary> /// <param name="folder"></param> public void AddChildFolder(InventoryFolderImpl folder) { lock (m_childFolders) { folder.ParentID = ID; m_childFolders[folder.ID] = folder; } } /// <summary> /// Does this folder contain the given child folder? /// </summary> /// <param name="folderID"></param> /// <returns></returns> public bool ContainsChildFolder(UUID folderID) { return m_childFolders.ContainsKey(folderID); } /// <summary> /// Create a new subfolder. /// </summary> /// <param name="folderID"></param> /// <param name="folderName"></param> /// <param name="type"></param> /// <returns>The newly created subfolder. Returns null if the folder already exists</returns> public InventoryFolderImpl CreateChildFolder(UUID folderID, string folderName, ushort type) { lock (m_childFolders) { if (!m_childFolders.ContainsKey(folderID)) { InventoryFolderImpl subFold = new InventoryFolderImpl(); subFold.Name = folderName; subFold.ID = folderID; subFold.Type = (short)type; subFold.ParentID = this.ID; subFold.Owner = Owner; m_childFolders.Add(subFold.ID, subFold); return subFold; } } return null; } /// <summary> /// Deletes an item if it exists in this folder or any children /// </summary> /// <param name="folderID"></param> /// <returns></returns> public bool DeleteItem(UUID itemID) { bool found = false; lock (Items) { if (Items.ContainsKey(itemID)) { Items.Remove(itemID); return true; } } lock (m_childFolders) { foreach (InventoryFolderImpl folder in m_childFolders.Values) { found = folder.DeleteItem(itemID); if (found == true) { break; } } } return found; } public InventoryItemBase FindAsset(UUID assetID) { lock (Items) { foreach (InventoryItemBase item in Items.Values) { if (item.AssetID == assetID) return item; } } lock (m_childFolders) { foreach (InventoryFolderImpl folder in m_childFolders.Values) { InventoryItemBase item = folder.FindAsset(assetID); if (item != null) { return item; } } } return null; } /// <summary> /// Returns the folder requested if it is this folder or is a descendent of this folder. The search is depth /// first. /// </summary> /// <returns>The requested folder if it exists, null if it does not.</returns> public InventoryFolderImpl FindFolder(UUID folderID) { if (folderID == ID) return this; lock (m_childFolders) { foreach (InventoryFolderImpl folder in m_childFolders.Values) { InventoryFolderImpl returnFolder = folder.FindFolder(folderID); if (returnFolder != null) return returnFolder; } } return null; } /// <summary> /// Find a folder given a PATH_DELIMITER delimited path starting from this folder /// </summary> /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We do not yet handle situations where folders have the same name. We could handle this by some /// XPath like expression /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// /// <param name="path"> /// The path to the required folder. /// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned. /// </param> /// <returns>null if the folder is not found</returns> public InventoryFolderImpl FindFolderByPath(string path) { if (path == string.Empty) return this; path = path.Trim(); if (path == PATH_DELIMITER) return this; string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None); lock (m_childFolders) { foreach (InventoryFolderImpl folder in m_childFolders.Values) { if (folder.Name == components[0]) if (components.Length > 1) return folder.FindFolderByPath(components[1]); else return folder; } } // We didn't find a folder with the given name return null; } /// <summary> /// Look through all child subfolders for a folder marked as one for a particular asset type, and return it. /// </summary> /// <param name="type"></param> /// <returns>Returns null if no such folder is found</returns> public InventoryFolderImpl FindFolderForType(int type) { lock (m_childFolders) { foreach (InventoryFolderImpl f in m_childFolders.Values) { if (f.Type == type) return f; } } return null; } /// <summary> /// Returns the item if it exists in this folder or in any of this folder's descendant folders /// </summary> /// <param name="itemID"></param> /// <returns>null if the item is not found</returns> public InventoryItemBase FindItem(UUID itemID) { lock (Items) { if (Items.ContainsKey(itemID)) { return Items[itemID]; } } lock (m_childFolders) { foreach (InventoryFolderImpl folder in m_childFolders.Values) { InventoryItemBase item = folder.FindItem(itemID); if (item != null) { return item; } } } return null; } /// <summary> /// Find an item given a PATH_DELIMITOR delimited path starting from this folder. /// /// This method does not handle paths that contain multiple delimitors /// /// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some /// XPath like expression /// /// FIXME: Delimitors which occur in names themselves are not currently escapable. /// </summary> /// <param name="path"> /// The path to the required item. /// </param> /// <returns>null if the item is not found</returns> public InventoryItemBase FindItemByPath(string path) { string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None); if (components.Length == 1) { lock (Items) { foreach (InventoryItemBase item in Items.Values) { if (item.Name == components[0]) return item; } } } else { lock (m_childFolders) { foreach (InventoryFolderImpl folder in m_childFolders.Values) { if (folder.Name == components[0]) return folder.FindItemByPath(components[1]); } } } // We didn't find an item or intermediate folder with the given name return null; } /// <summary> /// Get a child folder /// </summary> /// <param name="folderID"></param> /// <returns>The folder if it exists, null if it doesn't</returns> public InventoryFolderImpl GetChildFolder(UUID folderID) { InventoryFolderImpl folder = null; lock (m_childFolders) { m_childFolders.TryGetValue(folderID, out folder); } return folder; } /// <summary> /// Delete all the folders and items in this folder. /// </summary> public void Purge() { foreach (InventoryFolderImpl folder in m_childFolders.Values) { folder.Purge(); } m_childFolders.Clear(); Items.Clear(); } /// <summary> /// Removes the given child subfolder. /// </summary> /// <param name="folderID"></param> /// <returns> /// The folder removed, or null if the folder was not present. /// </returns> public InventoryFolderImpl RemoveChildFolder(UUID folderID) { InventoryFolderImpl removedFolder = null; lock (m_childFolders) { if (m_childFolders.ContainsKey(folderID)) { removedFolder = m_childFolders[folderID]; m_childFolders.Remove(folderID); } } return removedFolder; } public List<InventoryFolderImpl> RequestListOfFolderImpls() { List<InventoryFolderImpl> folderList = new List<InventoryFolderImpl>(); lock (m_childFolders) { foreach (InventoryFolderImpl folder in m_childFolders.Values) { folderList.Add(folder); } } return folderList; } /// <summary> /// Return a copy of the list of child folders in this folder. The folders themselves are the originals. /// </summary> public List<InventoryFolderBase> RequestListOfFolders() { List<InventoryFolderBase> folderList = new List<InventoryFolderBase>(); lock (m_childFolders) { foreach (InventoryFolderBase folder in m_childFolders.Values) { folderList.Add(folder); } } return folderList; } /// <summary> /// Return a copy of the list of child items in this folder. The items themselves are the originals. /// </summary> public List<InventoryItemBase> RequestListOfItems() { List<InventoryItemBase> itemList = new List<InventoryItemBase>(); lock (Items) { foreach (InventoryItemBase item in Items.Values) { // m_log.DebugFormat( // "[INVENTORY FOLDER IMPL]: Returning item {0} {1}, OwnerPermissions {2:X}", // item.Name, item.ID, item.CurrentPermissions); itemList.Add(item); } } //m_log.DebugFormat("[INVENTORY FOLDER IMPL]: Found {0} items", itemList.Count); return itemList; } } }
/* Copyright 2013-2014 Daikon Forge */ using UnityEngine; using UnityEditor; using System.Collections; public class dfGUIWizard : EditorWindow { #region Editor menu integration // Slowly migrating menu option locations, will remove older ones as // users become used to the new locations [MenuItem( "Tools/Daikon Forge/UI Wizard", false, 0 )] [MenuItem( "GameObject/Daikon Forge/UI Wizard", false, 0 )] static void ShowGUIWizard() { var window = GetWindow<dfGUIWizard>(); window.title = "GUI Wizard"; window.LoadPrefs(); } #endregion #region Private variables private int layer = 0; private bool orthographic = true; private bool pixelPerfect = true; private bool useJoystick = false; private KeyCode joystickClickButton = KeyCode.None; private string horizontalAxis = "Horizontal"; private string verticalAxis = "Vertical"; #endregion #region Unity Editor window events private void OnGUI() { using( dfEditorUtil.BeginGroup( "GUI Manager settings" ) ) { layer = EditorGUILayout.LayerField( "UI Layer", layer ); if( layer > 30 ) { EditorGUILayout.HelpBox( "Daikon Forge GUI will not work correctly on the selected layer. Please choose another layer.", MessageType.Warning ); return; } orthographic = EditorGUILayout.Toggle( "Orthographic", orthographic ); pixelPerfect = EditorGUILayout.Toggle( "Pixel Perfect", pixelPerfect ); } EditorGUILayout.Separator(); using( dfEditorUtil.BeginGroup( "GUI Input Manager settings" ) ) { useJoystick = EditorGUILayout.Toggle( "Use Joystick", useJoystick ); joystickClickButton = (KeyCode)EditorGUILayout.EnumPopup( "Joystick Click Button", joystickClickButton ); horizontalAxis = EditorGUILayout.TextField( "Horizontal Axis", horizontalAxis ); verticalAxis = EditorGUILayout.TextField( "Vertical Axis", verticalAxis ); } EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); { if( GUILayout.Button( "Help" ) ) { Application.OpenURL( "http://www.daikonforge.com/dfgui/getting-started/" ); } if( GUILayout.Button( "Create" ) ) { SavePrefs(); CreateUI(); } } EditorGUILayout.EndHorizontal(); } #endregion #region Public methods public void SavePrefs() { EditorPrefs.SetInt( "DFGUIWizard.Layer", layer ); EditorPrefs.SetBool( "DFGUIWizard.Ortho", orthographic ); EditorPrefs.SetBool( "DFGUIWizard.PixelPerfect", pixelPerfect ); EditorPrefs.SetBool( "DFGUIWizard.UseJoystick", useJoystick ); EditorPrefs.SetInt( "DFGUIWizard.JoystickClickButton", (int)joystickClickButton ); EditorPrefs.SetString( "DFGUIWizard.HorizontalAxis", horizontalAxis ); EditorPrefs.SetString( "DFGUIWizard.VerticalAxis", verticalAxis ); } public void LoadPrefs() { layer = EditorPrefs.GetInt( "DFGUIWizard.Layer", 0 ); orthographic = EditorPrefs.GetBool( "DFGUIWizard.Ortho", true ); pixelPerfect = EditorPrefs.GetBool( "DFGUIWizard.PixelPerfect", true ); useJoystick = EditorPrefs.GetBool( "DFGUIWizard.UseJoystick", false ); joystickClickButton = (KeyCode)EditorPrefs.GetInt( "DFGUIWizard.JoystickClickButton", (int)KeyCode.None ); horizontalAxis = EditorPrefs.GetString( "DFGUIWizard.HorizontalAxis", horizontalAxis ); verticalAxis = EditorPrefs.GetString( "DFGUIWizard.VerticalAxis", verticalAxis ); } #endregion #region Private utility methods private void CreateUI() { // Make sure other cameras already in the scene don't render the designated layer var sceneCameras = FindObjectsOfType( typeof( Camera ) ) as Camera[]; for( int i = 0; i < sceneCameras.Length; i++ ) { var sceneCamera = sceneCameras[ i ]; if( sceneCamera.gameObject.activeInHierarchy && sceneCamera.GetComponent<dfGUICamera>() == null ) { sceneCameras[ i ].cullingMask &= ~( 1 << layer ); sceneCameras[ i ].eventMask &= ~( 1 << layer ); EditorUtility.SetDirty( sceneCameras[ i ] ); } } GameObject go = new GameObject( "UI Root" ); go.transform.position = new Vector3( -100, 100, 0 ); go.layer = layer; GameObject cam_go = new GameObject( "UI Camera" ); cam_go.transform.parent = go.transform; cam_go.transform.localPosition = Vector3.zero; cam_go.transform.localRotation = Quaternion.identity; Camera cam = cam_go.AddComponent<Camera>(); cam.depth = getGuiCameraDepth(); cam.farClipPlane = 5; cam.clearFlags = CameraClearFlags.Depth; cam.cullingMask = ( 1 << layer ); cam.isOrthoGraphic = orthographic; dfGUIManager guiManager = go.AddComponent<dfGUIManager>(); guiManager.RenderCamera = cam; guiManager.PixelPerfectMode = pixelPerfect; guiManager.UIScaleLegacyMode = false; dfInputManager inputManager = go.GetComponent<dfInputManager>(); inputManager.RenderCamera = cam; inputManager.UseJoystick = useJoystick; inputManager.JoystickClickButton = joystickClickButton; inputManager.HorizontalAxis = horizontalAxis; inputManager.VerticalAxis = verticalAxis; inputManager.HoverStartDelay = 0f; inputManager.HoverNotificationFrequency = 0f; #if WEB_PLAYER guiManager.FixedHeight = PlayerSettings.defaultWebScreenHeight; guiManager.RenderCamera.aspect = (float)PlayerSettings.defaultWebScreenWidth / (float)PlayerSettings.defaultWebScreenHeight; #else guiManager.FixedHeight = PlayerSettings.defaultScreenHeight; guiManager.RenderCamera.aspect = (float)PlayerSettings.defaultScreenWidth / (float)PlayerSettings.defaultScreenHeight; #endif dfEditorUtil.DelayedInvoke( () => { Selection.activeObject = guiManager; var scene = SceneView.currentDrawingSceneView ?? SceneView.lastActiveSceneView; if( scene != null ) { scene.orthographic = true; scene.pivot = guiManager.transform.position; scene.AlignViewToObject( guiManager.transform ); } } ); this.Close(); } private float getGuiCameraDepth() { if( Camera.main != null ) return Mathf.Max( 1, Camera.main.depth + 1 ); return 1; } #endregion }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; namespace Apache.Geode.Client.Tests { using Apache.Geode.Client; /// <summary> /// User class for testing the put functionality for object. /// </summary> public class Portfolio : IGeodeSerializable { #region Private members and methods private int m_id; private string m_pkid; private Position m_position1; private Position m_position2; private Dictionary<Object, Object> m_positions; private string m_type; private string m_status; private string[] m_names; private byte[] m_newVal; private DateTime m_creationDate; private byte[] m_arrayZeroSize; private byte[] m_arrayNull; private static string[] m_secIds = { "SUN", "IBM", "YHOO", "GOOG", "MSFT", "AOL", "APPL", "ORCL", "SAP", "DELL" }; private UInt32 GetObjectSize(IGeodeSerializable obj) { return (obj == null ? 0 : obj.ObjectSize); } #endregion #region Public accessors public int ID { get { return m_id; } } public string Pkid { get { return m_pkid; } } public Position P1 { get { return m_position1; } } public Position P2 { get { return m_position2; } } public IDictionary<Object, Object> Positions { get { return m_positions; } } public string Status { get { return m_status; } } public bool IsActive { get { return (m_status == "active"); } } public byte[] NewVal { get { return m_newVal; } } public byte[] ArrayNull { get { return m_arrayNull; } } public byte[] ArrayZeroSize { get { return m_arrayZeroSize; } } public DateTime CreationDate { get { return m_creationDate; } } public string Type { get { return m_type; } } public static string[] SecIds { get { return m_secIds; } } public override string ToString() { string portStr = string.Format("Portfolio [ID={0} status={1} " + "type={2} pkid={3}]", m_id, m_status, m_type, m_pkid); portStr += string.Format("{0}\tP1: {1}", Environment.NewLine, m_position1); portStr += string.Format("{0}\tP2: {1}", Environment.NewLine, m_position2); portStr += string.Format("{0}Creation Date: {1}", Environment.NewLine, m_creationDate); return portStr; } #endregion #region Constructors public Portfolio() { m_id = 0; m_pkid = null; m_type = null; m_status = null; m_newVal = null; m_creationDate = DateTime.MinValue; } public Portfolio(int id) : this(id, 0) { } public Portfolio(int id, int size) : this(id, size, null) { } public Portfolio(int id, int size, string[] names) { m_names = names; m_id = id; m_pkid = id.ToString(); m_status = (id % 2 == 0) ? "active" : "inactive"; m_type = "type" + (id % 3); int numSecIds = m_secIds.Length; m_position1 = new Position(m_secIds[Position.Count % numSecIds], Position.Count * 1000); if (id % 2 != 0) { m_position2 = new Position(m_secIds[Position.Count % numSecIds], Position.Count * 1000); } else { m_position2 = null; } m_positions = new Dictionary<Object, Object>(); m_positions[(m_secIds[Position.Count % numSecIds])] = m_position1; if (size > 0) { m_newVal = new byte[size]; for (int index = 0; index < size; index++) { m_newVal[index] = (byte)'B'; } } m_creationDate = DateTime.Now; m_arrayNull = null; m_arrayZeroSize = new byte[0]; } #endregion #region IGeodeSerializable Members public IGeodeSerializable FromData(DataInput input) { m_id = input.ReadInt32(); m_pkid = input.ReadUTF(); m_position1 = (Position)input.ReadObject(); m_position2 = (Position)input.ReadObject(); m_positions = new Dictionary<Object, Object>(); input.ReadDictionary((System.Collections.IDictionary)m_positions); m_type = input.ReadUTF(); m_status = input.ReadUTF(); m_names = (string[])(object)input.ReadObject(); m_newVal = input.ReadBytes(); m_creationDate = input.ReadDate(); m_arrayNull = input.ReadBytes(); m_arrayZeroSize = input.ReadBytes(); return this; } public void ToData(DataOutput output) { output.WriteInt32(m_id); output.WriteUTF(m_pkid); output.WriteObject(m_position1); output.WriteObject(m_position2); output.WriteDictionary((System.Collections.IDictionary)m_positions); output.WriteUTF(m_type); output.WriteUTF(m_status); output.WriteObject(m_names); output.WriteBytes(m_newVal); output.WriteDate(m_creationDate); output.WriteBytes(m_arrayNull); output.WriteBytes(m_arrayZeroSize); } public UInt32 ObjectSize { get { UInt32 objectSize = 0; objectSize += (UInt32)sizeof(Int32); objectSize += (UInt32)(m_pkid.Length * sizeof(char)); objectSize += GetObjectSize(m_position1); objectSize += GetObjectSize(m_position2); objectSize += (UInt32)(m_type.Length * sizeof(char)); objectSize += (UInt32)(m_status == null ? 0 : sizeof(char) * m_status.Length); objectSize += (uint)m_names.Length;//TODO:need to calculate properly objectSize += (UInt32)(m_newVal == null ? 0 : sizeof(byte) * m_newVal.Length); objectSize += 8; //TODO:need to calculate properly for m_creationDate.; objectSize += (UInt32)(m_arrayZeroSize == null ? 0 : sizeof(byte) * m_arrayZeroSize.Length); objectSize += (UInt32)(m_arrayNull == null ? 0 : sizeof(byte) * m_arrayNull.Length); return objectSize; } } public UInt32 ClassId { get { return 0x08; } } #endregion public static IGeodeSerializable CreateDeserializable() { return new Portfolio(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Security; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Text; using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Threading; namespace System.IO { public static class Directory { public static DirectoryInfo GetParent(String path) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, "path"); Contract.EndContractBlock(); String fullPath = PathHelpers.GetFullPathInternal(path); String s = Path.GetDirectoryName(fullPath); if (s == null) return null; return new DirectoryInfo(s); } [System.Security.SecuritySafeCritical] public static DirectoryInfo CreateDirectory(String path) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, "path"); Contract.EndContractBlock(); String fullPath = PathHelpers.GetFullPathInternal(path); FileSystem.Current.CreateDirectory(fullPath); return new DirectoryInfo(fullPath, null); } // Input to this method should already be fullpath. This method will ensure that we append // the trailing slash only when appropriate. internal static String EnsureTrailingDirectorySeparator(string fullPath) { String fullPathWithTrailingDirectorySeparator; if (!PathHelpers.EndsInDirectorySeparator(fullPath)) fullPathWithTrailingDirectorySeparator = fullPath + PathHelpers.DirectorySeparatorCharAsString; else fullPathWithTrailingDirectorySeparator = fullPath; return fullPathWithTrailingDirectorySeparator; } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // [System.Security.SecuritySafeCritical] // auto-generated public static bool Exists(String path) { try { if (path == null) return false; if (path.Length == 0) return false; String fullPath = PathHelpers.GetFullPathInternal(path); return FileSystem.Current.DirectoryExists(fullPath); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } public static void SetCreationTime(String path, DateTime creationTime) { String fullPath = PathHelpers.GetFullPathInternal(path); FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: true); } public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc) { String fullPath = PathHelpers.GetFullPathInternal(path); FileSystem.Current.SetCreationTime(fullPath, File.GetUtcDateTimeOffset(creationTimeUtc), asDirectory: true); } public static DateTime GetCreationTime(String path) { return File.GetCreationTime(path); } public static DateTime GetCreationTimeUtc(String path) { return File.GetCreationTimeUtc(path); } public static void SetLastWriteTime(String path, DateTime lastWriteTime) { String fullPath = PathHelpers.GetFullPathInternal(path); FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: true); } public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc) { String fullPath = PathHelpers.GetFullPathInternal(path); FileSystem.Current.SetLastWriteTime(fullPath, File.GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: true); } public static DateTime GetLastWriteTime(String path) { return File.GetLastWriteTime(path); } public static DateTime GetLastWriteTimeUtc(String path) { return File.GetLastWriteTimeUtc(path); } public static void SetLastAccessTime(String path, DateTime lastAccessTime) { String fullPath = PathHelpers.GetFullPathInternal(path); FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: true); } public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc) { String fullPath = PathHelpers.GetFullPathInternal(path); FileSystem.Current.SetLastAccessTime(fullPath, File.GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: true); } public static DateTime GetLastAccessTime(String path) { return File.GetLastAccessTime(path); } public static DateTime GetLastAccessTimeUtc(String path) { return File.GetLastAccessTimeUtc(path); } // Returns an array of filenames in the DirectoryInfo specified by path public static String[] GetFiles(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search pattern (ie, "*.txt"). public static String[] GetFiles(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search pattern (ie, "*.txt") and search option public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFiles(path, searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search pattern (ie, "*.txt") and search option private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption); } // Returns an array of Directories in the current directory. public static String[] GetDirectories(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public static String[] GetDirectories(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetDirectories(path, searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<String[]>() != null); return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path public static String[] GetFileSystemEntries(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria public static String[] GetFileSystemEntries(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return InternalGetFileSystemEntries(path, searchPattern, searchOption); } private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption); } // Private class that holds search data that is passed around // in the heap based stack recursion internal sealed class SearchData { public SearchData(String fullPath, String userPath, SearchOption searchOption) { Contract.Requires(fullPath != null && fullPath.Length > 0); Contract.Requires(userPath != null && userPath.Length > 0); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); this.fullPath = fullPath; this.userPath = userPath; this.searchOption = searchOption; } public readonly string fullPath; // Fully qualified search path excluding the search criteria in the end (ex, c:\temp\bar\foo) public readonly string userPath; // User specified path (ex, bar\foo) public readonly SearchOption searchOption; } // Returns fully qualified user path of dirs/files that matches the search parameters. // For recursive search this method will search through all the sub dirs and execute // the given search criteria against every dir. // For all the dirs/files returned, it will then demand path discovery permission for // their parent folders (it will avoid duplicate permission checks) internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(userPathOriginal != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<String> enumerable = FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption, (includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0)); List<String> fileList = new List<String>(enumerable); return fileList.ToArray(); } public static IEnumerable<String> EnumerateDirectories(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateDirectories(path, searchPattern, searchOption); } private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true); } public static IEnumerable<String> EnumerateFiles(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFiles(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFiles(path, searchPattern, searchOption); } private static IEnumerable<String> InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false); } public static IEnumerable<String> EnumerateFileSystemEntries(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { if (path == null) throw new ArgumentNullException("path"); if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); Contract.EndContractBlock(); return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption); } private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true); } private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption, bool includeFiles, bool includeDirs) { Contract.Requires(path != null); Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); Contract.Ensures(Contract.Result<IEnumerable<String>>() != null); return FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption, (includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0)); } [System.Security.SecuritySafeCritical] public static String GetDirectoryRoot(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); String fullPath = PathHelpers.GetFullPathInternal(path); String root = fullPath.Substring(0, PathHelpers.GetRootLength(fullPath)); return root; } internal static String InternalGetDirectoryRoot(String path) { if (path == null) return null; return path.Substring(0, PathHelpers.GetRootLength(path)); } /*===============================CurrentDirectory=============================== **Action: Provides a getter and setter for the current directory. The original ** current DirectoryInfo is the one from which the process was started. **Returns: The current DirectoryInfo (from the getter). Void from the setter. **Arguments: The current DirectoryInfo to which to switch to the setter. **Exceptions: ==============================================================================*/ [System.Security.SecuritySafeCritical] public static String GetCurrentDirectory() { return FileSystem.Current.GetCurrentDirectory(); } [System.Security.SecurityCritical] // auto-generated public static void SetCurrentDirectory(String path) { if (path == null) throw new ArgumentNullException("value"); if (path.Length == 0) throw new ArgumentException(SR.Argument_PathEmpty, "path"); Contract.EndContractBlock(); if (path.Length >= FileSystem.Current.MaxPath) throw new PathTooLongException(SR.IO_PathTooLong); String fulldestDirName = PathHelpers.GetFullPathInternal(path); FileSystem.Current.SetCurrentDirectory(fulldestDirName); } [System.Security.SecuritySafeCritical] public static void Move(String sourceDirName, String destDirName) { if (sourceDirName == null) throw new ArgumentNullException("sourceDirName"); if (sourceDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, "sourceDirName"); if (destDirName == null) throw new ArgumentNullException("destDirName"); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName"); Contract.EndContractBlock(); String fullsourceDirName = PathHelpers.GetFullPathInternal(sourceDirName); String sourcePath = EnsureTrailingDirectorySeparator(fullsourceDirName); int maxDirectoryPath = FileSystem.Current.MaxDirectoryPath; if (sourcePath.Length >= maxDirectoryPath) throw new PathTooLongException(SR.IO_PathTooLong); String fulldestDirName = PathHelpers.GetFullPathInternal(destDirName); String destPath = EnsureTrailingDirectorySeparator(fulldestDirName); if (destPath.Length >= maxDirectoryPath) throw new PathTooLongException(SR.IO_PathTooLong); StringComparison pathComparison = PathInternal.GetComparison(); if (String.Equals(sourcePath, destPath, pathComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); String sourceRoot = Path.GetPathRoot(sourcePath); String destinationRoot = Path.GetPathRoot(destPath); if (!String.Equals(sourceRoot, destinationRoot, pathComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); FileSystem.Current.MoveDirectory(fullsourceDirName, fulldestDirName); } [System.Security.SecuritySafeCritical] public static void Delete(String path) { String fullPath = PathHelpers.GetFullPathInternal(path); FileSystem.Current.RemoveDirectory(fullPath, false); } [System.Security.SecuritySafeCritical] public static void Delete(String path, bool recursive) { String fullPath = PathHelpers.GetFullPathInternal(path); FileSystem.Current.RemoveDirectory(fullPath, recursive); } } }
/* * 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; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Reflection; using OpenSim.Framework; using OpenMetaverse; using log4net; namespace OpenSim.Services.Interfaces { public interface IGridService { /// <summary> /// Register a region with the grid service. /// </summary> /// <param name="regionInfos"> </param> /// <returns></returns> /// <exception cref="System.Exception">Thrown if region registration failed</exception> string RegisterRegion(UUID scopeID, GridRegion regionInfos); /// <summary> /// Deregister a region with the grid service. /// </summary> /// <param name="regionID"></param> /// <returns></returns> /// <exception cref="System.Exception">Thrown if region deregistration failed</exception> bool DeregisterRegion(UUID regionID); /// <summary> /// Get information about the regions neighbouring the given co-ordinates (in meters). /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID); GridRegion GetRegionByUUID(UUID scopeID, UUID regionID); /// <summary> /// Get the region at the given position (in meters) /// </summary> /// <param name="scopeID"></param> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> GridRegion GetRegionByPosition(UUID scopeID, int x, int y); /// <summary> /// Get information about a region which exactly matches the name given. /// </summary> /// <param name="scopeID"></param> /// <param name="regionName"></param> /// <returns>Returns the region information if the name matched. Null otherwise.</returns> GridRegion GetRegionByName(UUID scopeID, string regionName); /// <summary> /// Get information about regions starting with the provided name. /// </summary> /// <param name="name"> /// The name to match against. /// </param> /// <param name="maxNumber"> /// The maximum number of results to return. /// </param> /// <returns> /// A list of <see cref="RegionInfo"/>s of regions with matching name. If the /// grid-server couldn't be contacted or returned an error, return null. /// </returns> List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber); List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax); List<GridRegion> GetDefaultRegions(UUID scopeID); List<GridRegion> GetDefaultHypergridRegions(UUID scopeID); List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y); List<GridRegion> GetHyperlinks(UUID scopeID); /// <summary> /// Get internal OpenSimulator region flags. /// </summary> /// <remarks> /// See OpenSimulator.Framework.RegionFlags. These are not returned in the GridRegion structure - /// they currently need to be requested separately. Possibly this should change to avoid multiple service calls /// in some situations. /// </remarks> /// <returns> /// The region flags. /// </returns> /// <param name='scopeID'></param> /// <param name='regionID'></param> int GetRegionFlags(UUID scopeID, UUID regionID); Dictionary<string,object> GetExtraFeatures(); } public interface IHypergridLinker { GridRegion TryLinkRegionToCoords(UUID scopeID, string mapName, int xloc, int yloc, UUID ownerID, out string reason); bool TryUnlinkRegion(string mapName); } public class GridRegion { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #pragma warning disable 414 private static readonly string LogHeader = "[GRID REGION]"; #pragma warning restore 414 /// <summary> /// The port by which http communication occurs with the region /// </summary> public uint HttpPort { get; set; } /// <summary> /// A well-formed URI for the host region server (namely "http://" + ExternalHostName) /// </summary> public string ServerURI { get { if (!String.IsNullOrEmpty(m_serverURI)) { return m_serverURI; } else { if (HttpPort == 0) return "http://" + m_externalHostName + "/"; else return "http://" + m_externalHostName + ":" + HttpPort + "/"; } } set { if ( value == null) { m_serverURI = String.Empty; return; } if ( value.EndsWith("/") ) { m_serverURI = value; } else { m_serverURI = value + '/'; } } } protected string m_serverURI; /// <summary> /// Provides direct access to the 'm_serverURI' field, without returning a generated URL if m_serverURI is missing. /// </summary> public string RawServerURI { get { return m_serverURI; } set { m_serverURI = value; } } public string RegionName { get { return m_regionName; } set { m_regionName = value; } } protected string m_regionName = String.Empty; /// <summary> /// Region flags. /// </summary> /// <remarks> /// If not set (chiefly if a robust service is running code pre OpenSim 0.8.1) then this will be null and /// should be ignored. If you require flags information please use the separate IGridService.GetRegionFlags() call /// XXX: This field is currently ignored when used in RegisterRegion, but could potentially be /// used to set flags at this point. /// </remarks> public OpenSim.Framework.RegionFlags? RegionFlags { get; set; } protected string m_externalHostName; protected IPEndPoint m_internalEndPoint; /// <summary> /// The co-ordinate of this region in region units. /// </summary> public int RegionCoordX { get { return (int)Util.WorldToRegionLoc((uint)RegionLocX); } } /// <summary> /// The co-ordinate of this region in region units /// </summary> public int RegionCoordY { get { return (int)Util.WorldToRegionLoc((uint)RegionLocY); } } /// <summary> /// The location of this region in meters. /// DANGER DANGER! Note that this name means something different in RegionInfo. /// </summary> public int RegionLocX { get { return m_regionLocX; } set { m_regionLocX = value; } } protected int m_regionLocX; public int RegionSizeX { get; set; } public int RegionSizeY { get; set; } /// <summary> /// The location of this region in meters. /// DANGER DANGER! Note that this name means something different in RegionInfo. /// </summary> public int RegionLocY { get { return m_regionLocY; } set { m_regionLocY = value; } } protected int m_regionLocY; protected UUID m_estateOwner; public UUID EstateOwner { get { return m_estateOwner; } set { m_estateOwner = value; } } public UUID RegionID = UUID.Zero; public UUID ScopeID = UUID.Zero; public UUID TerrainImage = UUID.Zero; public UUID ParcelImage = UUID.Zero; public byte Access; public int Maturity; public string RegionSecret = string.Empty; public string Token = string.Empty; public GridRegion() { RegionSizeX = (int)Constants.RegionSize; RegionSizeY = (int)Constants.RegionSize; m_serverURI = string.Empty; } /* public GridRegion(int regionLocX, int regionLocY, IPEndPoint internalEndPoint, string externalUri) { m_regionLocX = regionLocX; m_regionLocY = regionLocY; RegionSizeX = (int)Constants.RegionSize; RegionSizeY = (int)Constants.RegionSize; m_internalEndPoint = internalEndPoint; m_externalHostName = externalUri; } public GridRegion(int regionLocX, int regionLocY, string externalUri, uint port) { m_regionLocX = regionLocX; m_regionLocY = regionLocY; RegionSizeX = (int)Constants.RegionSize; RegionSizeY = (int)Constants.RegionSize; m_externalHostName = externalUri; m_internalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)port); } */ public GridRegion(uint xcell, uint ycell) { m_regionLocX = (int)Util.RegionToWorldLoc(xcell); m_regionLocY = (int)Util.RegionToWorldLoc(ycell); RegionSizeX = (int)Constants.RegionSize; RegionSizeY = (int)Constants.RegionSize; } public GridRegion(RegionInfo ConvertFrom) { m_regionName = ConvertFrom.RegionName; m_regionLocX = (int)(ConvertFrom.WorldLocX); m_regionLocY = (int)(ConvertFrom.WorldLocY); RegionSizeX = (int)ConvertFrom.RegionSizeX; RegionSizeY = (int)ConvertFrom.RegionSizeY; m_internalEndPoint = ConvertFrom.InternalEndPoint; m_externalHostName = ConvertFrom.ExternalHostName; HttpPort = ConvertFrom.HttpPort; RegionID = ConvertFrom.RegionID; ServerURI = ConvertFrom.ServerURI; TerrainImage = ConvertFrom.RegionSettings.TerrainImageID; ParcelImage = ConvertFrom.RegionSettings.ParcelImageID; Access = ConvertFrom.AccessLevel; Maturity = ConvertFrom.RegionSettings.Maturity; RegionSecret = ConvertFrom.regionSecret; EstateOwner = ConvertFrom.EstateSettings.EstateOwner; } public GridRegion(GridRegion ConvertFrom) { m_regionName = ConvertFrom.RegionName; RegionFlags = ConvertFrom.RegionFlags; m_regionLocX = ConvertFrom.RegionLocX; m_regionLocY = ConvertFrom.RegionLocY; RegionSizeX = ConvertFrom.RegionSizeX; RegionSizeY = ConvertFrom.RegionSizeY; m_internalEndPoint = ConvertFrom.InternalEndPoint; m_externalHostName = ConvertFrom.ExternalHostName; HttpPort = ConvertFrom.HttpPort; RegionID = ConvertFrom.RegionID; ServerURI = ConvertFrom.ServerURI; TerrainImage = ConvertFrom.TerrainImage; ParcelImage = ConvertFrom.ParcelImage; Access = ConvertFrom.Access; Maturity = ConvertFrom.Maturity; RegionSecret = ConvertFrom.RegionSecret; EstateOwner = ConvertFrom.EstateOwner; } public GridRegion(Dictionary<string, object> kvp) { if (kvp.ContainsKey("uuid")) RegionID = new UUID((string)kvp["uuid"]); if (kvp.ContainsKey("locX")) RegionLocX = Convert.ToInt32((string)kvp["locX"]); if (kvp.ContainsKey("locY")) RegionLocY = Convert.ToInt32((string)kvp["locY"]); if (kvp.ContainsKey("sizeX")) RegionSizeX = Convert.ToInt32((string)kvp["sizeX"]); else RegionSizeX = (int)Constants.RegionSize; if (kvp.ContainsKey("sizeY")) RegionSizeY = Convert.ToInt32((string)kvp["sizeY"]); else RegionSizeX = (int)Constants.RegionSize; if (kvp.ContainsKey("regionName")) RegionName = (string)kvp["regionName"]; if (kvp.ContainsKey("access")) { byte access = Convert.ToByte((string)kvp["access"]); Access = access; Maturity = (int)Util.ConvertAccessLevelToMaturity(access); } if (kvp.ContainsKey("flags") && kvp["flags"] != null) RegionFlags = (OpenSim.Framework.RegionFlags?)Convert.ToInt32((string)kvp["flags"]); if (kvp.ContainsKey("serverIP")) { //int port = 0; //Int32.TryParse((string)kvp["serverPort"], out port); //IPEndPoint ep = new IPEndPoint(IPAddress.Parse((string)kvp["serverIP"]), port); ExternalHostName = (string)kvp["serverIP"]; } else ExternalHostName = "127.0.0.1"; if (kvp.ContainsKey("serverPort")) { Int32 port = 0; Int32.TryParse((string)kvp["serverPort"], out port); InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), port); } if (kvp.ContainsKey("serverHttpPort")) { UInt32 port = 0; UInt32.TryParse((string)kvp["serverHttpPort"], out port); HttpPort = port; } if (kvp.ContainsKey("serverURI")) ServerURI = (string)kvp["serverURI"]; if (kvp.ContainsKey("regionMapTexture")) UUID.TryParse((string)kvp["regionMapTexture"], out TerrainImage); if (kvp.ContainsKey("parcelMapTexture")) UUID.TryParse((string)kvp["parcelMapTexture"], out ParcelImage); if (kvp.ContainsKey("regionSecret")) RegionSecret =(string)kvp["regionSecret"]; if (kvp.ContainsKey("owner_uuid")) EstateOwner = new UUID(kvp["owner_uuid"].ToString()); if (kvp.ContainsKey("Token")) Token = kvp["Token"].ToString(); // m_log.DebugFormat("{0} New GridRegion. id={1}, loc=<{2},{3}>, size=<{4},{5}>", // LogHeader, RegionID, RegionLocX, RegionLocY, RegionSizeX, RegionSizeY); } public Dictionary<string, object> ToKeyValuePairs() { Dictionary<string, object> kvp = new Dictionary<string, object>(); kvp["uuid"] = RegionID.ToString(); kvp["locX"] = RegionLocX.ToString(); kvp["locY"] = RegionLocY.ToString(); kvp["sizeX"] = RegionSizeX.ToString(); kvp["sizeY"] = RegionSizeY.ToString(); kvp["regionName"] = RegionName; if (RegionFlags != null) kvp["flags"] = ((int)RegionFlags).ToString(); kvp["serverIP"] = ExternalHostName; //ExternalEndPoint.Address.ToString(); kvp["serverHttpPort"] = HttpPort.ToString(); kvp["serverURI"] = ServerURI; kvp["serverPort"] = InternalEndPoint.Port.ToString(); kvp["regionMapTexture"] = TerrainImage.ToString(); kvp["parcelMapTexture"] = ParcelImage.ToString(); kvp["access"] = Access.ToString(); kvp["regionSecret"] = RegionSecret; kvp["owner_uuid"] = EstateOwner.ToString(); kvp["Token"] = Token.ToString(); // Maturity doesn't seem to exist in the DB return kvp; } #region Definition of equality /// <summary> /// Define equality as two regions having the same, non-zero UUID. /// </summary> public bool Equals(GridRegion region) { if ((object)region == null) return false; // Return true if the non-zero UUIDs are equal: return (RegionID != UUID.Zero) && RegionID.Equals(region.RegionID); } public override bool Equals(Object obj) { if (obj == null) return false; return Equals(obj as GridRegion); } public override int GetHashCode() { return RegionID.GetHashCode() ^ TerrainImage.GetHashCode() ^ ParcelImage.GetHashCode(); } #endregion /// <value> /// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw. /// /// XXX Isn't this really doing too much to be a simple getter, rather than an explict method? /// </value> public IPEndPoint ExternalEndPoint { get { // Old one defaults to IPv6 //return new IPEndPoint(Dns.GetHostAddresses(m_externalHostName)[0], m_internalEndPoint.Port); IPAddress ia = null; // If it is already an IP, don't resolve it - just return directly if (IPAddress.TryParse(m_externalHostName, out ia)) return new IPEndPoint(ia, m_internalEndPoint.Port); // Reset for next check ia = null; try { foreach (IPAddress Adr in Dns.GetHostAddresses(m_externalHostName)) { if (ia == null) ia = Adr; if (Adr.AddressFamily == AddressFamily.InterNetwork) { ia = Adr; break; } } } catch (SocketException e) { /*throw new Exception( "Unable to resolve local hostname " + m_externalHostName + " innerException of type '" + e + "' attached to this exception", e);*/ // Don't throw a fatal exception here, instead, return Null and handle it in the caller. // Reason is, on systems such as OSgrid it has occured that known hostnames stop // resolving and thus make surrounding regions crash out with this exception. return null; } return new IPEndPoint(ia, m_internalEndPoint.Port); } } public string ExternalHostName { get { return m_externalHostName; } set { m_externalHostName = value; } } public IPEndPoint InternalEndPoint { get { return m_internalEndPoint; } set { m_internalEndPoint = value; } } public ulong RegionHandle { get { return Util.UIntsToLong((uint)RegionLocX, (uint)RegionLocY); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Reflection; namespace System.ComponentModel { /// <summary> /// The TypeDescriptionProvider class can be thought of as a "plug-in" for /// TypeDescriptor. There can be multiple type description provider classes /// all offering metadata to TypeDescriptor /// </summary> public abstract class TypeDescriptionProvider { private readonly TypeDescriptionProvider _parent; private EmptyCustomTypeDescriptor _emptyDescriptor; /// <summary> /// There are two versions of the constructor for this class. The empty /// constructor is identical to using TypeDescriptionProvider(null). /// If a child type description provider is passed into the constructor, /// the "base" versions of all methods will call to this parent provider. /// If no such provider is given, the base versions of the methods will /// return empty, but valid values. /// </summary> protected TypeDescriptionProvider() { } /// <summary> /// There are two versions of the constructor for this class. The empty /// constructor is identical to using TypeDescriptionProvider(null). /// If a child type description provider is passed into the constructor, /// the "base" versions of all methods will call to this parent provider. /// If no such provider is given, the base versions of the methods will /// return empty, but valid values. /// </summary> protected TypeDescriptionProvider(TypeDescriptionProvider parent) { _parent = parent; } /// <summary> /// This method is used to create an instance that can substitute for another /// data type. If the method is not interested in providing a substitute /// instance, it should call base. /// /// This method is prototyped as virtual, and by default returns null if no /// parent provider was passed. If a parent provider was passed, this /// method will invoke the parent provider's CreateInstance method. /// </summary> public virtual object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args) { if (_parent != null) { return _parent.CreateInstance(provider, objectType, argTypes, args); } if (objectType == null) { throw new ArgumentNullException(nameof(objectType)); } return Activator.CreateInstance(objectType, args); } /// <summary> /// TypeDescriptor may need to perform complex operations on collections of metadata. /// Since types are not unloaded for the life of a domain, TypeDescriptor will /// automatically cache the results of these operations based on type. There are a /// number of operations that use live object instances, however. These operations /// cannot be cached within TypeDescriptor because caching them would prevent the /// object from garbage collecting. Instead, TypeDescriptor allows for a per-object /// cache, accessed as an IDictionary of key/value pairs, to exist on an object. /// The GetCache method returns an instance of this cache. GetCache will return /// null if there is no supported cache for an object. /// </summary> public virtual IDictionary GetCache(object instance) { return _parent?.GetCache(instance); } /// <summary> /// This method returns an extended custom type descriptor for the given object. /// An extended type descriptor is a custom type descriptor that offers properties /// that other objects have added to this object, but are not actually defined on /// the object. For example, in the .NET Framework Component Model, objects that /// implement the interface IExtenderProvider can "attach" properties to other /// objects that reside in the same logical container. The GetTypeDescriptor /// method does not return a type descriptor that provides these extra extended /// properties. GetExtendedTypeDescriptor returns the set of these extended /// properties. TypeDescriptor will automatically merge the results of these /// two property collections. Note that while the .NET Framework component /// model only supports extended properties this API can be used for extended /// attributes and events as well, if the type description provider supports it. /// </summary> public virtual ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) { if (_parent != null) { return _parent.GetExtendedTypeDescriptor(instance); } return _emptyDescriptor ?? (_emptyDescriptor = new EmptyCustomTypeDescriptor()); } protected internal virtual IExtenderProvider[] GetExtenderProviders(object instance) { if (_parent != null) { return _parent.GetExtenderProviders(instance); } if (instance == null) { throw new ArgumentNullException(nameof(instance)); } return Array.Empty<IExtenderProvider>(); } /// <summary> /// The name of the specified component, or null if the component has no name. /// In many cases this will return the same value as GetComponentName. If the /// component resides in a nested container or has other nested semantics, it may /// return a different fully qualified name. /// /// If not overridden, the default implementation of this method will call /// GetTypeDescriptor.GetComponentName. /// </summary> public virtual string GetFullComponentName(object component) { if (_parent != null) { return _parent.GetFullComponentName(component); } return GetTypeDescriptor(component).GetComponentName(); } /// <summary> /// The GetReflection method is a lower level version of GetTypeDescriptor. /// If no custom type descriptor can be located for an object, GetReflectionType /// is called to perform normal reflection against the object. /// </summary> public Type GetReflectionType(Type objectType) { return GetReflectionType(objectType, null); } /// <summary> /// The GetReflection method is a lower level version of GetTypeDescriptor. /// If no custom type descriptor can be located for an object, GetReflectionType /// is called to perform normal reflection against the object. /// /// This method is prototyped as virtual, and by default returns the /// object type if no parent provider was passed. If a parent provider was passed, this /// method will invoke the parent provider's GetReflectionType method. /// </summary> public Type GetReflectionType(object instance) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } return GetReflectionType(instance.GetType(), instance); } /// <summary> /// The GetReflection method is a lower level version of GetTypeDescriptor. /// If no custom type descriptor can be located for an object, GetReflectionType /// is called to perform normal reflection against the object. /// /// This method is prototyped as virtual, and by default returns the /// object type if no parent provider was passed. If a parent provider was passed, this /// method will invoke the parent provider's GetReflectionType method. /// </summary> public virtual Type GetReflectionType(Type objectType, object instance) { if (_parent != null) { return _parent.GetReflectionType(objectType, instance); } return objectType; } /// <summary> /// The GetRuntimeType method reverses GetReflectionType to convert a reflection type /// back into a runtime type. Historically the Type.UnderlyingSystemType property has /// been used to return the runtime type. This isn't exactly correct, but it needs /// to be preserved unless all type description providers are revised. /// </summary> public virtual Type GetRuntimeType(Type reflectionType) { if (_parent != null) { return _parent.GetRuntimeType(reflectionType); } if (reflectionType == null) { throw new ArgumentNullException(nameof(reflectionType)); } if (reflectionType.GetType().Assembly == typeof(object).Assembly) { return reflectionType; } return reflectionType.UnderlyingSystemType; } /// <summary> /// This method returns a custom type descriptor for the given type / object. /// The objectType parameter is always valid, but the instance parameter may /// be null if no instance was passed to TypeDescriptor. The method should /// return a custom type descriptor for the object. If the method is not /// interested in providing type information for the object it should /// return base. /// </summary> public ICustomTypeDescriptor GetTypeDescriptor(Type objectType) { return GetTypeDescriptor(objectType, null); } /// <summary> /// This method returns a custom type descriptor for the given type / object. /// The objectType parameter is always valid, but the instance parameter may /// be null if no instance was passed to TypeDescriptor. The method should /// return a custom type descriptor for the object. If the method is not /// interested in providing type information for the object it should /// return base. /// </summary> public ICustomTypeDescriptor GetTypeDescriptor(object instance) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } return GetTypeDescriptor(instance.GetType(), instance); } /// <summary> /// This method returns a custom type descriptor for the given type / object. /// The objectType parameter is always valid, but the instance parameter may /// be null if no instance was passed to TypeDescriptor. The method should /// return a custom type descriptor for the object. If the method is not /// interested in providing type information for the object it should /// return base. /// /// This method is prototyped as virtual, and by default returns a /// custom type descriptor that returns empty collections for all values /// if no parent provider was passed. If a parent provider was passed, /// this method will invoke the parent provider's GetTypeDescriptor /// method. /// </summary> public virtual ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { if (_parent != null) { return _parent.GetTypeDescriptor(objectType, instance); } return _emptyDescriptor ?? (_emptyDescriptor = new EmptyCustomTypeDescriptor()); } /// <summary> /// This method returns true if the type is "supported" by the type descriptor /// and its chain of type description providers. /// </summary> public virtual bool IsSupportedType(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (_parent != null) { return _parent.IsSupportedType(type); } return true; } /// <summary> /// A simple empty descriptor that is used as a placeholder for times /// when the user does not provide their own. /// </summary> private sealed class EmptyCustomTypeDescriptor : CustomTypeDescriptor { } } }
// 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.Text; /// <summary> /// String.TrimStart /// </summary> public class StringTrim4 { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 256; // U+200B stops being trimmable http://msdn2.microsoft.com/en-us/library/t97s7bs3.aspx // U+FEFF has been deprecate as a trimmable space private string[] spaceStrings = new string[]{"\u0009","\u000A","\u000B","\u000C","\u000D","\u0020", "\u00A0","\u2000","\u2001","\u2002","\u2003","\u2004","\u2005", "\u2006","\u2007","\u2008","\u2009","\u200A","\u3000"}; public static int Main() { StringTrim4 st4 = new StringTrim4(); TestLibrary.TestFramework.BeginTestCase("StringTrim4"); if (st4.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region PostiveTesting public bool PosTest1() { bool retVal = true; string strA; char[] charA; string ActualResult; TestLibrary.TestFramework.BeginScenario("PosTest1: empty string trimStart char[]"); try { strA = string.Empty; charA = new char[] { TestLibrary.Generator.GetChar(-55), TestLibrary.Generator.GetChar(-55), TestLibrary.Generator.GetChar(-55) }; ActualResult = strA.TrimStart(charA); if (ActualResult != string.Empty) { TestLibrary.TestFramework.LogError("001", "empty string trimStart char[] ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string strA; char[] charA; string ActualResult; TestLibrary.TestFramework.BeginScenario("PosTest2:normal string trimStart char[] one"); try { strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); char char1 = this.GetChar(0, c_MINI_STRING_LENGTH); char char2 = this.GetChar(c_MINI_STRING_LENGTH, c_MINI_STRING_LENGTH + 68); char char3 = this.GetChar(c_MINI_STRING_LENGTH + 68, c_MAX_STRING_LENGTH / 2); char charEnd = this.GetChar(c_MAX_STRING_LENGTH / 2, c_MAX_STRING_LENGTH); charA = new char[] { char1, char2, char3 }; string strA1 = char1.ToString() + char3.ToString() + charEnd.ToString() + strA + char1.ToString() + char3.ToString(); ActualResult = strA1.TrimStart(charA); if (ActualResult.ToString() != charEnd.ToString() + strA.ToString() + char1.ToString() + char3.ToString()) { TestLibrary.TestFramework.LogError("003", "normal string trimStart char[] one ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string strA; char[] charA; string ActualResult; TestLibrary.TestFramework.BeginScenario("PosTest3:normal string trimStart char[] two"); try { strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); char char1 = this.GetChar(0, c_MINI_STRING_LENGTH); char char2 = this.GetChar(c_MINI_STRING_LENGTH, c_MINI_STRING_LENGTH + 68); char char3 = this.GetChar(c_MAX_STRING_LENGTH + 68, c_MAX_STRING_LENGTH / 2); char charStart = this.GetChar(c_MAX_STRING_LENGTH / 2, c_MAX_STRING_LENGTH); charA = new char[] { char1, char2, char3 }; string strA1 = char1.ToString() + char3.ToString() + charStart.ToString() + strA + char2.ToString() + charStart.ToString() + char1.ToString() + char3.ToString(); ActualResult = strA1.TrimStart(charA); if (ActualResult.ToString() != charStart.ToString() + strA + char2.ToString() + charStart.ToString() + char1.ToString() + char3.ToString()) { TestLibrary.TestFramework.LogError("005", "normal string trimStart char[] two ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string strA; char[] charA; string ActualResult; TestLibrary.TestFramework.BeginScenario("PosTest4:normal string trimStart char[] three"); try { strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); charA = new char[0]; string strB = spaceStrings[this.GetInt32(0, spaceStrings.Length)]; string strA1 = strB + "H" + strA + "D" + strB; ActualResult = strA1.TrimStart(charA); if (ActualResult.ToString() != "H" + strA + "D" + strB) { TestLibrary.TestFramework.LogError("007", "normal string trimStart char[] three ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string strA; char[] charA; string ActualResult; TestLibrary.TestFramework.BeginScenario("PosTest5:normal string trimStart char[] four"); try { strA = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); charA = new char[0]; string strB = spaceStrings[this.GetInt32(0, spaceStrings.Length)]; string strA1 = strB + "H" + strB + strA + "D" + strB; ActualResult = strA1.TrimStart(charA); if (ActualResult.ToString() != "H" + strB + strA + "D" + strB) { TestLibrary.TestFramework.LogError("009", "normal string trimStart char[] four ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest6() { int iCountErrors = 0; TestLibrary.TestFramework.BeginScenario("PosTest7: Trim consistent with char.IsWhitespace"); StringBuilder sb = new StringBuilder(); for (char c = char.MinValue; c < char.MaxValue; ++c) { if (char.IsWhiteSpace(c)) sb.Append(c); } string t = sb.ToString().Trim(); for(int i = 0; i<t.Length; i++) { iCountErrors++; TestLibrary.TestFramework.LogError("011", "Failure: " + t[i] + " not trimmed correctly."); } ///// Finish diagnostics and reporting of results. if ( iCountErrors == 0 ) { return true; } else { return false;} } #endregion #region Help method for geting test data private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } private Char GetChar(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return Convert.ToChar(minValue); } if (minValue < maxValue) { return Convert.ToChar(Convert.ToInt32(TestLibrary.Generator.GetChar(-55)) % (maxValue - minValue) + minValue); } } catch { throw; } return Convert.ToChar(minValue); } private string GetString(bool ValidPath, Int32 minValue, Int32 maxValue) { StringBuilder sVal = new StringBuilder(); string s; if (0 == minValue && 0 == maxValue) return String.Empty; if (minValue > maxValue) return null; if (ValidPath) { return TestLibrary.Generator.GetString(-55, ValidPath, minValue, maxValue); } else { int length = this.GetInt32(minValue, maxValue); for (int i = 0; length > i; i++) { char c = this.GetChar(minValue, maxValue); sVal.Append(c); } s = sVal.ToString(); return s; } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Configuration.Internal; using System.Diagnostics; using System.IO; using System.Net; using System.Runtime.InteropServices; namespace System.Configuration { internal sealed class ClientConfigurationHost : DelegatingConfigHost, IInternalConfigClientHost { internal const string MachineConfigName = "MACHINE"; internal const string ExeConfigName = "EXE"; internal const string RoamingUserConfigName = "ROAMING_USER"; internal const string LocalUserConfigName = "LOCAL_USER"; internal const string MachineConfigPath = MachineConfigName; internal const string ExeConfigPath = MachineConfigPath + "/" + ExeConfigName; internal const string RoamingUserConfigPath = ExeConfigPath + "/" + RoamingUserConfigName; internal const string LocalUserConfigPath = RoamingUserConfigPath + "/" + LocalUserConfigName; private const string MachineConfigFilename = "machine.config"; private const string MachineConfigSubdirectory = "Config"; private static readonly object s_version = new object(); private static volatile string s_machineConfigFilePath; private ClientConfigPaths _configPaths; // physical paths to client config files private string _exePath; // the physical path to the exe being configured private ExeConfigurationFileMap _fileMap; // optional file map private bool _initComplete; internal ClientConfigurationHost() { Host = new InternalConfigHost(); } internal ClientConfigPaths ConfigPaths => _configPaths ?? (_configPaths = ClientConfigPaths.GetPaths(_exePath, _initComplete)); internal static string MachineConfigFilePath { get { if (s_machineConfigFilePath == null) { string directory = AppDomain.CurrentDomain.BaseDirectory; s_machineConfigFilePath = Path.Combine(Path.Combine(directory, MachineConfigSubdirectory), MachineConfigFilename); } return s_machineConfigFilePath; } } public override bool HasRoamingConfig { get { if (_fileMap != null) return !string.IsNullOrEmpty(_fileMap.RoamingUserConfigFilename); else return ConfigPaths.HasRoamingConfig; } } public override bool HasLocalConfig { get { if (_fileMap != null) return !string.IsNullOrEmpty(_fileMap.LocalUserConfigFilename); else return ConfigPaths.HasLocalConfig; } } public override bool IsAppConfigHttp => !IsFile(GetStreamName(ExeConfigPath)); public override bool SupportsRefresh => true; public override bool SupportsPath => false; // Do we support location tags? public override bool SupportsLocation => false; bool IInternalConfigClientHost.IsExeConfig(string configPath) { return StringUtil.EqualsIgnoreCase(configPath, ExeConfigPath); } bool IInternalConfigClientHost.IsRoamingUserConfig(string configPath) { return StringUtil.EqualsIgnoreCase(configPath, RoamingUserConfigPath); } bool IInternalConfigClientHost.IsLocalUserConfig(string configPath) { return StringUtil.EqualsIgnoreCase(configPath, LocalUserConfigPath); } string IInternalConfigClientHost.GetExeConfigPath() { return ExeConfigPath; } string IInternalConfigClientHost.GetRoamingUserConfigPath() { return RoamingUserConfigPath; } string IInternalConfigClientHost.GetLocalUserConfigPath() { return LocalUserConfigPath; } public override void RefreshConfigPaths() { // Refresh current config paths. if ((_configPaths != null) && !_configPaths.HasEntryAssembly && (_exePath == null)) { ClientConfigPaths.RefreshCurrent(); _configPaths = null; } } // Return true if the config path is for a user.config file, false otherwise. private bool IsUserConfig(string configPath) { return StringUtil.EqualsIgnoreCase(configPath, RoamingUserConfigPath) || StringUtil.EqualsIgnoreCase(configPath, LocalUserConfigPath); } public override void Init(IInternalConfigRoot configRoot, params object[] hostInitParams) { try { ConfigurationFileMap fileMap = (ConfigurationFileMap)hostInitParams[0]; _exePath = (string)hostInitParams[1]; Host.Init(configRoot, hostInitParams); // Do not complete initialization in runtime config, to avoid expense of // loading user.config files that may not be required. _initComplete = configRoot.IsDesignTime; if ((fileMap != null) && !string.IsNullOrEmpty(_exePath)) throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init"); if (string.IsNullOrEmpty(_exePath)) _exePath = null; // Initialize the fileMap, if provided. if (fileMap != null) { _fileMap = new ExeConfigurationFileMap(); if (!string.IsNullOrEmpty(fileMap.MachineConfigFilename)) _fileMap.MachineConfigFilename = Path.GetFullPath(fileMap.MachineConfigFilename); ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap; if (exeFileMap != null) { if (!string.IsNullOrEmpty(exeFileMap.ExeConfigFilename)) _fileMap.ExeConfigFilename = Path.GetFullPath(exeFileMap.ExeConfigFilename); if (!string.IsNullOrEmpty(exeFileMap.RoamingUserConfigFilename)) _fileMap.RoamingUserConfigFilename = Path.GetFullPath(exeFileMap.RoamingUserConfigFilename); if (!string.IsNullOrEmpty(exeFileMap.LocalUserConfigFilename)) _fileMap.LocalUserConfigFilename = Path.GetFullPath(exeFileMap.LocalUserConfigFilename); } } } catch { throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init"); } } public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) { locationSubPath = null; configPath = (string)hostInitConfigurationParams[2]; locationConfigPath = null; Init(configRoot, hostInitConfigurationParams); } // Delay init if we have not been asked to complete init, and it is a user.config file. public override bool IsInitDelayed(IInternalConfigRecord configRecord) { return !_initComplete && IsUserConfig(configRecord.ConfigPath); } public override void RequireCompleteInit(IInternalConfigRecord record) { // Loading information about user.config files is expensive, // so do it just once by locking. lock (this) { if (!_initComplete) { // Note that all future requests for config must be complete. _initComplete = true; // Throw out the ConfigPath for this exe. ClientConfigPaths.RefreshCurrent(); // Throw out our cached copy. _configPaths = null; // Force loading of user.config file information under lock. _ = ConfigPaths; } } } public override bool IsConfigRecordRequired(string configPath) { string configName = ConfigPathUtility.GetName(configPath); switch (configName) { case MachineConfigName: case ExeConfigName: return true; case RoamingUserConfigName: // Makes the design easier even if we only have an empty Roaming config record. return HasRoamingConfig || HasLocalConfig; case LocalUserConfigName: return HasLocalConfig; default: // should never get here Debug.Fail("unexpected config name: " + configName); return false; } } public override string GetStreamName(string configPath) { string configName = ConfigPathUtility.GetName(configPath); switch (configName) { case MachineConfigName: return _fileMap?.MachineConfigFilename ?? MachineConfigFilePath; case ExeConfigName: return _fileMap?.ExeConfigFilename ?? ConfigPaths.ApplicationConfigUri; case RoamingUserConfigName: return _fileMap?.RoamingUserConfigFilename ?? ConfigPaths.RoamingConfigFilename; case LocalUserConfigName: return _fileMap?.LocalUserConfigFilename ?? ConfigPaths.LocalConfigFilename; default: // should never get here Debug.Fail("unexpected config name: " + configName); goto case MachineConfigName; } } public override string GetStreamNameForConfigSource(string streamName, string configSource) { if (IsFile(streamName)) return Host.GetStreamNameForConfigSource(streamName, configSource); int index = streamName.LastIndexOf('/'); if (index < 0) return null; string parentUri = streamName.Substring(0, index + 1); string result = parentUri + configSource.Replace('\\', '/'); return result; } public override object GetStreamVersion(string streamName) { return IsFile(streamName) ? Host.GetStreamVersion(streamName) : s_version; } // default impl treats name as a file name // null means stream doesn't exist for this name public override Stream OpenStreamForRead(string streamName) { // the streamName can either be a file name, or a URI if (IsFile(streamName)) return Host.OpenStreamForRead(streamName); if (streamName == null) return null; // scheme is http WebClient client = new WebClient(); // Try using default credentials try { client.Credentials = CredentialCache.DefaultCredentials; } catch { } byte[] fileData = null; try { fileData = client.DownloadData(streamName); } catch { } if (fileData == null) return null; MemoryStream stream = new MemoryStream(fileData); return stream; } public override Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) { // only support files, not URIs if (!IsFile(streamName)) throw ExceptionUtil.UnexpectedError($"ClientConfigurationHost::OpenStreamForWrite '{streamName}' '{templateStreamName}'"); return Host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext); } public override void DeleteStream(string streamName) { // only support files, not URIs if (!IsFile(streamName)) throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Delete"); Host.DeleteStream(streamName); } public override bool IsDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition) { string allowedConfigPath; switch (allowExeDefinition) { case ConfigurationAllowExeDefinition.MachineOnly: allowedConfigPath = MachineConfigPath; break; case ConfigurationAllowExeDefinition.MachineToApplication: allowedConfigPath = ExeConfigPath; break; case ConfigurationAllowExeDefinition.MachineToRoamingUser: allowedConfigPath = RoamingUserConfigPath; break; // MachineToLocalUser does not current have any definition restrictions case ConfigurationAllowExeDefinition.MachineToLocalUser: return true; default: // If we have extended ConfigurationAllowExeDefinition // make sure to update this switch accordingly throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::IsDefinitionAllowed"); } return configPath.Length <= allowedConfigPath.Length; } public override void VerifyDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, IConfigErrorInfo errorInfo) { if (!IsDefinitionAllowed(configPath, allowDefinition, allowExeDefinition)) { throw allowExeDefinition switch { ConfigurationAllowExeDefinition.MachineOnly => new ConfigurationErrorsException( SR.Config_allow_exedefinition_error_machine, errorInfo), ConfigurationAllowExeDefinition.MachineToApplication => new ConfigurationErrorsException( SR.Config_allow_exedefinition_error_application, errorInfo), ConfigurationAllowExeDefinition.MachineToRoamingUser => new ConfigurationErrorsException( SR.Config_allow_exedefinition_error_roaminguser, errorInfo), // If we have extended ConfigurationAllowExeDefinition // make sure to update this switch accordingly _ => ExceptionUtil.UnexpectedError("ClientConfigurationHost::VerifyDefinitionAllowed"), }; } } // prefetch support public override bool PrefetchAll(string configPath, string streamName) { // If it's a file, we don't need to. Otherwise (e.g. it's from the web), we'll prefetch everything. return !IsFile(streamName); } public override bool PrefetchSection(string sectionGroupName, string sectionName) { return sectionGroupName == "system.net"; } public override object CreateDeprecatedConfigContext(string configPath) { return null; } public override object CreateConfigurationContext(string configPath, string locationSubPath) { return new ExeContext(GetUserLevel(configPath), ConfigPaths.ApplicationUri); } private ConfigurationUserLevel GetUserLevel(string configPath) { ConfigurationUserLevel level; switch (ConfigPathUtility.GetName(configPath)) { case MachineConfigName: level = ConfigurationUserLevel.None; break; case ExeConfigName: level = ConfigurationUserLevel.None; break; case LocalUserConfigName: level = ConfigurationUserLevel.PerUserRoamingAndLocal; break; case RoamingUserConfigName: level = ConfigurationUserLevel.PerUserRoaming; break; default: Debug.Fail("unrecognized configPath " + configPath); level = ConfigurationUserLevel.None; break; } return level; } internal static Configuration OpenExeConfiguration(ConfigurationFileMap fileMap, bool isMachine, ConfigurationUserLevel userLevel, string exePath) { // validate userLevel argument switch (userLevel) { case ConfigurationUserLevel.None: case ConfigurationUserLevel.PerUserRoaming: case ConfigurationUserLevel.PerUserRoamingAndLocal: break; default: throw ExceptionUtil.ParameterInvalid(nameof(userLevel)); } // validate fileMap arguments if (fileMap != null) { if (string.IsNullOrEmpty(fileMap.MachineConfigFilename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(fileMap.MachineConfigFilename)); ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap; if (exeFileMap != null) { switch (userLevel) { case ConfigurationUserLevel.None: if (string.IsNullOrEmpty(exeFileMap.ExeConfigFilename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(exeFileMap.ExeConfigFilename)); break; case ConfigurationUserLevel.PerUserRoaming: if (string.IsNullOrEmpty(exeFileMap.RoamingUserConfigFilename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(exeFileMap.RoamingUserConfigFilename)); goto case ConfigurationUserLevel.None; case ConfigurationUserLevel.PerUserRoamingAndLocal: if (string.IsNullOrEmpty(exeFileMap.LocalUserConfigFilename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(exeFileMap.LocalUserConfigFilename)); goto case ConfigurationUserLevel.PerUserRoaming; } } } string configPath = null; if (isMachine) configPath = MachineConfigPath; else { switch (userLevel) { case ConfigurationUserLevel.None: configPath = ExeConfigPath; break; case ConfigurationUserLevel.PerUserRoaming: configPath = RoamingUserConfigPath; break; case ConfigurationUserLevel.PerUserRoamingAndLocal: configPath = LocalUserConfigPath; break; } } Configuration configuration = new Configuration(null, typeof(ClientConfigurationHost), fileMap, exePath, configPath); return configuration; } } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2013 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections.Generic; using System.Text; namespace BerkeleyDB { /// <summary> /// Statistical information about the locking subsystem /// </summary> public class LockStats { private Internal.LockStatStruct st; internal LockStats(Internal.LockStatStruct stats) { st = stats; } /// <summary> /// Current number of lockers allocated. /// </summary> public uint AllocatedLockers { get { return st.st_lockers; } } /// <summary> /// Current number of locks allocated. /// </summary> public uint AllocatedLocks { get { return st.st_locks; } } /// <summary> /// Current number of lock objects allocated. /// </summary> public uint AllocatedObjects { get { return st.st_objects; } } /// <summary> /// Initial number of locks allocated. /// </summary> public uint InitLocks { get { return st.st_initlocks; } } /// <summary> /// Initial number of lockers allocated. /// </summary> public uint InitLockers { get { return st.st_initlockers; } } /// <summary> /// Initial number of lock objects allocated. /// </summary> public uint InitObjects { get { return st.st_initobjects; } } /// <summary> /// Last allocated locker ID. /// </summary> public uint LastAllocatedLockerID { get { return st.st_id; } } /// <summary> /// Lock conflicts w/ subsequent wait /// </summary> public ulong LockConflictsWait { get { return st.st_lock_wait; } } /// <summary> /// Lock conflicts w/o subsequent wait /// </summary> public ulong LockConflictsNoWait { get { return st.st_lock_nowait; } } /// <summary> /// Number of lock deadlocks. /// </summary> public ulong LockDeadlocks { get { return st.st_ndeadlocks; } } /// <summary> /// Number of lock downgrades. /// </summary> public ulong LockDowngrades { get { return st.st_ndowngrade; } } /// <summary> /// Number of lock modes. /// </summary> public int LockModes { get { return st.st_nmodes; } } /// <summary> /// Number of lock puts. /// </summary> public ulong LockPuts { get { return st.st_nreleases; } } /// <summary> /// Number of lock gets. /// </summary> public ulong LockRequests { get { return st.st_nrequests; } } /// <summary> /// Number of lock steals so far. /// </summary> public ulong LockSteals { get { return st.st_locksteals; } } /// <summary> /// Lock timeout. /// </summary> public uint LockTimeoutLength { get { return st.st_locktimeout; } } /// <summary> /// Number of lock timeouts. /// </summary> public ulong LockTimeouts { get { return st.st_nlocktimeouts; } } /// <summary> /// Number of lock upgrades. /// </summary> public ulong LockUpgrades { get { return st.st_nupgrade; } } /// <summary> /// Locker lock granted without wait. /// </summary> public ulong LockerNoWait { get { return st.st_lockers_nowait; } } /// <summary> /// Locker lock granted after wait. /// </summary> public ulong LockerWait { get { return st.st_lockers_wait; } } /// <summary> /// Current number of lockers. /// </summary> public uint Lockers { get { return st.st_nlockers; } } /// <summary> /// Current number of locks. /// </summary> public uint Locks { get { return st.st_nlocks; } } /// <summary> /// Max length of bucket. /// </summary> public uint MaxBucketLength { get { return st.st_hash_len; } } /// <summary> /// Maximum number steals in any partition. /// </summary> public ulong MaxLockSteals { get { return st.st_maxlsteals; } } /// <summary> /// Maximum number of lockers so far. /// </summary> public uint MaxLockers { get { return st.st_maxnlockers; } } /// <summary> /// Maximum num of lockers in table. /// </summary> public uint MaxLockersInTable { get { return st.st_maxlockers; } } /// <summary> /// Maximum number of locks so far. /// </summary> public uint MaxLocks { get { return st.st_maxnlocks; } } /// <summary> /// Maximum number of locks in any bucket. /// </summary> public uint MaxLocksInBucket { get { return st.st_maxhlocks; } } /// <summary> /// Maximum number of locks in table. /// </summary> public uint MaxLocksInTable { get { return st.st_maxlocks; } } /// <summary> /// Maximum number of steals in any partition. /// </summary> public ulong MaxObjectSteals { get { return st.st_maxosteals; } } /// <summary> /// Maximum number of objects so far. /// </summary> public uint MaxObjects { get { return st.st_maxnobjects; } } /// <summary> /// Maximum number of objectsin any bucket. /// </summary> public uint MaxObjectsInBucket { get { return st.st_maxhobjects; } } /// <summary> /// Max partition lock granted without wait. /// </summary> public ulong MaxPartitionLockNoWait { get { return st.st_part_max_nowait; } } /// <summary> /// Max partition lock granted after wait. /// </summary> public ulong MaxPartitionLockWait { get { return st.st_part_max_wait; } } /// <summary> /// Current maximum unused ID. /// </summary> public uint MaxUnusedID { get { return st.st_cur_maxid; } } /// <summary> /// Maximum num of objects in table. /// </summary> public uint MaxObjectsInTable { get { return st.st_maxobjects; } } /// <summary> /// number of partitions. /// </summary> public uint nPartitions { get { return st.st_partitions; } } /// <summary> /// Object lock granted without wait. /// </summary> public ulong ObjectNoWait { get { return st.st_objs_nowait; } } /// <summary> /// Number of objects steals so far. /// </summary> public ulong ObjectSteals { get { return st.st_objectsteals; } } /// <summary> /// Object lock granted after wait. /// </summary> public ulong ObjectWait { get { return st.st_objs_wait; } } /// <summary> /// Current number of objects. /// </summary> public uint Objects { get { return st.st_nobjects; } } /// <summary> /// Partition lock granted without wait. /// </summary> public ulong PartitionLockNoWait { get { return st.st_part_nowait; } } /// <summary> /// Partition lock granted after wait. /// </summary> public ulong PartitionLockWait { get { return st.st_part_wait; } } /// <summary> /// Region lock granted without wait. /// </summary> public ulong RegionNoWait { get { return st.st_region_nowait; } } /// <summary> /// Region size. /// </summary> public ulong RegionSize { get { return (ulong)st.st_regsize.ToInt64(); } } /// <summary> /// Region lock granted after wait. /// </summary> public ulong RegionWait { get { return st.st_region_wait; } } /// <summary> /// Size of object hash table. /// </summary> public uint TableSize { get { return st.st_tablesize; } } /// <summary> /// Transaction timeout. /// </summary> public uint TxnTimeoutLength { get { return st.st_txntimeout; } } /// <summary> /// Number of transaction timeouts. /// </summary> public ulong TxnTimeouts { get { return st.st_ntxntimeouts; } } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 ServiceStack, Inc. All Rights Reserved. // // Licensed under the same terms of ServiceStack. // using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace ServiceStack.Text.Common { public static class DeserializeType<TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); internal static ParseStringDelegate GetParseMethod(TypeConfig typeConfig) => v => GetParseStringSpanMethod(typeConfig)(v.AsSpan()); internal static ParseStringSpanDelegate GetParseStringSpanMethod(TypeConfig typeConfig) { var type = typeConfig.Type; if (!type.IsStandardClass()) return null; var accessors = DeserializeTypeRef.GetTypeAccessors(typeConfig, Serializer); var ctorFn = JsConfig.ModelFactory(type); if (accessors == null) return value => ctorFn(); if (typeof(TSerializer) == typeof(Json.JsonTypeSerializer)) return new StringToTypeContext(typeConfig, ctorFn, accessors).DeserializeJson; return new StringToTypeContext(typeConfig, ctorFn, accessors).DeserializeJsv; } internal struct StringToTypeContext { private readonly TypeConfig typeConfig; private readonly EmptyCtorDelegate ctorFn; private readonly KeyValuePair<string, TypeAccessor>[] accessors; public StringToTypeContext(TypeConfig typeConfig, EmptyCtorDelegate ctorFn, KeyValuePair<string, TypeAccessor>[] accessors) { this.typeConfig = typeConfig; this.ctorFn = ctorFn; this.accessors = accessors; } internal object DeserializeJson(ReadOnlySpan<char> value) => DeserializeTypeRefJson.StringToType(value, typeConfig, ctorFn, accessors); internal object DeserializeJsv(ReadOnlySpan<char> value) => DeserializeTypeRefJsv.StringToType(value, typeConfig, ctorFn, accessors); } public static object ObjectStringToType(ReadOnlySpan<char> strType) { var type = ExtractType(strType); if (type != null) { var parseFn = Serializer.GetParseStringSpanFn(type); var propertyValue = parseFn(strType); return propertyValue; } var config = JsConfig.GetConfig(); if (config.ConvertObjectTypesIntoStringDictionary && !strType.IsNullOrEmpty()) { if (strType[0] == JsWriter.MapStartChar) { var dynamicMatch = DeserializeDictionary<TSerializer>.ParseDictionary<string, object>(strType, null, v => Serializer.UnescapeString(v).ToString(), v => Serializer.UnescapeString(v).ToString()); if (dynamicMatch != null && dynamicMatch.Count > 0) { return dynamicMatch; } } if (strType[0] == JsWriter.ListStartChar) { return DeserializeList<List<object>, TSerializer>.ParseStringSpan(strType); } } var primitiveType = config.TryToParsePrimitiveTypeValues ? ParsePrimitive(strType) : null; if (primitiveType != null) return primitiveType; if (Serializer.ObjectDeserializer != null && typeof(TSerializer) == typeof(Json.JsonTypeSerializer)) return Serializer.ObjectDeserializer(strType); return Serializer.UnescapeString(strType).Value(); } public static Type ExtractType(string strType) => ExtractType(strType.AsSpan()); //TODO: optimize ExtractType public static Type ExtractType(ReadOnlySpan<char> strType) { if (strType.IsEmpty || strType.Length <= 1) return null; var hasWhitespace = Json.JsonUtils.WhiteSpaceChars.Contains(strType[1]); if (hasWhitespace) { var pos = strType.IndexOf('"'); if (pos >= 0) strType = ("{" + strType.Substring(pos, strType.Length - pos)).AsSpan(); } var typeAttrInObject = Serializer.TypeAttrInObject; if (strType.Length > typeAttrInObject.Length && strType.Slice(0, typeAttrInObject.Length).EqualsOrdinal(typeAttrInObject)) { var propIndex = typeAttrInObject.Length; var typeName = Serializer.UnescapeSafeString(Serializer.EatValue(strType, ref propIndex)).ToString(); var type = JsConfig.TypeFinder(typeName); JsWriter.AssertAllowedRuntimeType(type); if (type == null) { Tracer.Instance.WriteWarning("Could not find type: " + typeName); return null; } return ReflectionOptimizer.Instance.UseType(type); } return null; } public static object ParseAbstractType<T>(ReadOnlySpan<char> value) { if (typeof(T).IsAbstract) { if (value.IsNullOrEmpty()) return null; var concreteType = ExtractType(value); if (concreteType != null) { var fn = Serializer.GetParseStringSpanFn(concreteType); if (fn == ParseAbstractType<T>) return null; var ret = fn(value); return ret; } Tracer.Instance.WriteWarning( "Could not deserialize Abstract Type with unknown concrete type: " + typeof(T).FullName); } return null; } public static object ParseQuotedPrimitive(string value) { var config = JsConfig.GetConfig(); var fn = config.ParsePrimitiveFn; var result = fn?.Invoke(value); if (result != null) return result; if (string.IsNullOrEmpty(value)) return null; if (Guid.TryParse(value, out Guid guidValue)) return guidValue; if (value.StartsWith(DateTimeSerializer.EscapedWcfJsonPrefix, StringComparison.Ordinal) || value.StartsWith(DateTimeSerializer.WcfJsonPrefix, StringComparison.Ordinal)) return DateTimeSerializer.ParseWcfJsonDate(value); if (JsConfig.DateHandler == DateHandler.ISO8601) { // check that we have UTC ISO8601 date: // YYYY-MM-DDThh:mm:ssZ // YYYY-MM-DDThh:mm:ss+02:00 // YYYY-MM-DDThh:mm:ss-02:00 if (value.Length > 14 && value[10] == 'T' && (value.EndsWithInvariant("Z") || value[value.Length - 6] == '+' || value[value.Length - 6] == '-')) { return DateTimeSerializer.ParseShortestXsdDateTime(value); } } if (config.DateHandler == DateHandler.RFC1123) { // check that we have RFC1123 date: // ddd, dd MMM yyyy HH:mm:ss GMT if (value.Length == 29 && (value.EndsWithInvariant("GMT"))) { return DateTimeSerializer.ParseRFC1123DateTime(value); } } return Serializer.UnescapeString(value); } public static object ParsePrimitive(string value) => ParsePrimitive(value.AsSpan()); public static object ParsePrimitive(ReadOnlySpan<char> value) { var fn = JsConfig.ParsePrimitiveFn; var result = fn?.Invoke(value.ToString()); if (result != null) return result; if (value.IsNullOrEmpty()) return null; if (value.TryParseBoolean(out bool boolValue)) return boolValue; return value.ParseNumber(); } internal static object ParsePrimitive(string value, char firstChar) { if (typeof(TSerializer) == typeof(Json.JsonTypeSerializer)) { return firstChar == JsWriter.QuoteChar ? ParseQuotedPrimitive(value) : ParsePrimitive(value); } return (ParsePrimitive(value) ?? ParseQuotedPrimitive(value)); } } internal static class TypeAccessorUtils { internal static TypeAccessor Get(this KeyValuePair<string, TypeAccessor>[] accessors, ReadOnlySpan<char> propertyName, bool lenient) { var testValue = FindPropertyAccessor(accessors, propertyName); if (testValue != null) return testValue; if (lenient) return FindPropertyAccessor(accessors, propertyName.ToString().Replace("-", string.Empty).Replace("_", string.Empty).AsSpan()); return null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] //Binary Search private static TypeAccessor FindPropertyAccessor(KeyValuePair<string, TypeAccessor>[] accessors, ReadOnlySpan<char> propertyName) { var lo = 0; var hi = accessors.Length - 1; var mid = (lo + hi + 1) / 2; while (lo <= hi) { var test = accessors[mid]; var cmp = propertyName.CompareTo(test.Key.AsSpan(), StringComparison.OrdinalIgnoreCase); if (cmp == 0) return test.Value; if (cmp < 0) hi = mid - 1; else lo = mid + 1; mid = (lo + hi + 1) / 2; } return null; } } internal class TypeAccessor { internal ParseStringSpanDelegate GetProperty; internal SetMemberDelegate SetProperty; internal Type PropertyType; public static Type ExtractType(ITypeSerializer Serializer, string strType) => ExtractType(Serializer, strType.AsSpan()); public static Type ExtractType(ITypeSerializer Serializer, ReadOnlySpan<char> strType) { if (strType.IsEmpty || strType.Length <= 1) return null; var hasWhitespace = Json.JsonUtils.WhiteSpaceChars.Contains(strType[1]); if (hasWhitespace) { var pos = strType.IndexOf('"'); if (pos >= 0) strType = ("{" + strType.Substring(pos)).AsSpan(); } var typeAttrInObject = Serializer.TypeAttrInObject; if (strType.Length > typeAttrInObject.Length && strType.Slice(0, typeAttrInObject.Length).EqualsOrdinal(typeAttrInObject)) { var propIndex = typeAttrInObject.Length; var typeName = Serializer.EatValue(strType, ref propIndex).ToString(); var type = JsConfig.TypeFinder(typeName); if (type == null) Tracer.Instance.WriteWarning("Could not find type: " + typeName); return type; } return null; } public static TypeAccessor Create(ITypeSerializer serializer, TypeConfig typeConfig, PropertyInfo propertyInfo) { return new TypeAccessor { PropertyType = propertyInfo.PropertyType, GetProperty = GetPropertyMethod(serializer, propertyInfo), SetProperty = GetSetPropertyMethod(typeConfig, propertyInfo), }; } internal static ParseStringSpanDelegate GetPropertyMethod(ITypeSerializer serializer, PropertyInfo propertyInfo) { var getPropertyFn = serializer.GetParseStringSpanFn(propertyInfo.PropertyType); if (propertyInfo.PropertyType == typeof(object) || propertyInfo.PropertyType.HasInterface(typeof(IEnumerable<object>))) { var declaringTypeNamespace = propertyInfo.DeclaringType?.Namespace; if (declaringTypeNamespace == null || (!JsConfig.AllowRuntimeTypeInTypesWithNamespaces.Contains(declaringTypeNamespace) && !JsConfig.AllowRuntimeTypeInTypes.Contains(propertyInfo.DeclaringType.FullName))) { return value => { var hold = JsState.IsRuntimeType; try { JsState.IsRuntimeType = true; return getPropertyFn(value); } finally { JsState.IsRuntimeType = hold; } }; } } return getPropertyFn; } private static SetMemberDelegate GetSetPropertyMethod(TypeConfig typeConfig, PropertyInfo propertyInfo) { if (typeConfig.Type != propertyInfo.DeclaringType) propertyInfo = propertyInfo.DeclaringType.GetProperty(propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (!propertyInfo.CanWrite && !typeConfig.EnableAnonymousFieldSetters) return null; FieldInfo fieldInfo = null; if (!propertyInfo.CanWrite) { var fieldNameFormat = Env.IsMono ? "<{0}>" : "<{0}>i__Field"; var fieldName = string.Format(fieldNameFormat, propertyInfo.Name); var fieldInfos = typeConfig.Type.GetWritableFields(); foreach (var f in fieldInfos) { if (f.IsInitOnly && f.FieldType == propertyInfo.PropertyType && f.Name.EqualsIgnoreCase(fieldName)) { fieldInfo = f; break; } } if (fieldInfo == null) return null; } return propertyInfo.CanWrite ? ReflectionOptimizer.Instance.CreateSetter(propertyInfo) : ReflectionOptimizer.Instance.CreateSetter(fieldInfo); } public static TypeAccessor Create(ITypeSerializer serializer, TypeConfig typeConfig, FieldInfo fieldInfo) { return new TypeAccessor { PropertyType = fieldInfo.FieldType, GetProperty = serializer.GetParseStringSpanFn(fieldInfo.FieldType), SetProperty = GetSetFieldMethod(typeConfig, fieldInfo), }; } private static SetMemberDelegate GetSetFieldMethod(TypeConfig typeConfig, FieldInfo fieldInfo) { if (typeConfig.Type != fieldInfo.DeclaringType) fieldInfo = fieldInfo.DeclaringType.GetField(fieldInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return ReflectionOptimizer.Instance.CreateSetter(fieldInfo); } } public static class DeserializeTypeExensions { public static bool Has(this ParseAsType flags, ParseAsType flag) { return (flag & flags) != 0; } public static object ParseNumber(this ReadOnlySpan<char> value) => ParseNumber(value, JsConfig.TryParseIntoBestFit); public static object ParseNumber(this ReadOnlySpan<char> value, bool bestFit) { if (value.Length == 1) { int singleDigit = value[0]; if (singleDigit >= 48 || singleDigit <= 57) // 0 - 9 { var result = singleDigit - 48; if (bestFit) return (byte) result; return result; } } var config = JsConfig.GetConfig(); // Parse as decimal var acceptDecimal = config.ParsePrimitiveFloatingPointTypes.Has(ParseAsType.Decimal); var isDecimal = value.TryParseDecimal(out decimal decimalValue); // Check if the number is an Primitive Integer type given that we have a decimal if (isDecimal && decimalValue == decimal.Truncate(decimalValue)) { // Value is a whole number var parseAs = config.ParsePrimitiveIntegerTypes; if (parseAs.Has(ParseAsType.Byte) && decimalValue <= byte.MaxValue && decimalValue >= byte.MinValue) return (byte)decimalValue; if (parseAs.Has(ParseAsType.SByte) && decimalValue <= sbyte.MaxValue && decimalValue >= sbyte.MinValue) return (sbyte)decimalValue; if (parseAs.Has(ParseAsType.Int16) && decimalValue <= Int16.MaxValue && decimalValue >= Int16.MinValue) return (Int16)decimalValue; if (parseAs.Has(ParseAsType.UInt16) && decimalValue <= UInt16.MaxValue && decimalValue >= UInt16.MinValue) return (UInt16)decimalValue; if (parseAs.Has(ParseAsType.Int32) && decimalValue <= Int32.MaxValue && decimalValue >= Int32.MinValue) return (Int32)decimalValue; if (parseAs.Has(ParseAsType.UInt32) && decimalValue <= UInt32.MaxValue && decimalValue >= UInt32.MinValue) return (UInt32)decimalValue; if (parseAs.Has(ParseAsType.Int64) && decimalValue <= Int64.MaxValue && decimalValue >= Int64.MinValue) return (Int64)decimalValue; if (parseAs.Has(ParseAsType.UInt64) && decimalValue <= UInt64.MaxValue && decimalValue >= UInt64.MinValue) return (UInt64)decimalValue; return decimalValue; } // Value is a floating point number // Return a decimal if the user accepts a decimal if (isDecimal && acceptDecimal) return decimalValue; var acceptFloat = config.ParsePrimitiveFloatingPointTypes.HasFlag(ParseAsType.Single); var isFloat = value.TryParseFloat(out float floatValue); if (acceptFloat && isFloat) return floatValue; var acceptDouble = config.ParsePrimitiveFloatingPointTypes.HasFlag(ParseAsType.Double); var isDouble = value.TryParseDouble(out double doubleValue); if (acceptDouble && isDouble) return doubleValue; if (isDecimal) return decimalValue; if (isFloat) return floatValue; if (isDouble) return doubleValue; return null; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; 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 LocationApplication.Areas.HelpPage.ModelDescriptions; using LocationApplication.Areas.HelpPage.Models; namespace LocationApplication.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; } if (complexTypeDescription != null) { 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 ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//------------------------------------------------------------------------------ // <copyright file="Parameter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Globalization; /// <devdoc> /// Represents a parameter to a DataSourceControl. /// Parameters can be session variables, web request parameters, or of custom types. /// </devdoc> [ DefaultProperty("DefaultValue"), ] public class Parameter : ICloneable, IStateManager { private ParameterCollection _owner; private bool _tracking; private StateBag _viewState; /// <devdoc> /// Creates an instance of the Parameter class. /// </devdoc> public Parameter() { } /// <devdoc> /// Creates an instance of the Parameter class with the specified parameter name. /// </devdoc> public Parameter(string name) { Name = name; } /// <devdoc> /// Creates an instance of the Parameter class with the specified parameter name and db type. /// </devdoc> public Parameter(string name, DbType dbType) { Name = name; DbType = dbType; } /// <devdoc> /// Creates an instance of the Parameter class with the specified parameter name, db type, and default value. /// </devdoc> public Parameter(string name, DbType dbType, string defaultValue) { Name = name; DbType = dbType; DefaultValue = defaultValue; } /// <devdoc> /// Creates an instance of the Parameter class with the specified parameter name and type. /// </devdoc> public Parameter(string name, TypeCode type) { Name = name; Type = type; } /// <devdoc> /// Creates an instance of the Parameter class with the specified parameter name, type, and default value. /// </devdoc> public Parameter(string name, TypeCode type, string defaultValue) { Name = name; Type = type; DefaultValue = defaultValue; } /// <devdoc> /// Used to clone a parameter. /// </devdoc> protected Parameter(Parameter original) { DefaultValue = original.DefaultValue; Direction = original.Direction; Name = original.Name; ConvertEmptyStringToNull = original.ConvertEmptyStringToNull; Size = original.Size; Type = original.Type; DbType = original.DbType; } /// <devdoc> /// Indicates whether the Parameter is tracking view state. /// </devdoc> protected bool IsTrackingViewState { get { return _tracking; } } /// <devdoc> /// Gets/sets the db type of the parameter's value. /// When DbType is DbType.Object, the Type property will be used instead /// </devdoc> [ DefaultValue(DbType.Object), WebCategory("Parameter"), WebSysDescription(SR.Parameter_DbType), ] public DbType DbType { get { object o = ViewState["DbType"]; if (o == null) return DbType.Object; return (DbType)o; } set { if (value < DbType.AnsiString || value > DbType.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } if (DbType != value) { ViewState["DbType"] = value; OnParameterChanged(); } } } /// <devdoc> /// The default value to use in GetValue() if it cannot obtain a value. /// </devdoc> [ DefaultValue(null), WebCategory("Parameter"), WebSysDescription(SR.Parameter_DefaultValue), ] public string DefaultValue { get { object o = ViewState["DefaultValue"]; return (o as string); } set { if (DefaultValue != value) { ViewState["DefaultValue"] = value; OnParameterChanged(); } } } /// <devdoc> /// Gets/sets the direction of the parameter. /// </devdoc> [ DefaultValue(ParameterDirection.Input), WebCategory("Parameter"), WebSysDescription(SR.Parameter_Direction), ] public ParameterDirection Direction { get { object o = ViewState["Direction"]; if (o == null) return ParameterDirection.Input; return (ParameterDirection)o; } set { if (Direction != value) { ViewState["Direction"] = value; OnParameterChanged(); } } } /// <devdoc> /// Gets/sets the name of the parameter. /// </devdoc> [ DefaultValue(""), WebCategory("Parameter"), WebSysDescription(SR.Parameter_Name), ] public string Name { get { object o = ViewState["Name"]; if (o == null) return String.Empty; return (string)o; } set { if (Name != value) { ViewState["Name"] = value; OnParameterChanged(); } } } /// <devdoc> /// Returns the value of parameter after converting it to the proper type. /// </devdoc> [ Browsable(false), ] internal object ParameterValue { get { return GetValue(ViewState["ParameterValue"], false); } } public DbType GetDatabaseType() { DbType dbType = DbType; if (dbType == DbType.Object) { return ConvertTypeCodeToDbType(Type); } if (Type != TypeCode.Empty) { throw new InvalidOperationException(SR.GetString(SR.Parameter_TypeNotSupported, Name)); } return dbType; } internal object GetValue(object value, bool ignoreNullableTypeChanges) { DbType dbType = DbType; if (dbType == DbType.Object) { return GetValue(value, DefaultValue, Type, ConvertEmptyStringToNull, ignoreNullableTypeChanges); } if (Type != TypeCode.Empty) { throw new InvalidOperationException(SR.GetString(SR.Parameter_TypeNotSupported, Name)); } return GetValue(value, DefaultValue, dbType, ConvertEmptyStringToNull, ignoreNullableTypeChanges); } internal static object GetValue(object value, string defaultValue, DbType dbType, bool convertEmptyStringToNull, bool ignoreNullableTypeChanges) { // use the TypeCode conversion logic for Whidbey types. if ((dbType != DbType.DateTimeOffset) && (dbType != DbType.Time) && (dbType != DbType.Guid)) { TypeCode type = ConvertDbTypeToTypeCode(dbType); return GetValue(value, defaultValue, type, convertEmptyStringToNull, ignoreNullableTypeChanges); } value = HandleNullValue(value, defaultValue, convertEmptyStringToNull); if (value == null) { return null; } // For ObjectDataSource we special-case Nullable<T> and do nothing because these // types will get converted when we actually call the method. if (ignoreNullableTypeChanges && IsNullableType(value.GetType())) { return value; } if (dbType == DbType.DateTimeOffset) { if (value is DateTimeOffset) { return value; } return DateTimeOffset.Parse(value.ToString(), CultureInfo.CurrentCulture); } else if (dbType == DbType.Time) { if (value is TimeSpan) { return value; } return TimeSpan.Parse(value.ToString(), CultureInfo.CurrentCulture); } else if (dbType == DbType.Guid) { if (value is Guid) { return value; } return new Guid(value.ToString()); } Debug.Fail("Should never reach this point."); return null; } internal static object GetValue(object value, string defaultValue, TypeCode type, bool convertEmptyStringToNull, bool ignoreNullableTypeChanges) { // Convert.ChangeType() throws if you attempt to convert to DBNull, so we have to special case it. if (type == TypeCode.DBNull) { return DBNull.Value; } value = HandleNullValue(value, defaultValue, convertEmptyStringToNull); if (value == null) { return null; } if (type == TypeCode.Object || type == TypeCode.Empty) { return value; } // For ObjectDataSource we special-case Nullable<T> and do nothing because these // types will get converted when we actually call the method. if (ignoreNullableTypeChanges && IsNullableType(value.GetType())) { return value; } return value = Convert.ChangeType(value, type, CultureInfo.CurrentCulture);; } private static object HandleNullValue(object value, string defaultValue, bool convertEmptyStringToNull) { // Get the value and convert it to the default value if it is null if (convertEmptyStringToNull) { string stringValue = value as string; if ((stringValue != null) && (stringValue.Length == 0)) { value = null; } } if (value == null) { // Attempt to use the default value, but if it is null too, just return null immediately if (convertEmptyStringToNull && String.IsNullOrEmpty(defaultValue)) { defaultValue = null; } if (defaultValue == null) { return null; } value = defaultValue; } return value; } private static bool IsNullableType(Type type) { return type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)); } /// <devdoc> /// Gets/sets the size of the parameter. /// </devdoc> [ DefaultValue(0), WebCategory("Parameter"), WebSysDescription(SR.Parameter_Size), ] public int Size { get { object o = ViewState["Size"]; if (o == null) return 0; return (int)o; } set { if (Size != value) { ViewState["Size"] = value; OnParameterChanged(); } } } /// <devdoc> /// Gets/sets the type of the parameter's value. /// </devdoc> [ DefaultValue(TypeCode.Empty), WebCategory("Parameter"), WebSysDescription(SR.Parameter_Type), ] public TypeCode Type { get { object o = ViewState["Type"]; if (o == null) return TypeCode.Empty; return (TypeCode)o; } set { if (value < TypeCode.Empty || value > TypeCode.String) { throw new ArgumentOutOfRangeException("value"); } if (Type != value) { ViewState["Type"] = value; OnParameterChanged(); } } } /// <devdoc> /// Gets/sets whether an empty string should be treated as a null value. If this property is set to true /// and the value is an empty string, the default value will be used. /// </devdoc> [ DefaultValue(true), WebCategory("Parameter"), WebSysDescription(SR.Parameter_ConvertEmptyStringToNull), ] public bool ConvertEmptyStringToNull { get { object o = ViewState["ConvertEmptyStringToNull"]; if (o == null) return true; return (bool)o; } set { if (ConvertEmptyStringToNull != value) { ViewState["ConvertEmptyStringToNull"] = value; OnParameterChanged(); } } } /// <devdoc> /// Indicates a dictionary of state information that allows you to save and restore /// the state of a Parameter across multiple requests for the same page. /// </devdoc> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] protected StateBag ViewState { get { if (_viewState == null) { _viewState = new StateBag(); if (_tracking) _viewState.TrackViewState(); } return _viewState; } } /// <devdoc> /// Creates a new Parameter that is a copy of this Parameter. /// </devdoc> protected virtual Parameter Clone() { return new Parameter(this); } public static TypeCode ConvertDbTypeToTypeCode(DbType dbType) { switch (dbType) { case DbType.AnsiString: case DbType.AnsiStringFixedLength: case DbType.String: case DbType.StringFixedLength: return TypeCode.String; case DbType.Boolean: return TypeCode.Boolean; case DbType.Byte: return TypeCode.Byte; case DbType.VarNumeric: // ??? case DbType.Currency: case DbType.Decimal: return TypeCode.Decimal; case DbType.Date: case DbType.DateTime: case DbType.DateTime2: // new Katmai type case DbType.Time: // new Katmai type - no TypeCode for TimeSpan return TypeCode.DateTime; case DbType.Double: return TypeCode.Double; case DbType.Int16: return TypeCode.Int16; case DbType.Int32: return TypeCode.Int32; case DbType.Int64: return TypeCode.Int64; case DbType.SByte: return TypeCode.SByte; case DbType.Single: return TypeCode.Single; case DbType.UInt16: return TypeCode.UInt16; case DbType.UInt32: return TypeCode.UInt32; case DbType.UInt64: return TypeCode.UInt64; case DbType.Guid: // ??? case DbType.Binary: case DbType.Object: case DbType.DateTimeOffset: // new Katmai type - no TypeCode for DateTimeOffset default: return TypeCode.Object; } } public static DbType ConvertTypeCodeToDbType(TypeCode typeCode) { // no TypeCode equivalent for TimeSpan or DateTimeOffset switch (typeCode) { case TypeCode.Boolean: return DbType.Boolean; case TypeCode.Byte: return DbType.Byte; case TypeCode.Char: return DbType.StringFixedLength; // ??? case TypeCode.DateTime: // Used for Date, DateTime and DateTime2 DbTypes return DbType.DateTime; case TypeCode.Decimal: return DbType.Decimal; case TypeCode.Double: return DbType.Double; case TypeCode.Int16: return DbType.Int16; case TypeCode.Int32: return DbType.Int32; case TypeCode.Int64: return DbType.Int64; case TypeCode.SByte: return DbType.SByte; case TypeCode.Single: return DbType.Single; case TypeCode.String: return DbType.String; case TypeCode.UInt16: return DbType.UInt16; case TypeCode.UInt32: return DbType.UInt32; case TypeCode.UInt64: return DbType.UInt64; case TypeCode.DBNull: case TypeCode.Empty: case TypeCode.Object: default: return DbType.Object; } } /// <devdoc> /// Evaluates the parameter and returns the new value. /// The control parameter is used to access the page's framework. /// By default it returns the null, implying that the DefaultValue will /// be the value. /// </devdoc> protected internal virtual object Evaluate(HttpContext context, Control control) { return null; } /// <devdoc> /// Loads view state. /// </devdoc> protected virtual void LoadViewState(object savedState) { if (savedState != null) { ViewState.LoadViewState(savedState); } } /// <devdoc> /// Raises the ParameterChanged event. This notifies a listener that it should re-evaluate the value. /// </devdoc> protected void OnParameterChanged() { if (_owner != null) { _owner.CallOnParametersChanged(); } } /// <devdoc> /// Saves view state. /// </devdoc> protected virtual object SaveViewState() { return (_viewState != null) ? _viewState.SaveViewState() : null; } /// <devdoc> /// Tells the Parameter to record its entire state into view state. /// </devdoc> protected internal virtual void SetDirty() { ViewState.SetDirty(true); } /// <devdoc> /// Tells the Parameter the collection it belongs to /// </devdoc> internal void SetOwner(ParameterCollection owner) { _owner = owner; } /// <devdoc> /// Converts the Parameter to a string value. /// </devdoc> public override string ToString() { return this.Name; } /// <devdoc> /// Tells the Parameter to start tracking property changes. /// </devdoc> protected virtual void TrackViewState() { _tracking = true; if (_viewState != null) { _viewState.TrackViewState(); } } /// <devdoc> /// Updates the value of parameter. /// If the value changed, this will raise the ParametersChanged event of the ParameterCollection it belongs to. /// The control parameter is used to access the page's framework. /// </devdoc> internal void UpdateValue(HttpContext context, Control control) { object oldValue = ViewState["ParameterValue"]; object newValue = Evaluate(context, control); ViewState["ParameterValue"] = newValue; // If you have chains of dependency, like one control with a control parameter on another, and then a third with a control // parameter on the second, the order in which the evaluations take place is non-deterministic and may create incorrect // evaluation of parameters because all our evaluation happens during LoadComplete. The correct solution is to call DataBind // on the third control when the second control's selected value changes. Hacky, but we don't support specifying dependency // chains on data sources. if ((newValue == null && oldValue != null) || (newValue != null && !newValue.Equals(oldValue))) { OnParameterChanged(); } } #region Implementation of ICloneable /// <internalonly/> object ICloneable.Clone() { return Clone(); } #endregion #region Implementation of IStateManager /// <internalonly/> bool IStateManager.IsTrackingViewState { get { return IsTrackingViewState; } } /// <internalonly/> void IStateManager.LoadViewState(object savedState) { LoadViewState(savedState); } /// <internalonly/> object IStateManager.SaveViewState() { return SaveViewState(); } /// <internalonly/> void IStateManager.TrackViewState() { TrackViewState(); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; namespace System.Text.RegularExpressions { public delegate string MatchEvaluator(Match match); public enum RegexOptions { #if !SILVERLIGHT Compiled = 8, #endif CultureInvariant = 0x200, ECMAScript = 0x100, ExplicitCapture = 4, IgnoreCase = 1, IgnorePatternWhitespace = 0x20, Multiline = 2, None = 0, RightToLeft = 0x40, Singleline = 0x10 } public class Regex { extern public RegexOptions Options { get; } extern public bool RightToLeft { get; } #if false public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes, string resourceFile) { } public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes) { } public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname) { } #endif public String[] Split(string input, int count, int startat) { Contract.Requires(input != null); Contract.Ensures(Contract.Result<String[]>() != null); return default(String[]); } public String[] Split(string input, int count) { Contract.Requires(input != null); Contract.Ensures(Contract.Result<String[]>() != null); return default(String[]); } public String[] Split(string input) { Contract.Requires(input != null); Contract.Ensures(Contract.Result<String[]>() != null); return default(String[]); } public static String[] Split(string input, string pattern, RegexOptions options) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Ensures(Contract.Result<String[]>() != null); return default(String[]); } public static String[] Split(string input, string pattern) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Ensures(Contract.Result<String[]>() != null); return default(String[]); } public string Replace(string input, MatchEvaluator evaluator, int count, int startat) { Contract.Requires(input != null); Contract.Requires(evaluator != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public string Replace(string input, MatchEvaluator evaluator, int count) { Contract.Requires(input != null); Contract.Requires(evaluator != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public string Replace(string input, MatchEvaluator evaluator) { Contract.Requires(input != null); Contract.Requires(evaluator != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public static string Replace(string input, string pattern, MatchEvaluator evaluator, RegexOptions options) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Requires(evaluator != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public static string Replace(string input, string pattern, MatchEvaluator evaluator) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Requires(evaluator != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public string Replace(string input, string replacement, int count, int startat) { Contract.Requires(input != null); Contract.Requires(replacement != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public string Replace(string input, string replacement, int count) { Contract.Requires(input != null); Contract.Requires(replacement != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public string Replace(string input, string replacement) { Contract.Requires(input != null); Contract.Requires(replacement != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public static string Replace(string input, string pattern, string replacement, RegexOptions options) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Requires(replacement != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public static string Replace(string input, string pattern, string replacement) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Requires(replacement != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public MatchCollection Matches(string input, int startat) { Contract.Requires(input != null); Contract.Ensures(Contract.Result<MatchCollection>() != null); return default(MatchCollection); } public MatchCollection Matches(string input) { Contract.Requires(input != null); Contract.Ensures(Contract.Result<MatchCollection>() != null); return default(MatchCollection); } public static MatchCollection Matches(string input, string pattern, RegexOptions options) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Ensures(Contract.Result<MatchCollection>() != null); return default(MatchCollection); } public static MatchCollection Matches(string input, string pattern) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Ensures(Contract.Result<MatchCollection>() != null); return default(MatchCollection); } public Match Match(string input, int beginning, int length) { Contract.Requires(input != null); Contract.Ensures(Contract.Result<Match>() != null); return default(Match); } public Match Match(string input, int startat) { Contract.Requires(input != null); Contract.Ensures(Contract.Result<Match>() != null); return default(Match); } [Pure] public Match Match(string input) { Contract.Requires(input != null); Contract.Ensures(Contract.Result<Match>() != null); return default(Match); } [Pure] public static Match Match(string input, string pattern, RegexOptions options) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Ensures(Contract.Result<Match>() != null); return default(Match); } [Pure] public static Match Match(string input, string pattern) { Contract.Requires(input != null); Contract.Requires(pattern != null); Contract.Ensures(Contract.Result<Match>() != null); return default(Match); } [Pure] public bool IsMatch(string input, int startat) { Contract.Requires(input != null); Contract.Requires(startat >= 0); return default(bool); } [Pure] public bool IsMatch(string input) { Contract.Requires(input != null); return default(bool); } [Pure] public static bool IsMatch(string input, string pattern, RegexOptions options) { return default(bool); } [Pure] public static bool IsMatch(string input, string pattern) { return default(bool); } [Pure] public int GroupNumberFromName(string name) { Contract.Requires(name != null); return default(int); } [Pure] public string GroupNameFromNumber(int i) { Contract.Ensures(Contract.Result<string>() != null); return default(string); } [Pure] public Int32[] GetGroupNumbers() { Contract.Ensures(Contract.Result<int[]>() != null); return default(Int32[]); } [Pure] public String[] GetGroupNames() { Contract.Ensures(Contract.Result<string[]>() != null); return default(String[]); } [Pure] public static string Unescape(string str) { Contract.Requires(str != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } [Pure] public static string Escape(string str) { Contract.Requires(str != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public Regex(string pattern, RegexOptions options) { Contract.Requires(pattern != null); } public Regex(string pattern) { Contract.Requires(pattern != null); } } }