context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using UnityEngine; using UnityEditor; using System.Linq; [CustomEditor(typeof(CC_Levels))] public class CC_LevelsEditor : CC_BaseEditor { GUIContent rampContent; int[] histogram; static Color32 lumColor; static Color32 redColor; static Color32 greenColor; static Color32 blueColor; static string[] channels = { "Red", "Green", "Blue" }; int selectedPreset = 0; static string[] presets = { "Default", "Darker", "Increase Contrast 1", "Increase Contrast 2", "Increase Contrast 3", "Lighten Shadows", "Lighter", "Midtones Brighter", "Midtones Darker" }; static float [,] presetsData = { { 0, 1, 255, 0, 255 }, { 15, 1, 255, 0, 255 }, { 10, 1, 245, 0, 255 }, { 20, 1, 235, 0, 255 }, { 30, 1, 225, 0, 255 }, { 0, 1.6f, 255, 0, 255 }, { 0, 1, 230, 0, 255 }, { 0, 1.25f, 255, 0, 255 }, { 0, 0.75f, 255, 0, 255 } }; static bool IsLinear { get { return QualitySettings.activeColorSpace == ColorSpace.Linear; } } SerializedProperty p_isRGB; SerializedProperty p_inputMinL; SerializedProperty p_inputMaxL; SerializedProperty p_inputGammaL; SerializedProperty p_inputMinR; SerializedProperty p_inputMaxR; SerializedProperty p_inputGammaR; SerializedProperty p_inputMinG; SerializedProperty p_inputMaxG; SerializedProperty p_inputGammaG; SerializedProperty p_inputMinB; SerializedProperty p_inputMaxB; SerializedProperty p_inputGammaB; SerializedProperty p_outputMinL; SerializedProperty p_outputMaxL; SerializedProperty p_outputMinR; SerializedProperty p_outputMaxR; SerializedProperty p_outputMinG; SerializedProperty p_outputMaxG; SerializedProperty p_outputMinB; SerializedProperty p_outputMaxB; SerializedProperty p_currentChannel; SerializedProperty p_logarithmic; void OnEnable() { p_isRGB = serializedObject.FindProperty("isRGB"); p_inputMinL = serializedObject.FindProperty("inputMinL"); p_inputMaxL = serializedObject.FindProperty("inputMaxL"); p_inputGammaL = serializedObject.FindProperty("inputGammaL"); p_inputMinR = serializedObject.FindProperty("inputMinR"); p_inputMaxR = serializedObject.FindProperty("inputMaxR"); p_inputGammaR = serializedObject.FindProperty("inputGammaR"); p_inputMinG = serializedObject.FindProperty("inputMinG"); p_inputMaxG = serializedObject.FindProperty("inputMaxG"); p_inputGammaG = serializedObject.FindProperty("inputGammaG"); p_inputMinB = serializedObject.FindProperty("inputMinB"); p_inputMaxB = serializedObject.FindProperty("inputMaxB"); p_inputGammaB = serializedObject.FindProperty("inputGammaB"); p_outputMinL = serializedObject.FindProperty("outputMinL"); p_outputMaxL = serializedObject.FindProperty("outputMaxL"); p_outputMinR = serializedObject.FindProperty("outputMinR"); p_outputMaxR = serializedObject.FindProperty("outputMaxR"); p_outputMinG = serializedObject.FindProperty("outputMinG"); p_outputMaxG = serializedObject.FindProperty("outputMaxG"); p_outputMinB = serializedObject.FindProperty("outputMinB"); p_outputMaxB = serializedObject.FindProperty("outputMaxB"); p_currentChannel = serializedObject.FindProperty("currentChannel"); p_logarithmic = serializedObject.FindProperty("logarithmic"); rampContent = new GUIContent((Texture2D)Resources.Load(IsLinear ? "GrayscaleRampLinear" : "GrayscaleRamp")); if (EditorGUIUtility.isProSkin) { lumColor = new Color32(255, 255, 255, 255); redColor = new Color32(215, 0, 0, 255); greenColor = new Color32(0, 215, 0, 255); blueColor = new Color32(0, 110, 205, 255); } else { lumColor = new Color32(20, 20, 20, 255); redColor = new Color32(215, 0, 0, 255); greenColor = new Color32(0, 180, 0, 255); blueColor = new Color32(0, 110, 205, 255); } histogram = new int[256]; ComputeHistogram(); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); // Mode & channels EditorGUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck(); if (p_isRGB.boolValue) p_currentChannel.intValue = EditorGUILayout.Popup(p_currentChannel.intValue, channels); p_isRGB.boolValue = GUILayout.Toggle(p_isRGB.boolValue, "Multi-channel Mode", EditorStyles.miniButton); if (EditorGUI.EndChangeCheck()) ComputeHistogram(); EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); // Top buttons EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(GUILayout.Width(256)); EditorGUI.BeginChangeCheck(); p_logarithmic.boolValue = GUILayout.Toggle(p_logarithmic.boolValue, "Log", EditorStyles.miniButton, GUILayout.Width(70)); if (EditorGUI.EndChangeCheck()) ComputeHistogram(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Auto B&W", EditorStyles.miniButton, GUILayout.Width(70))) { // Find min and max value on the current channel int min = 0, max = 255; for (int i = 0; i < 256; i++) { if (histogram[255 - i] > 0) min = 255 - i; if (histogram[i] > 0) max = i; } if (!p_isRGB.boolValue) { p_inputMinL.floatValue = min; p_inputMaxL.floatValue = max; } else { int c = p_currentChannel.intValue; if (c == 0) { p_inputMinR.floatValue = min; p_inputMaxR.floatValue = max; } else if (c == 1) { p_inputMinG.floatValue = min; p_inputMaxG.floatValue = max; } else if (c == 2) { p_inputMinB.floatValue = min; p_inputMaxB.floatValue = max; } } } GUILayout.FlexibleSpace(); if (GUILayout.Button("Refresh", EditorStyles.miniButton, GUILayout.Width(70))) { ComputeHistogram(); } EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); // Histogram EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.FlexibleSpace(); Rect histogramRect = GUILayoutUtility.GetRect(258, 128); GUI.Box(histogramRect, ""); if (!p_isRGB.boolValue) Handles.color = lumColor; else if (p_currentChannel.intValue == 0) Handles.color = redColor; else if (p_currentChannel.intValue == 1) Handles.color = greenColor; else if (p_currentChannel.intValue == 2) Handles.color = blueColor; for (int i = 0; i < 256; i++) { Handles.DrawLine( new Vector2(histogramRect.x + i + 2f, histogramRect.yMax - 1f), new Vector2(histogramRect.x + i + 2f, histogramRect.yMin - 1f + (histogramRect.height - histogram[i])) ); } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); // Bottom buttons EditorGUILayout.Separator(); if (!p_isRGB.boolValue) { ChannelUI(p_inputMinL, p_inputGammaL, p_inputMaxL, p_outputMinL, p_outputMaxL); } else { if (p_currentChannel.intValue == 0) ChannelUI(p_inputMinR, p_inputGammaR, p_inputMaxR, p_outputMinR, p_outputMaxR); else if (p_currentChannel.intValue == 1) ChannelUI(p_inputMinG, p_inputGammaG, p_inputMaxG, p_outputMinG, p_outputMaxG); else if (p_currentChannel.intValue == 2) ChannelUI(p_inputMinB, p_inputGammaB, p_inputMaxB, p_outputMinB, p_outputMaxB); } // Presets EditorGUI.BeginChangeCheck(); selectedPreset = EditorGUILayout.Popup("Preset", selectedPreset, presets); if (EditorGUI.EndChangeCheck()) { p_isRGB.boolValue = false; p_currentChannel.intValue = 0; p_inputMinL.floatValue = presetsData[selectedPreset, 0]; p_inputGammaL.floatValue = presetsData[selectedPreset, 1]; p_inputMaxL.floatValue = presetsData[selectedPreset, 2]; p_outputMinL.floatValue = presetsData[selectedPreset, 3]; p_outputMaxL.floatValue = presetsData[selectedPreset, 4]; ComputeHistogram(); } // Done serializedObject.ApplyModifiedProperties(); } void ChannelUI(SerializedProperty inputMinP, SerializedProperty inputGammaP, SerializedProperty inputMaxP, SerializedProperty outputMinP, SerializedProperty outputMaxP) { float inputMin = inputMinP.floatValue; float inputGamma = inputGammaP.floatValue; float inputMax = inputMaxP.floatValue; float outputMin = outputMinP.floatValue; float outputMax = outputMaxP.floatValue; // Input GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.MinMaxSlider(ref inputMin, ref inputMax, 0, 255, GUILayout.Width(256)); inputMinP.floatValue = inputMin; inputMaxP.floatValue = inputMax; GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(GUILayout.Width(256)); inputMin = EditorGUILayout.FloatField((int)inputMin, GUILayout.Width(50)); GUILayout.FlexibleSpace(); inputGamma = EditorGUILayout.FloatField(inputGamma, GUILayout.Width(50)); GUILayout.FlexibleSpace(); inputMax = EditorGUILayout.FloatField((int)inputMax, GUILayout.Width(50)); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); // Ramp GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.LabelField(rampContent, GUILayout.Width(256), GUILayout.Height(20)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); // Output GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.MinMaxSlider(ref outputMin, ref outputMax, 0, 255, GUILayout.Width(256)); outputMinP.floatValue = outputMin; outputMaxP.floatValue = outputMax; GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(GUILayout.Width(256)); outputMin = EditorGUILayout.FloatField((int)outputMin, GUILayout.Width(50)); GUILayout.FlexibleSpace(); outputMax = EditorGUILayout.FloatField((int)outputMax, GUILayout.Width(50)); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); inputMinP.floatValue = inputMin; inputGammaP.floatValue = Mathf.Clamp(inputGamma, 0.1f, 9.99f); inputMaxP.floatValue = inputMax; outputMinP.floatValue = outputMin; outputMaxP.floatValue = outputMax; } void ComputeHistogram() { int channel = !p_isRGB.boolValue ? 0 : p_currentChannel.intValue + 1; // Current camera MonoBehaviour target = (MonoBehaviour)this.target; CC_Levels comp = (CC_Levels)target.GetComponent<CC_Levels>(); Camera camera = target.GetComponent<Camera>(); if (camera == null || !camera.enabled || !target.enabled || !target.gameObject.activeInHierarchy) return; // Prepare the texture to render the camera to. Base width will be 640 pixels (precision should be good enough // to get an histogram) and the height depends on the camera aspect ratio Texture2D cameraTexture = new Texture2D(640, (int)(640f * camera.aspect), TextureFormat.ARGB32, false, IsLinear); cameraTexture.hideFlags = HideFlags.HideAndDontSave; cameraTexture.filterMode = FilterMode.Point; RenderTexture rt = RenderTexture.GetTemporary(cameraTexture.width, cameraTexture.height, 24, RenderTextureFormat.ARGB32); // Backup the current states bool prevCompEnabled = comp.enabled; RenderTexture prevTargetTexture = camera.targetTexture; // Disable the current CC_Levels component, we don't want it to be applied before getting the histogram data comp.enabled = false; // Render camera.targetTexture = rt; RenderTexture.active = rt; camera.Render(); cameraTexture.ReadPixels(new Rect(0, 0, cameraTexture.width, cameraTexture.height), 0, 0, false); cameraTexture.Apply(); Color32[] pixels = cameraTexture.GetPixels32(); // Cleanup camera.targetTexture = prevTargetTexture; RenderTexture.active = null; RenderTexture.ReleaseTemporary(rt); DestroyImmediate(cameraTexture); comp.enabled = prevCompEnabled; // Gets the histogram for the given channel histogram = new int[256]; int l = pixels.Length; if (channel == 0) // Lum { for (int i = 0; i < l; i++) histogram[(int)(pixels[i].r * 0.3f + pixels[i].g * 0.59f + pixels[i].b * 0.11f)]++; } else if (channel == 1) // Red { for (int i = 0; i < l; i++) histogram[pixels[i].r]++; } else if (channel == 2) // Green { for (int i = 0; i < l; i++) histogram[pixels[i].g]++; } else if (channel == 3) // Blue { for (int i = 0; i < l; i++) histogram[pixels[i].b]++; } // Scale the histogram values float max = histogram.Max(); if (p_logarithmic.boolValue) // Log { float factor = 126f / Mathf.Log10(max); for (int i = 0; i < 256; i++) histogram[i] = (histogram[i] == 0) ? 0 : (int)Mathf.Round(Mathf.Log10(histogram[i]) * factor); } else // Linear { float factor = 126f / max; for (int i = 0; i < 256; i++) histogram[i] = (int)Mathf.Round(histogram[i] * factor); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace WebApiServices.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Cloud OS Login API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://cloud.google.com/compute/docs/oslogin/'>Cloud OS Login API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20190204 (1495) * <tr><th>API Docs * <td><a href='https://cloud.google.com/compute/docs/oslogin/'> * https://cloud.google.com/compute/docs/oslogin/</a> * <tr><th>Discovery Name<td>oslogin * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Cloud OS Login API can be found at * <a href='https://cloud.google.com/compute/docs/oslogin/'>https://cloud.google.com/compute/docs/oslogin/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.CloudOSLogin.v1 { /// <summary>The CloudOSLogin Service.</summary> public class CloudOSLoginService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudOSLoginService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudOSLoginService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { users = new UsersResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "oslogin"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://oslogin.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://oslogin.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud OS Login API.</summary> public class Scope { /// <summary>View and manage your data across Google Cloud Platform services</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>View and manage your Google Compute Engine resources</summary> public static string Compute = "https://www.googleapis.com/auth/compute"; } /// <summary>Available OAuth 2.0 scope constants for use with the Cloud OS Login API.</summary> public static class ScopeConstants { /// <summary>View and manage your data across Google Cloud Platform services</summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary>View and manage your Google Compute Engine resources</summary> public const string Compute = "https://www.googleapis.com/auth/compute"; } private readonly UsersResource users; /// <summary>Gets the Users resource.</summary> public virtual UsersResource Users { get { return users; } } } ///<summary>A base abstract class for CloudOSLogin requests.</summary> public abstract class CloudOSLoginBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new CloudOSLoginBaseServiceRequest instance.</summary> protected CloudOSLoginBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudOSLogin parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "users" collection of methods.</summary> public class UsersResource { private const string Resource = "users"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public UsersResource(Google.Apis.Services.IClientService service) { this.service = service; projects = new ProjectsResource(service); sshPublicKeys = new SshPublicKeysResource(service); } private readonly ProjectsResource projects; /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get { return projects; } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Deletes a POSIX account.</summary> /// <param name="name">A reference to the POSIX account to update. POSIX accounts are identified by the project ID they /// are associated with. A reference to the POSIX account is in format `users/{user}/projects/{project}`.</param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary>Deletes a POSIX account.</summary> public class DeleteRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>A reference to the POSIX account to update. POSIX accounts are identified by the project ID /// they are associated with. A reference to the POSIX account is in format /// `users/{user}/projects/{project}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+/projects/[^/]+$", }); } } } private readonly SshPublicKeysResource sshPublicKeys; /// <summary>Gets the SshPublicKeys resource.</summary> public virtual SshPublicKeysResource SshPublicKeys { get { return sshPublicKeys; } } /// <summary>The "sshPublicKeys" collection of methods.</summary> public class SshPublicKeysResource { private const string Resource = "sshPublicKeys"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public SshPublicKeysResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Deletes an SSH public key.</summary> /// <param name="name">The fingerprint of the public key to update. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format `users/{user}/sshPublicKeys/{fingerprint}`.</param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary>Deletes an SSH public key.</summary> public class DeleteRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The fingerprint of the public key to update. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format /// `users/{user}/sshPublicKeys/{fingerprint}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+/sshPublicKeys/[^/]+$", }); } } /// <summary>Retrieves an SSH public key.</summary> /// <param name="name">The fingerprint of the public key to retrieve. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format `users/{user}/sshPublicKeys/{fingerprint}`.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Retrieves an SSH public key.</summary> public class GetRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1.Data.SshPublicKey> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The fingerprint of the public key to retrieve. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format /// `users/{user}/sshPublicKeys/{fingerprint}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+/sshPublicKeys/[^/]+$", }); } } /// <summary>Updates an SSH public key and returns the profile information. This method supports patch /// semantics.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The fingerprint of the public key to update. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format `users/{user}/sshPublicKeys/{fingerprint}`.</param> public virtual PatchRequest Patch(Google.Apis.CloudOSLogin.v1.Data.SshPublicKey body, string name) { return new PatchRequest(service, body, name); } /// <summary>Updates an SSH public key and returns the profile information. This method supports patch /// semantics.</summary> public class PatchRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1.Data.SshPublicKey> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudOSLogin.v1.Data.SshPublicKey body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The fingerprint of the public key to update. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format /// `users/{user}/sshPublicKeys/{fingerprint}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Mask to control which fields get updated. Updates all if not present.</summary> [Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)] public virtual object UpdateMask { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudOSLogin.v1.Data.SshPublicKey Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "patch"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PATCH"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+/sshPublicKeys/[^/]+$", }); RequestParameters.Add( "updateMask", new Google.Apis.Discovery.Parameter { Name = "updateMask", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>Retrieves the profile information used for logging in to a virtual machine on Google Compute /// Engine.</summary> /// <param name="name">The unique ID for the user in format `users/{user}`.</param> public virtual GetLoginProfileRequest GetLoginProfile(string name) { return new GetLoginProfileRequest(service, name); } /// <summary>Retrieves the profile information used for logging in to a virtual machine on Google Compute /// Engine.</summary> public class GetLoginProfileRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1.Data.LoginProfile> { /// <summary>Constructs a new GetLoginProfile request.</summary> public GetLoginProfileRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The unique ID for the user in format `users/{user}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>The project ID of the Google Cloud Platform project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Query)] public virtual string ProjectId { get; set; } /// <summary>A system ID for filtering the results of the request.</summary> [Google.Apis.Util.RequestParameterAttribute("systemId", Google.Apis.Util.RequestParameterType.Query)] public virtual string SystemId { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "getLoginProfile"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}/loginProfile"; } } /// <summary>Initializes GetLoginProfile parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+$", }); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "systemId", new Google.Apis.Discovery.Parameter { Name = "systemId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Adds an SSH public key and returns the profile information. Default POSIX account information is /// set when no username and UID exist as part of the login profile.</summary> /// <param name="body">The body of the request.</param> /// <param name="parent">The unique ID for the user in format `users/{user}`.</param> public virtual ImportSshPublicKeyRequest ImportSshPublicKey(Google.Apis.CloudOSLogin.v1.Data.SshPublicKey body, string parent) { return new ImportSshPublicKeyRequest(service, body, parent); } /// <summary>Adds an SSH public key and returns the profile information. Default POSIX account information is /// set when no username and UID exist as part of the login profile.</summary> public class ImportSshPublicKeyRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1.Data.ImportSshPublicKeyResponse> { /// <summary>Constructs a new ImportSshPublicKey request.</summary> public ImportSshPublicKeyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudOSLogin.v1.Data.SshPublicKey body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary>The unique ID for the user in format `users/{user}`.</summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>The project ID of the Google Cloud Platform project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Query)] public virtual string ProjectId { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudOSLogin.v1.Data.SshPublicKey Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "importSshPublicKey"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+parent}:importSshPublicKey"; } } /// <summary>Initializes ImportSshPublicKey parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+$", }); RequestParameters.Add( "projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.CloudOSLogin.v1.Data { /// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A /// typical example is to use it as the request or the response type of an API method. For instance: /// /// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } /// /// The JSON representation for `Empty` is empty JSON object `{}`.</summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A response message for importing an SSH public key.</summary> public class ImportSshPublicKeyResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The login profile information for the user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("loginProfile")] public virtual LoginProfile LoginProfile { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The user profile information used for logging in to a virtual machine on Google Compute /// Engine.</summary> public class LoginProfile : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A unique user ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The list of POSIX accounts associated with the user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("posixAccounts")] public virtual System.Collections.Generic.IList<PosixAccount> PosixAccounts { get; set; } /// <summary>A map from SSH public key fingerprint to the associated key object.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sshPublicKeys")] public virtual System.Collections.Generic.IDictionary<string,SshPublicKey> SshPublicKeys { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The POSIX account information associated with a Google account.</summary> public class PosixAccount : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Output only. A POSIX account identifier.</summary> [Newtonsoft.Json.JsonPropertyAttribute("accountId")] public virtual string AccountId { get; set; } /// <summary>The GECOS (user information) entry for this account.</summary> [Newtonsoft.Json.JsonPropertyAttribute("gecos")] public virtual string Gecos { get; set; } /// <summary>The default group ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("gid")] public virtual System.Nullable<long> Gid { get; set; } /// <summary>The path to the home directory for this account.</summary> [Newtonsoft.Json.JsonPropertyAttribute("homeDirectory")] public virtual string HomeDirectory { get; set; } /// <summary>The operating system type where this account applies.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operatingSystemType")] public virtual string OperatingSystemType { get; set; } /// <summary>Only one POSIX account can be marked as primary.</summary> [Newtonsoft.Json.JsonPropertyAttribute("primary")] public virtual System.Nullable<bool> Primary { get; set; } /// <summary>The path to the logic shell for this account.</summary> [Newtonsoft.Json.JsonPropertyAttribute("shell")] public virtual string Shell { get; set; } /// <summary>System identifier for which account the username or uid applies to. By default, the empty value is /// used.</summary> [Newtonsoft.Json.JsonPropertyAttribute("systemId")] public virtual string SystemId { get; set; } /// <summary>The user ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("uid")] public virtual System.Nullable<long> Uid { get; set; } /// <summary>The username of the POSIX account.</summary> [Newtonsoft.Json.JsonPropertyAttribute("username")] public virtual string Username { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The SSH public key information associated with a Google account.</summary> public class SshPublicKey : Google.Apis.Requests.IDirectResponseSchema { /// <summary>An expiration time in microseconds since epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expirationTimeUsec")] public virtual System.Nullable<long> ExpirationTimeUsec { get; set; } /// <summary>Output only. The SHA-256 fingerprint of the SSH public key.</summary> [Newtonsoft.Json.JsonPropertyAttribute("fingerprint")] public virtual string Fingerprint { get; set; } /// <summary>Public key text in SSH format, defined by RFC4253 section 6.6.</summary> [Newtonsoft.Json.JsonPropertyAttribute("key")] public virtual string Key { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { /// <summary> /// A revolute joint constrains to bodies to share a common point while they /// are free to rotate about the point. The relative rotation about the shared /// point is the joint angle. You can limit the relative rotation with /// a joint limit that specifies a lower and upper angle. You can use a motor /// to drive the relative rotation about the shared point. A maximum motor torque /// is provided so that infinite forces are not generated. /// </summary> public class RevoluteJoint : Joint { #region Properties/Fields /// <summary> /// The local anchor point on BodyA /// </summary> public Vector2 localAnchorA; /// <summary> /// The local anchor point on BodyB /// </summary> public Vector2 localAnchorB; public override Vector2 worldAnchorA { get { return bodyA.getWorldPoint( localAnchorA ); } set { localAnchorA = bodyA.getLocalPoint( value ); } } public override Vector2 worldAnchorB { get { return bodyB.getWorldPoint( localAnchorB ); } set { localAnchorB = bodyB.getLocalPoint( value ); } } /// <summary> /// The referance angle computed as BodyB angle minus BodyA angle. /// </summary> public float referenceAngle { get { return _referenceAngle; } set { wakeBodies(); _referenceAngle = value; } } /// <summary> /// Get the current joint angle in radians. /// </summary> public float jointAngle { get { return bodyB._sweep.a - bodyA._sweep.a - referenceAngle; } } /// <summary> /// Get the current joint angle speed in radians per second. /// </summary> public float jointSpeed { get { return bodyB._angularVelocity - bodyA._angularVelocity; } } /// <summary> /// Is the joint limit enabled? /// </summary> /// <value><c>true</c> if [limit enabled]; otherwise, <c>false</c>.</value> public bool limitEnabled { get { return _enableLimit; } set { if( _enableLimit != value ) { wakeBodies(); _enableLimit = value; _impulse.Z = 0.0f; } } } /// <summary> /// Get the lower joint limit in radians. /// </summary> public float lowerLimit { get { return _lowerAngle; } set { if( _lowerAngle != value ) { wakeBodies(); _lowerAngle = value; _impulse.Z = 0.0f; } } } /// <summary> /// Get the upper joint limit in radians. /// </summary> public float upperLimit { get { return _upperAngle; } set { if( _upperAngle != value ) { wakeBodies(); _upperAngle = value; _impulse.Z = 0.0f; } } } /// <summary> /// Is the joint motor enabled? /// </summary> /// <value><c>true</c> if [motor enabled]; otherwise, <c>false</c>.</value> public bool motorEnabled { get { return _enableMotor; } set { wakeBodies(); _enableMotor = value; } } /// <summary> /// Get or set the motor speed in radians per second. /// </summary> public float motorSpeed { set { wakeBodies(); _motorSpeed = value; } get { return _motorSpeed; } } /// <summary> /// Get or set the maximum motor torque, usually in N-m. /// </summary> public float maxMotorTorque { set { wakeBodies(); _maxMotorTorque = value; } get { return _maxMotorTorque; } } /// <summary> /// Get or set the current motor impulse, usually in N-m. /// </summary> public float motorImpulse { get { return _motorImpulse; } set { wakeBodies(); _motorImpulse = value; } } // Solver shared Vector3 _impulse; float _motorImpulse; bool _enableMotor; float _maxMotorTorque; float _motorSpeed; bool _enableLimit; float _referenceAngle; float _lowerAngle; float _upperAngle; // Solver temp int _indexA; int _indexB; Vector2 _rA; Vector2 _rB; Vector2 _localCenterA; Vector2 _localCenterB; float _invMassA; float _invMassB; float _invIA; float _invIB; Mat33 _mass; // effective mass for point-to-point constraint. float _motorMass; // effective mass for motor/limit angular constraint. LimitState _limitState; #endregion internal RevoluteJoint() { jointType = JointType.Revolute; } /// <summary> /// Constructor of RevoluteJoint. /// </summary> /// <param name="bodyA">The first body.</param> /// <param name="bodyB">The second body.</param> /// <param name="anchorA">The first body anchor.</param> /// <param name="anchorB">The second anchor.</param> /// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param> public RevoluteJoint( Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, bool useWorldCoordinates = false ) : base( bodyA, bodyB ) { jointType = JointType.Revolute; if( useWorldCoordinates ) { localAnchorA = base.bodyA.getLocalPoint( anchorA ); localAnchorB = base.bodyB.getLocalPoint( anchorB ); } else { localAnchorA = anchorA; localAnchorB = anchorB; } referenceAngle = base.bodyB.rotation - base.bodyA.rotation; _impulse = Vector3.Zero; _limitState = LimitState.Inactive; } /// <summary> /// Constructor of RevoluteJoint. /// </summary> /// <param name="bodyA">The first body.</param> /// <param name="bodyB">The second body.</param> /// <param name="anchor">The shared anchor.</param> /// <param name="useWorldCoordinates"></param> public RevoluteJoint( Body bodyA, Body bodyB, Vector2 anchor, bool useWorldCoordinates = false ) : this( bodyA, bodyB, anchor, anchor, useWorldCoordinates ) { } /// <summary> /// Set the joint limits, usually in meters. /// </summary> /// <param name="lower">The lower limit</param> /// <param name="upper">The upper limit</param> public void setLimits( float lower, float upper ) { if( lower != _lowerAngle || upper != _upperAngle ) { wakeBodies(); _upperAngle = upper; _lowerAngle = lower; _impulse.Z = 0.0f; } } /// <summary> /// Gets the motor torque in N-m. /// </summary> /// <param name="invDt">The inverse delta time</param> public float getMotorTorque( float invDt ) { return invDt * _motorImpulse; } public override Vector2 getReactionForce( float invDt ) { var p = new Vector2( _impulse.X, _impulse.Y ); return invDt * p; } public override float getReactionTorque( float invDt ) { return invDt * _impulse.Z; } internal override void initVelocityConstraints( ref SolverData data ) { _indexA = bodyA.islandIndex; _indexB = bodyB.islandIndex; _localCenterA = bodyA._sweep.localCenter; _localCenterB = bodyB._sweep.localCenter; _invMassA = bodyA._invMass; _invMassB = bodyB._invMass; _invIA = bodyA._invI; _invIB = bodyB._invI; float aA = data.positions[_indexA].a; Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; float aB = data.positions[_indexB].a; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; Rot qA = new Rot( aA ), qB = new Rot( aB ); _rA = MathUtils.mul( qA, localAnchorA - _localCenterA ); _rB = MathUtils.mul( qB, localAnchorB - _localCenterB ); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; bool fixedRotation = ( iA + iB == 0.0f ); _mass.ex.X = mA + mB + _rA.Y * _rA.Y * iA + _rB.Y * _rB.Y * iB; _mass.ey.X = -_rA.Y * _rA.X * iA - _rB.Y * _rB.X * iB; _mass.ez.X = -_rA.Y * iA - _rB.Y * iB; _mass.ex.Y = _mass.ey.X; _mass.ey.Y = mA + mB + _rA.X * _rA.X * iA + _rB.X * _rB.X * iB; _mass.ez.Y = _rA.X * iA + _rB.X * iB; _mass.ex.Z = _mass.ez.X; _mass.ey.Z = _mass.ez.Y; _mass.ez.Z = iA + iB; _motorMass = iA + iB; if( _motorMass > 0.0f ) { _motorMass = 1.0f / _motorMass; } if( _enableMotor == false || fixedRotation ) { _motorImpulse = 0.0f; } if( _enableLimit && fixedRotation == false ) { float jointAngle = aB - aA - referenceAngle; if( Math.Abs( _upperAngle - _lowerAngle ) < 2.0f * Settings.angularSlop ) { _limitState = LimitState.Equal; } else if( jointAngle <= _lowerAngle ) { if( _limitState != LimitState.AtLower ) { _impulse.Z = 0.0f; } _limitState = LimitState.AtLower; } else if( jointAngle >= _upperAngle ) { if( _limitState != LimitState.AtUpper ) { _impulse.Z = 0.0f; } _limitState = LimitState.AtUpper; } else { _limitState = LimitState.Inactive; _impulse.Z = 0.0f; } } else { _limitState = LimitState.Inactive; } if( Settings.enableWarmstarting ) { // Scale impulses to support a variable time step. _impulse *= data.step.dtRatio; _motorImpulse *= data.step.dtRatio; Vector2 P = new Vector2( _impulse.X, _impulse.Y ); vA -= mA * P; wA -= iA * ( MathUtils.cross( _rA, P ) + motorImpulse + _impulse.Z ); vB += mB * P; wB += iB * ( MathUtils.cross( _rB, P ) + motorImpulse + _impulse.Z ); } else { _impulse = Vector3.Zero; _motorImpulse = 0.0f; } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override void solveVelocityConstraints( ref SolverData data ) { Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; bool fixedRotation = ( iA + iB == 0.0f ); // Solve motor constraint. if( _enableMotor && _limitState != LimitState.Equal && fixedRotation == false ) { float Cdot = wB - wA - _motorSpeed; float impulse = _motorMass * ( -Cdot ); float oldImpulse = _motorImpulse; float maxImpulse = data.step.dt * _maxMotorTorque; _motorImpulse = MathUtils.clamp( _motorImpulse + impulse, -maxImpulse, maxImpulse ); impulse = _motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve limit constraint. if( _enableLimit && _limitState != LimitState.Inactive && fixedRotation == false ) { Vector2 Cdot1 = vB + MathUtils.cross( wB, _rB ) - vA - MathUtils.cross( wA, _rA ); float Cdot2 = wB - wA; Vector3 Cdot = new Vector3( Cdot1.X, Cdot1.Y, Cdot2 ); Vector3 impulse = -_mass.Solve33( Cdot ); if( _limitState == LimitState.Equal ) { _impulse += impulse; } else if( _limitState == LimitState.AtLower ) { float newImpulse = _impulse.Z + impulse.Z; if( newImpulse < 0.0f ) { Vector2 rhs = -Cdot1 + _impulse.Z * new Vector2( _mass.ez.X, _mass.ez.Y ); Vector2 reduced = _mass.Solve22( rhs ); impulse.X = reduced.X; impulse.Y = reduced.Y; impulse.Z = -_impulse.Z; _impulse.X += reduced.X; _impulse.Y += reduced.Y; _impulse.Z = 0.0f; } else { _impulse += impulse; } } else if( _limitState == LimitState.AtUpper ) { float newImpulse = _impulse.Z + impulse.Z; if( newImpulse > 0.0f ) { Vector2 rhs = -Cdot1 + _impulse.Z * new Vector2( _mass.ez.X, _mass.ez.Y ); Vector2 reduced = _mass.Solve22( rhs ); impulse.X = reduced.X; impulse.Y = reduced.Y; impulse.Z = -_impulse.Z; _impulse.X += reduced.X; _impulse.Y += reduced.Y; _impulse.Z = 0.0f; } else { _impulse += impulse; } } Vector2 P = new Vector2( impulse.X, impulse.Y ); vA -= mA * P; wA -= iA * ( MathUtils.cross( _rA, P ) + impulse.Z ); vB += mB * P; wB += iB * ( MathUtils.cross( _rB, P ) + impulse.Z ); } else { // Solve point-to-point constraint Vector2 Cdot = vB + MathUtils.cross( wB, _rB ) - vA - MathUtils.cross( wA, _rA ); Vector2 impulse = _mass.Solve22( -Cdot ); _impulse.X += impulse.X; _impulse.Y += impulse.Y; vA -= mA * impulse; wA -= iA * MathUtils.cross( _rA, impulse ); vB += mB * impulse; wB += iB * MathUtils.cross( _rB, impulse ); } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override bool solvePositionConstraints( ref SolverData data ) { Vector2 cA = data.positions[_indexA].c; float aA = data.positions[_indexA].a; Vector2 cB = data.positions[_indexB].c; float aB = data.positions[_indexB].a; Rot qA = new Rot( aA ), qB = new Rot( aB ); float angularError = 0.0f; float positionError; bool fixedRotation = ( _invIA + _invIB == 0.0f ); // Solve angular limit constraint. if( _enableLimit && _limitState != LimitState.Inactive && fixedRotation == false ) { float angle = aB - aA - referenceAngle; float limitImpulse = 0.0f; if( _limitState == LimitState.Equal ) { // Prevent large angular corrections float C = MathUtils.clamp( angle - _lowerAngle, -Settings.maxAngularCorrection, Settings.maxAngularCorrection ); limitImpulse = -_motorMass * C; angularError = Math.Abs( C ); } else if( _limitState == LimitState.AtLower ) { float C = angle - _lowerAngle; angularError = -C; // Prevent large angular corrections and allow some slop. C = MathUtils.clamp( C + Settings.angularSlop, -Settings.maxAngularCorrection, 0.0f ); limitImpulse = -_motorMass * C; } else if( _limitState == LimitState.AtUpper ) { float C = angle - _upperAngle; angularError = C; // Prevent large angular corrections and allow some slop. C = MathUtils.clamp( C - Settings.angularSlop, 0.0f, Settings.maxAngularCorrection ); limitImpulse = -_motorMass * C; } aA -= _invIA * limitImpulse; aB += _invIB * limitImpulse; } // Solve point-to-point constraint. { qA.Set( aA ); qB.Set( aB ); Vector2 rA = MathUtils.mul( qA, localAnchorA - _localCenterA ); Vector2 rB = MathUtils.mul( qB, localAnchorB - _localCenterB ); Vector2 C = cB + rB - cA - rA; positionError = C.Length(); float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; Mat22 K = new Mat22(); K.ex.X = mA + mB + iA * rA.Y * rA.Y + iB * rB.Y * rB.Y; K.ex.Y = -iA * rA.X * rA.Y - iB * rB.X * rB.Y; K.ey.X = K.ex.Y; K.ey.Y = mA + mB + iA * rA.X * rA.X + iB * rB.X * rB.X; Vector2 impulse = -K.Solve( C ); cA -= mA * impulse; aA -= iA * MathUtils.cross( rA, impulse ); cB += mB * impulse; aB += iB * MathUtils.cross( rB, impulse ); } data.positions[_indexA].c = cA; data.positions[_indexA].a = aA; data.positions[_indexB].c = cB; data.positions[_indexB].a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.ServiceModel.Discovery.VersionApril2005 { using System.ComponentModel; using System.ServiceModel.Channels; using System.Runtime; using System.ServiceModel.Description; using System.Threading; class AnnouncementInnerClientApril2005 : ClientBase<IAnnouncementContractApril2005>, IAnnouncementInnerClient { DiscoveryMessageSequenceGenerator discoveryMessageSequenceGenerator; BeginOperationDelegate onBeginHelloOperationDelegate; EndOperationDelegate onEndHelloOperationDelegate; SendOrPostCallback onHelloOperationCompletedDelegate; BeginOperationDelegate onBeginByeOperationDelegate; EndOperationDelegate onEndByeOperationDelegate; SendOrPostCallback onByeOperationCompletedDelegate; public AnnouncementInnerClientApril2005(AnnouncementEndpoint announcementEndpoint) : base(announcementEndpoint) { this.discoveryMessageSequenceGenerator = new DiscoveryMessageSequenceGenerator(); } event EventHandler<AsyncCompletedEventArgs> HelloOperationCompletedEventHandler; event EventHandler<AsyncCompletedEventArgs> ByeOperationCompletedEventHandler; event EventHandler<AsyncCompletedEventArgs> IAnnouncementInnerClient.HelloOperationCompleted { add { this.HelloOperationCompletedEventHandler += value; } remove { this.HelloOperationCompletedEventHandler -= value; } } event EventHandler<AsyncCompletedEventArgs> IAnnouncementInnerClient.ByeOperationCompleted { add { this.ByeOperationCompletedEventHandler += value; } remove { this.ByeOperationCompletedEventHandler -= value; } } public DiscoveryMessageSequenceGenerator DiscoveryMessageSequenceGenerator { get { return this.discoveryMessageSequenceGenerator; } set { this.discoveryMessageSequenceGenerator = value; } } public new ChannelFactory ChannelFactory { get { return base.ChannelFactory; } } public new IClientChannel InnerChannel { get { return base.InnerChannel; } } public new ServiceEndpoint Endpoint { get { return base.Endpoint; } } public ICommunicationObject InnerCommunicationObject { get { return this as ICommunicationObject; } } public void HelloOperation(EndpointDiscoveryMetadata endpointDiscoveryMetadata) { HelloMessageApril2005 message = HelloMessageApril2005.Create(DiscoveryMessageSequenceGenerator.Next(), endpointDiscoveryMetadata); base.Channel.HelloOperation(message); } public void ByeOperation(EndpointDiscoveryMetadata endpointDiscoveryMetadata) { ByeMessageApril2005 message = ByeMessageApril2005.Create(DiscoveryMessageSequenceGenerator.Next(), endpointDiscoveryMetadata); base.Channel.ByeOperation(message); } public IAsyncResult BeginHelloOperation(EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state) { HelloMessageApril2005 message = HelloMessageApril2005.Create(DiscoveryMessageSequenceGenerator.Next(), endpointDiscoveryMetadata); return base.Channel.BeginHelloOperation(message, callback, state); } IAsyncResult BeginHelloOperation(HelloMessageApril2005 message, AsyncCallback callback, object state) { return base.Channel.BeginHelloOperation(message, callback, state); } public void EndHelloOperation(IAsyncResult result) { base.Channel.EndHelloOperation(result); } public IAsyncResult BeginByeOperation(EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state) { ByeMessageApril2005 message = ByeMessageApril2005.Create(DiscoveryMessageSequenceGenerator.Next(), endpointDiscoveryMetadata); return base.Channel.BeginByeOperation(message, callback, state); } IAsyncResult BeginByeOperation(ByeMessageApril2005 message, AsyncCallback callback, object state) { return base.Channel.BeginByeOperation(message, callback, state); } public void EndByeOperation(IAsyncResult result) { base.Channel.EndByeOperation(result); } IAsyncResult OnBeginHelloOperation(object[] inValues, System.AsyncCallback callback, object asyncState) { HelloMessageApril2005 message = ((HelloMessageApril2005)(inValues[0])); return this.BeginHelloOperation(message, callback, asyncState); } object[] OnEndHelloOperation(System.IAsyncResult result) { this.EndHelloOperation(result); return null; } void OnHelloOperationCompleted(object state) { if ((this.HelloOperationCompletedEventHandler != null)) { InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state)); this.HelloOperationCompletedEventHandler(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } public void HelloOperationAsync(EndpointDiscoveryMetadata endpointDiscoveryMetadata, object userState) { HelloMessageApril2005 message = HelloMessageApril2005.Create(DiscoveryMessageSequenceGenerator.Next(), endpointDiscoveryMetadata); if ((this.onBeginHelloOperationDelegate == null)) { this.onBeginHelloOperationDelegate = new BeginOperationDelegate(this.OnBeginHelloOperation); } if ((this.onEndHelloOperationDelegate == null)) { this.onEndHelloOperationDelegate = new EndOperationDelegate(this.OnEndHelloOperation); } if ((this.onHelloOperationCompletedDelegate == null)) { this.onHelloOperationCompletedDelegate = Fx.ThunkCallback(new SendOrPostCallback(this.OnHelloOperationCompleted)); } base.InvokeAsync( this.onBeginHelloOperationDelegate, new object[] { message }, this.onEndHelloOperationDelegate, this.onHelloOperationCompletedDelegate, userState); } IAsyncResult OnBeginByeOperation(object[] inValues, System.AsyncCallback callback, object asyncState) { ByeMessageApril2005 message = ((ByeMessageApril2005)(inValues[0])); return this.BeginByeOperation(message, callback, asyncState); } object[] OnEndByeOperation(System.IAsyncResult result) { this.EndByeOperation(result); return null; } void OnByeOperationCompleted(object state) { if ((this.ByeOperationCompletedEventHandler != null)) { InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state)); this.ByeOperationCompletedEventHandler(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState)); } } public void ByeOperationAsync(EndpointDiscoveryMetadata endpointDiscoveryMetadata, object userState) { ByeMessageApril2005 message = ByeMessageApril2005.Create(DiscoveryMessageSequenceGenerator.Next(), endpointDiscoveryMetadata); if ((this.onBeginByeOperationDelegate == null)) { this.onBeginByeOperationDelegate = new BeginOperationDelegate(this.OnBeginByeOperation); } if ((this.onEndByeOperationDelegate == null)) { this.onEndByeOperationDelegate = new EndOperationDelegate(this.OnEndByeOperation); } if ((this.onByeOperationCompletedDelegate == null)) { this.onByeOperationCompletedDelegate = Fx.ThunkCallback(new SendOrPostCallback(this.OnByeOperationCompleted)); } base.InvokeAsync( this.onBeginByeOperationDelegate, new object[] { message }, this.onEndByeOperationDelegate, this.onByeOperationCompletedDelegate, userState); } } }
using System; /* * $Id: Inflate.cs,v 1.2 2008/05/10 09:35:40 bouncy Exp $ * Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ namespace Org.BouncyCastle.Utilities.Zlib { internal sealed class Inflate{ private const int MAX_WBITS=15; // 32K LZ77 window // preset dictionary flag in zlib header private const int PRESET_DICT=0x20; internal const int Z_NO_FLUSH=0; internal const int Z_PARTIAL_FLUSH=1; internal const int Z_SYNC_FLUSH=2; internal const int Z_FULL_FLUSH=3; internal const int Z_FINISH=4; private const int Z_DEFLATED=8; private const int Z_OK=0; private const int Z_STREAM_END=1; private const int Z_NEED_DICT=2; private const int Z_ERRNO=-1; private const int Z_STREAM_ERROR=-2; private const int Z_DATA_ERROR=-3; private const int Z_MEM_ERROR=-4; private const int Z_BUF_ERROR=-5; private const int Z_VERSION_ERROR=-6; private const int METHOD=0; // waiting for method byte private const int FLAG=1; // waiting for flag byte private const int DICT4=2; // four dictionary check bytes to go private const int DICT3=3; // three dictionary check bytes to go private const int DICT2=4; // two dictionary check bytes to go private const int DICT1=5; // one dictionary check byte to go private const int DICT0=6; // waiting for inflateSetDictionary private const int BLOCKS=7; // decompressing blocks private const int CHECK4=8; // four check bytes to go private const int CHECK3=9; // three check bytes to go private const int CHECK2=10; // two check bytes to go private const int CHECK1=11; // one check byte to go private const int DONE=12; // finished check, done private const int BAD=13; // got an error--stay here internal int mode; // current inflate mode // mode dependent information internal int method; // if FLAGS, method byte // if CHECK, check values to compare internal long[] was=new long[1] ; // computed check value internal long need; // stream check value // if BAD, inflateSync's marker bytes count internal int marker; // mode independent information internal int nowrap; // flag for no wrapper internal int wbits; // log2(window size) (8..15, defaults to 15) internal InfBlocks blocks; // current inflate_blocks state internal int inflateReset(ZStream z){ if(z == null || z.istate == null) return Z_STREAM_ERROR; z.total_in = z.total_out = 0; z.msg = null; z.istate.mode = z.istate.nowrap!=0 ? BLOCKS : METHOD; z.istate.blocks.reset(z, null); return Z_OK; } internal int inflateEnd(ZStream z){ if(blocks != null) blocks.free(z); blocks=null; // ZFREE(z, z->state); return Z_OK; } internal int inflateInit(ZStream z, int w){ z.msg = null; blocks = null; // handle undocumented nowrap option (no zlib header or check) nowrap = 0; if(w < 0){ w = - w; nowrap = 1; } // set window size if(w<8 ||w>15){ inflateEnd(z); return Z_STREAM_ERROR; } wbits=w; z.istate.blocks=new InfBlocks(z, z.istate.nowrap!=0 ? null : this, 1<<w); // reset state inflateReset(z); return Z_OK; } internal int inflate(ZStream z, int f){ int r; int b; if(z == null || z.istate == null || z.next_in == null) return Z_STREAM_ERROR; f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK; r = Z_BUF_ERROR; while (true){ //System.out.println("mode: "+z.istate.mode); switch (z.istate.mode){ case METHOD: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; if(((z.istate.method = z.next_in[z.next_in_index++])&0xf)!=Z_DEFLATED){ z.istate.mode = BAD; z.msg="unknown compression method"; z.istate.marker = 5; // can't try inflateSync break; } if((z.istate.method>>4)+8>z.istate.wbits){ z.istate.mode = BAD; z.msg="invalid window size"; z.istate.marker = 5; // can't try inflateSync break; } z.istate.mode=FLAG; goto case FLAG; case FLAG: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; b = (z.next_in[z.next_in_index++])&0xff; if((((z.istate.method << 8)+b) % 31)!=0){ z.istate.mode = BAD; z.msg = "incorrect header check"; z.istate.marker = 5; // can't try inflateSync break; } if((b&PRESET_DICT)==0){ z.istate.mode = BLOCKS; break; } z.istate.mode = DICT4; goto case DICT4; case DICT4: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L; z.istate.mode=DICT3; goto case DICT3; case DICT3: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L; z.istate.mode=DICT2; goto case DICT2; case DICT2: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L; z.istate.mode=DICT1; goto case DICT1; case DICT1: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; z.istate.need += (z.next_in[z.next_in_index++]&0xffL); z.adler = z.istate.need; z.istate.mode = DICT0; return Z_NEED_DICT; case DICT0: z.istate.mode = BAD; z.msg = "need dictionary"; z.istate.marker = 0; // can try inflateSync return Z_STREAM_ERROR; case BLOCKS: r = z.istate.blocks.proc(z, r); if(r == Z_DATA_ERROR){ z.istate.mode = BAD; z.istate.marker = 0; // can try inflateSync break; } if(r == Z_OK){ r = f; } if(r != Z_STREAM_END){ return r; } r = f; z.istate.blocks.reset(z, z.istate.was); if(z.istate.nowrap!=0){ z.istate.mode=DONE; break; } z.istate.mode=CHECK4; goto case CHECK4; case CHECK4: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L; z.istate.mode=CHECK3; goto case CHECK3; case CHECK3: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L; z.istate.mode = CHECK2; goto case CHECK2; case CHECK2: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L; z.istate.mode = CHECK1; goto case CHECK1; case CHECK1: if(z.avail_in==0)return r;r=f; z.avail_in--; z.total_in++; z.istate.need+=(z.next_in[z.next_in_index++]&0xffL); if(((int)(z.istate.was[0])) != ((int)(z.istate.need))){ z.istate.mode = BAD; z.msg = "incorrect data check"; z.istate.marker = 5; // can't try inflateSync break; } z.istate.mode = DONE; goto case DONE; case DONE: return Z_STREAM_END; case BAD: return Z_DATA_ERROR; default: return Z_STREAM_ERROR; } } } internal int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength){ int index=0; int length = dictLength; if(z==null || z.istate == null|| z.istate.mode != DICT0) return Z_STREAM_ERROR; if(z._adler.adler32(1L, dictionary, 0, dictLength)!=z.adler){ return Z_DATA_ERROR; } z.adler = z._adler.adler32(0, null, 0, 0); if(length >= (1<<z.istate.wbits)){ length = (1<<z.istate.wbits)-1; index=dictLength - length; } z.istate.blocks.set_dictionary(dictionary, index, length); z.istate.mode = BLOCKS; return Z_OK; } private static readonly byte[] mark = {(byte)0, (byte)0, (byte)0xff, (byte)0xff}; internal int inflateSync(ZStream z){ int n; // number of bytes to look at int p; // pointer to bytes int m; // number of marker bytes found in a row long r, w; // temporaries to save total_in and total_out // set up if(z == null || z.istate == null) return Z_STREAM_ERROR; if(z.istate.mode != BAD){ z.istate.mode = BAD; z.istate.marker = 0; } if((n=z.avail_in)==0) return Z_BUF_ERROR; p=z.next_in_index; m=z.istate.marker; // search while (n!=0 && m < 4){ if(z.next_in[p] == mark[m]){ m++; } else if(z.next_in[p]!=0){ m = 0; } else{ m = 4 - m; } p++; n--; } // restore z.total_in += p-z.next_in_index; z.next_in_index = p; z.avail_in = n; z.istate.marker = m; // return no joy or set up to restart on a new block if(m != 4){ return Z_DATA_ERROR; } r=z.total_in; w=z.total_out; inflateReset(z); z.total_in=r; z.total_out = w; z.istate.mode = BLOCKS; return Z_OK; } // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP // implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH // but removes the length bytes of the resulting empty stored block. When // decompressing, PPP checks that at the end of input packet, inflate is // waiting for these length bytes. internal int inflateSyncPoint(ZStream z){ if(z == null || z.istate == null || z.istate.blocks == null) return Z_STREAM_ERROR; return z.istate.blocks.sync_point(); } } }
using LynkAdventures.Controls; using LynkAdventures.Entities; using LynkAdventures.Graphics; using LynkAdventures.Gui; using LynkAdventures.Sounds; using LynkAdventures.World; using LynkAdventures.World.Rooms; using LynkAdventures.World.Tiles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using SharpNeatLib.Maths; using System; namespace LynkAdventures { /// <summary> /// Game's main class. /// </summary> /// @author Denis Zhidkikh /// @version 6.4.2013 public class Game : Microsoft.Xna.Framework.Game { public const int SCALE = 2; public const int WIDTH = 800; public const int HEIGHT = 600; public const string TITLE = "The Adventures of Lynk"; public const string VERSION = "Beta 1.5.2"; private GraphicsDeviceManager graphics; private SpriteBatch spriteBatch; private Renderer renderer; private bool isGameLoaded = false; #region Timer (FPS) private int lastSecond = DateTime.Now.Second; private int frames = 0; private int frameCounter = 0; private TimeSpan elapsedTime = TimeSpan.Zero; /// <summary> /// Gets frames per second. /// </summary> /// <value> /// The frames per second. /// </value> public int FPS { get { return frames; } } #endregion private LevelManager levelManager; private static GuiManager guiManager; private EntityPlayer player; private static Camera camera; private GuiDebug debugGui; private GuiMainMenu mainMenu; private static GuiDeath deathMenu; private KeyboardHandler keyboardHandler; /// <summary> /// Gets the death message. /// </summary> /// <value> /// The death message GUI. /// </value> public static GuiDeath DeathMenu { get { return deathMenu; } } /// <summary> /// Gets a value indicating whether the game is loaded and playable. /// </summary> /// <value> /// <c>true</c> if the game is loaded; otherwise, <c>false</c>. /// </value> public bool IsGameLoaded { get { return isGameLoaded; } } /// <summary> /// Gets the instance of the level manager responsible for loading and updating all the levels in the game. /// </summary> /// <value> /// The level manager instance. /// </value> public LevelManager LevelManager { get { return levelManager; } } /// <summary> /// Gets the camera instance. /// </summary> /// <value> /// The camera instance. /// </value> public static Camera Camera { get { return camera; } } /// <summary> /// Gets the random number generator instance. /// </summary> /// <value> /// The random number generator. /// </value> public static FastRandom Random { get; private set; } /// <summary> /// Gets the GUI manager responsible for updating and rendering all the registered GUIs in the game. /// </summary> /// <value> /// The GUI manager instance. /// </value> public static GuiManager GuiManager { get { return guiManager; } } public static int LEVEL_FOREST { get; private set; } public static int LEVEL_DUNGEON { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Game"/> class. /// </summary> public Game() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; levelManager = new LevelManager(0); Random = new FastRandom(); } /// <summary> /// Called after the Game and GraphicsDevice are created, but before LoadContent. /// </summary> protected override void Initialize() { base.Initialize(); Window.Title = TITLE + " " + VERSION; IsMouseVisible = true; graphics.PreferredBackBufferWidth = WIDTH; graphics.PreferredBackBufferHeight = HEIGHT; Window.AllowUserResizing = false; graphics.SynchronizeWithVerticalRetrace = false; graphics.ApplyChanges(); keyboardHandler = new KeyboardHandler(); InitKeys(); StartMainMenu(); } /// <summary> /// Registers the keys needed used in the game. /// </summary> private void InitKeys() { keyboardHandler.RegisterKey(Keys.F3); keyboardHandler.RegisterKey(Keys.F4); keyboardHandler.RegisterKey(Keys.Escape); keyboardHandler.RegisterKey(Keys.Space); keyboardHandler.RegisterKey(Keys.LeftShift); keyboardHandler.RegisterKey(Keys.LeftControl); keyboardHandler.RegisterKey(Keys.E); keyboardHandler.RegisterKey(Keys.W); keyboardHandler.RegisterKey(Keys.A); keyboardHandler.RegisterKey(Keys.S); keyboardHandler.RegisterKey(Keys.D); keyboardHandler.RegisterKey(Keys.Down); keyboardHandler.RegisterKey(Keys.Up); keyboardHandler.RegisterKey(Keys.Enter); } /// <summary> /// Loads all the resources used in the game. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); renderer = new Renderer(spriteBatch, GraphicsDevice); guiManager = new GuiManager(renderer, GraphicsDevice, Content); GameSpriteSheets.LoadSpriteSheets(this.Content, renderer); Sound.LoadSounds(this.Content); Shaders.LoadShaders(this.Content, renderer); RoomTileMaps.LoadRooms(this.Content); } /// <summary> /// Ends current game and returns to the main menu. /// </summary> public void StartMainMenu() { levelManager = new LevelManager(0); guiManager = new GuiManager(renderer, GraphicsDevice, Content); mainMenu = new GuiMainMenu(this); System.GC.Collect(); isGameLoaded = false; guiManager.LoadAsActiveGui(mainMenu); } /// <summary> /// Reinitializes all the game components (except resources and GuiManager) and starts the game. /// </summary> public void StartGame() { guiManager = new GuiManager(renderer, GraphicsDevice, Content); levelManager = new LevelManager(0); LevelForest forest = new LevelForest(this.Content.Load<Texture2D>("Levels/level1"), levelManager); LevelDungeon1 ld = new LevelDungeon1(this.Content.Load<Texture2D>("Levels/dungeon1"), levelManager); LEVEL_FOREST = levelManager.AddLevel(forest); LEVEL_DUNGEON = levelManager.AddLevel(ld); levelManager.InitAllLevels(); player = new EntityPlayer(levelManager); levelManager.CurrentLevel.AddEntity(player, 0, 0); camera = new Camera(0, 0, this, new Point(0, 0), new Point(levelManager.CurrentLevel.Width * Tile.TILESIZE, levelManager.CurrentLevel.Height * Tile.TILESIZE)); camera.FollowEntity(player); guiManager.LoadGui(new GuiIngame(player)); debugGui = new GuiDebug(100, 100, new Point(0, 0), this, player); guiManager.LoadGui(debugGui, false); deathMenu = new GuiDeath(this); isGameLoaded = true; } /// <summary> /// Updates the game. /// </summary> /// <param name="gameTime">Time passed since the last call to Update.</param> protected override void Update(GameTime gameTime) { keyboardHandler.Update(); if (KeyboardHandler.IsKeyPressed(Keys.Escape)) if (IsGameLoaded && !mainMenu.IsActive && !deathMenu.IsActive) mainMenu.Activate(true); if (isGameLoaded) { if (!GuiManager.HasActiveGui) levelManager.CurrentLevel.Update(); if (KeyboardHandler.IsKeyPressed(Keys.F3)) { if (!debugGui.IsActive) debugGui.Activate(); else debugGui.Close(); } if (KeyboardHandler.IsKeyPressed(Keys.F4)) IsFixedTimeStep = !IsFixedTimeStep; } GuiManager.Update(); elapsedTime += gameTime.ElapsedGameTime; if (elapsedTime > TimeSpan.FromSeconds(1)) { elapsedTime -= TimeSpan.FromSeconds(1); frames = frameCounter; frameCounter = 0; } base.Update(gameTime); } /// <summary> /// Draws everything on the screen. /// </summary> /// <param name="gameTime">Time passed since the last call to Draw.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); GraphicsDevice.Textures[0] = null; GraphicsDevice.SetRenderTarget(null); renderer.BeginRender(); if (isGameLoaded) { camera.Update(); levelManager.RenderLevel(camera, renderer); } GuiManager.RenderGuis(); renderer.EndRender(); frameCounter++; base.Draw(gameTime); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; #pragma warning disable 618 // obsolete types namespace System.Collections.Tests { public class HashtableTests : RemoteExecutorTestBase { [Fact] public void Ctor_Empty() { var hash = new ComparableHashtable(); VerifyHashtable(hash, null, null); } [Fact] public void Ctor_HashCodeProvider_Comparer() { var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash, null, hash.EqualityComparer); Assert.Same(CaseInsensitiveHashCodeProvider.DefaultInvariant, hash.HashCodeProvider); Assert.Same(StringComparer.OrdinalIgnoreCase, hash.Comparer); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] public void Ctor_HashCodeProvider_Comparer_NullInputs(bool nullProvider, bool nullComparer) { var hash = new ComparableHashtable( nullProvider ? null : CaseInsensitiveHashCodeProvider.DefaultInvariant, nullComparer ? null : StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash, null, hash.EqualityComparer); } [Fact] public void Ctor_IDictionary() { // No exception var hash1 = new ComparableHashtable(new Hashtable()); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable()))))); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2); VerifyHashtable(hash1, hash2, null); } [Fact] public void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null)); // Dictionary is null } [Fact] public void Ctor_IDictionary_HashCodeProvider_Comparer() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable())))), CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash1, hash2, hash1.EqualityComparer); } [Fact] public void Ctor_IDictionary_HashCodeProvider_Comparer_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, CaseInsensitiveHashCodeProvider.Default, StringComparer.OrdinalIgnoreCase)); // Dictionary is null } [Fact] public void Ctor_IEqualityComparer() { RemoteInvoke(() => { // Null comparer var hash = new ComparableHashtable((IEqualityComparer)null); VerifyHashtable(hash, null, null); // Custom comparer IEqualityComparer comparer = StringComparer.CurrentCulture; hash = new ComparableHashtable(comparer); VerifyHashtable(hash, null, comparer); return SuccessExitCode; }).Dispose(); } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] public void Ctor_Int(int capacity) { var hash = new ComparableHashtable(capacity); VerifyHashtable(hash, null, null); } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] public void Ctor_Int_HashCodeProvider_Comparer(int capacity) { var hash = new ComparableHashtable(capacity, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash, null, hash.EqualityComparer); } [Fact] public void Ctor_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1)); // Capacity < 0 AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue)); // Capacity / load factor > int.MaxValue } [Fact] public void Ctor_IDictionary_Int() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash1, hash2, hash1.EqualityComparer); } [Fact] public void Ctor_IDictionary_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f)); // Dictionary is null AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f)); // Load factor < 0.1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f)); // Load factor > 1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN)); // Load factor is NaN AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity)); // Load factor is infinity AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity)); // Load factor is infinity } [Fact] public void Ctor_IDictionary_Int_HashCodeProvider_Comparer() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), 1f); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, 1f); VerifyHashtable(hash1, hash2, null); } [Fact] public void Ctor_IDictionary_IEqualityComparer() { RemoteInvoke(() => { // No exception var hash1 = new ComparableHashtable(new Hashtable(), null); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), null), null), null), null), null); Assert.Equal(0, hash1.Count); // Null comparer Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, null); VerifyHashtable(hash1, hash2, null); // Custom comparer hash2 = Helpers.CreateIntHashtable(100); IEqualityComparer comparer = StringComparer.CurrentCulture; hash1 = new ComparableHashtable(hash2, comparer); VerifyHashtable(hash1, hash2, comparer); return SuccessExitCode; }).Dispose(); } [Fact] public void Ctor_IDictionary_IEqualityComparer_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null, null)); // Dictionary is null } [Theory] [InlineData(0, 0.1)] [InlineData(10, 0.2)] [InlineData(100, 0.3)] [InlineData(1000, 1)] public void Ctor_Int_Int(int capacity, float loadFactor) { var hash = new ComparableHashtable(capacity, loadFactor); VerifyHashtable(hash, null, null); } [Theory] [InlineData(0, 0.1)] [InlineData(10, 0.2)] [InlineData(100, 0.3)] [InlineData(1000, 1)] public void Ctor_Int_Int_HashCodeProvider_Comparer(int capacity, float loadFactor) { var hash = new ComparableHashtable(capacity, loadFactor, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash, null, hash.EqualityComparer); } [Fact] public void Ctor_Int_Int_GenerateNewPrime() { // The ctor for Hashtable performs the following calculation: // rawSize = capacity / (loadFactor * 0.72) // If rawSize is > 3, then it calls HashHelpers.GetPrime(rawSize) to generate a prime. // Then, if the rawSize > 7,199,369 (the largest number in a list of known primes), we have to generate a prime programatically // This test makes sure this works. int capacity = 8000000; float loadFactor = 0.1f / 0.72f; try { var hash = new ComparableHashtable(capacity, loadFactor); } catch (OutOfMemoryException) { // On memory constrained devices, we can get an OutOfMemoryException, which we can safely ignore. } } [Fact] public void Ctor_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f)); // Capacity < 0 AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, 0.1f)); // Capacity / load factor > int.MaxValue AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f)); // Load factor < 0.1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f)); // Load factor > 1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN)); // Load factor is NaN AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity)); // Load factor is infinity AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity)); // Load factor is infinity } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public void Ctor_Int_IEqualityComparer(int capacity) { RemoteInvoke((rcapacity) => { int.TryParse(rcapacity, out int capacityint); // Null comparer var hash = new ComparableHashtable(capacityint, null); VerifyHashtable(hash, null, null); // Custom comparer IEqualityComparer comparer = StringComparer.CurrentCulture; hash = new ComparableHashtable(capacityint, comparer); VerifyHashtable(hash, null, comparer); return SuccessExitCode; }, capacity.ToString()).Dispose(); } [Fact] public void Ctor_Int_IEqualityComparer_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, null)); // Capacity < 0 AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, null)); // Capacity / load factor > int.MaxValue } [Fact] public void Ctor_IDictionary_Int_IEqualityComparer() { RemoteInvoke(() => { // No exception var hash1 = new ComparableHashtable(new Hashtable(), 1f, null); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable( new Hashtable(new Hashtable(new Hashtable(), 1f, null), 1f, null), 1f, null), 1f, null), 1f, null); Assert.Equal(0, hash1.Count); // Null comparer Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, 1f, null); VerifyHashtable(hash1, hash2, null); hash2 = Helpers.CreateIntHashtable(100); // Custom comparer IEqualityComparer comparer = StringComparer.CurrentCulture; hash1 = new ComparableHashtable(hash2, 1f, comparer); VerifyHashtable(hash1, hash2, comparer); return SuccessExitCode; }).Dispose(); } [Fact] public void Ctor_IDictionary_LoadFactor_IEqualityComparer_Invalid() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f, null)); // Dictionary is null AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f, null)); // Load factor < 0.1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f, null)); // Load factor > 1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN, null)); // Load factor is NaN AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity, null)); // Load factor is infinity AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity, null)); // Load factor is infinity } [Theory] [InlineData(0, 0.1)] [InlineData(10, 0.2)] [InlineData(100, 0.3)] [InlineData(1000, 1)] public void Ctor_Int_Int_IEqualityComparer(int capacity, float loadFactor) { RemoteInvoke((rcapacity, rloadFactor) => { int.TryParse(rcapacity, out int capacityint); float.TryParse(rloadFactor, out float loadFactorFloat); // Null comparer var hash = new ComparableHashtable(capacityint, loadFactorFloat, null); VerifyHashtable(hash, null, null); Assert.Null(hash.EqualityComparer); // Custom compare IEqualityComparer comparer = StringComparer.CurrentCulture; hash = new ComparableHashtable(capacityint, loadFactorFloat, comparer); VerifyHashtable(hash, null, comparer); return SuccessExitCode; }, capacity.ToString(), loadFactor.ToString()).Dispose(); } [Fact] public void Ctor_Capacity_LoadFactor_IEqualityComparer_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f, null)); // Capacity < 0 AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, 0.1f, null)); // Capacity / load factor > int.MaxValue AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f, null)); // Load factor < 0.1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f, null)); // Load factor > 1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN, null)); // Load factor is NaN AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity, null)); // Load factor is infinity AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity, null)); // Load factor is infinity } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttribute() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new Hashtable()); var hash = new Hashtable() { { "a", 1 }, { "b", 2 } }; DebuggerAttributes.ValidateDebuggerTypeProxyProperties(hash); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), Hashtable.Synchronized(hash)); bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Fact] public void Add_ReferenceType() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { // Value is a reference var foo = new Foo(); hash2.Add("Key", foo); Assert.Equal("Hello World", ((Foo)hash2["Key"]).StringValue); // Changing original object should change the object stored in the Hashtable foo.StringValue = "Goodbye"; Assert.Equal("Goodbye", ((Foo)hash2["Key"]).StringValue); }); } [Fact] public void Add_ClearRepeatedly() { const int Iterations = 2; const int Count = 2; var hash = new Hashtable(); for (int i = 0; i < Iterations; i++) { for (int j = 0; j < Count; j++) { string key = "Key: i=" + i + ", j=" + j; string value = "Value: i=" + i + ", j=" + j; hash.Add(key, value); } Assert.Equal(Count, hash.Count); hash.Clear(); } } [Fact] [OuterLoop] public void AddRemove_LargeAmountNumbers() { // Generate a random 100,000 array of ints as test data var inputData = new int[100000]; var random = new Random(341553); for (int i = 0; i < inputData.Length; i++) { inputData[i] = random.Next(7500000, int.MaxValue); } var hash = new Hashtable(); int count = 0; foreach (long number in inputData) { hash.Add(number, count++); } count = 0; foreach (long number in inputData) { Assert.Equal(hash[number], count); Assert.True(hash.ContainsKey(number)); count++; } foreach (long number in inputData) { hash.Remove(number); } Assert.Equal(0, hash.Count); } [Fact] public void DuplicatedKeysWithInitialCapacity() { // Make rehash get called because to many items with duplicated keys have been added to the hashtable var hash = new Hashtable(200); const int Iterations = 1600; for (int i = 0; i < Iterations; i += 2) { hash.Add(new BadHashCode(i), i.ToString()); hash.Add(new BadHashCode(i + 1), (i + 1).ToString()); hash.Remove(new BadHashCode(i)); hash.Remove(new BadHashCode(i + 1)); } for (int i = 0; i < Iterations; i++) { hash.Add(i.ToString(), i); } for (int i = 0; i < Iterations; i++) { Assert.Equal(i, hash[i.ToString()]); } } [Fact] public void DuplicatedKeysWithDefaultCapacity() { // Make rehash get called because to many items with duplicated keys have been added to the hashtable var hash = new Hashtable(); const int Iterations = 1600; for (int i = 0; i < Iterations; i += 2) { hash.Add(new BadHashCode(i), i.ToString()); hash.Add(new BadHashCode(i + 1), (i + 1).ToString()); hash.Remove(new BadHashCode(i)); hash.Remove(new BadHashCode(i + 1)); } for (int i = 0; i < Iterations; i++) { hash.Add(i.ToString(), i); } for (int i = 0; i < Iterations; i++) { Assert.Equal(i, hash[i.ToString()]); } } [Theory] [InlineData(0)] [InlineData(100)] public void Clone(int count) { Hashtable hash1 = Helpers.CreateStringHashtable(count); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { Hashtable clone = (Hashtable)hash2.Clone(); Assert.Equal(hash2.Count, clone.Count); Assert.Equal(hash2.IsSynchronized, clone.IsSynchronized); Assert.Equal(hash2.IsFixedSize, clone.IsFixedSize); Assert.Equal(hash2.IsReadOnly, clone.IsReadOnly); for (int i = 0; i < clone.Count; i++) { string key = "Key_" + i; string value = "Value_" + i; Assert.True(clone.ContainsKey(key)); Assert.True(clone.ContainsValue(value)); Assert.Equal(value, clone[key]); } }); } [Fact] public void Clone_IsShallowCopy() { var hash = new Hashtable(); for (int i = 0; i < 10; i++) { hash.Add(i, new Foo()); } Hashtable clone = (Hashtable)hash.Clone(); for (int i = 0; i < clone.Count; i++) { Assert.Equal("Hello World", ((Foo)clone[i]).StringValue); Assert.Same(hash[i], clone[i]); } // Change object in original hashtable ((Foo)hash[1]).StringValue = "Goodbye"; Assert.Equal("Goodbye", ((Foo)clone[1]).StringValue); // Removing an object from the original hashtable doesn't change the clone hash.Remove(0); Assert.True(clone.Contains(0)); } [Fact] public void Clone_HashtableCastedToInterfaces() { // Try to cast the returned object from Clone() to different types Hashtable hash = Helpers.CreateIntHashtable(100); ICollection collection = (ICollection)hash.Clone(); Assert.Equal(hash.Count, collection.Count); IDictionary dictionary = (IDictionary)hash.Clone(); Assert.Equal(hash.Count, dictionary.Count); } [Fact] public void ContainsKey() { Hashtable hash1 = Helpers.CreateStringHashtable(100); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { for (int i = 0; i < hash2.Count; i++) { string key = "Key_" + i; Assert.True(hash2.ContainsKey(key)); Assert.True(hash2.Contains(key)); } Assert.False(hash2.ContainsKey("Non Existent Key")); Assert.False(hash2.Contains("Non Existent Key")); Assert.False(hash2.ContainsKey(101)); Assert.False(hash2.Contains("Non Existent Key")); string removedKey = "Key_1"; hash2.Remove(removedKey); Assert.False(hash2.ContainsKey(removedKey)); Assert.False(hash2.Contains(removedKey)); }); } [Fact] public void ContainsKey_EqualObjects() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { var foo1 = new Foo() { StringValue = "Goodbye" }; var foo2 = new Foo() { StringValue = "Goodbye" }; hash2.Add(foo1, 101); Assert.True(hash2.ContainsKey(foo2)); Assert.True(hash2.Contains(foo2)); int i1 = 0x10; int i2 = 0x100; long l1 = (((long)i1) << 32) + i2; // Create two longs with same hashcode long l2 = (((long)i2) << 32) + i1; hash2.Add(l1, 101); hash2.Add(l2, 101); // This will cause collision bit of the first entry to be set Assert.True(hash2.ContainsKey(l1)); Assert.True(hash2.Contains(l1)); hash2.Remove(l1); // Remove the first item Assert.False(hash2.ContainsKey(l1)); Assert.False(hash2.Contains(l1)); Assert.True(hash2.ContainsKey(l2)); Assert.True(hash2.Contains(l2)); }); } [Fact] public void ContainsKey_NullKey_ThrowsArgumentNullException() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => hash2.ContainsKey(null)); // Key is null AssertExtensions.Throws<ArgumentNullException>("key", () => hash2.Contains(null)); // Key is null }); } [Fact] public void ContainsValue() { Hashtable hash1 = Helpers.CreateStringHashtable(100); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { for (int i = 0; i < hash2.Count; i++) { string value = "Value_" + i; Assert.True(hash2.ContainsValue(value)); } Assert.False(hash2.ContainsValue("Non Existent Value")); Assert.False(hash2.ContainsValue(101)); Assert.False(hash2.ContainsValue(null)); hash2.Add("Key_101", null); Assert.True(hash2.ContainsValue(null)); string removedKey = "Key_1"; string removedValue = "Value_1"; hash2.Remove(removedKey); Assert.False(hash2.ContainsValue(removedValue)); }); } [Fact] public void ContainsValue_EqualObjects() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { var foo1 = new Foo() { StringValue = "Goodbye" }; var foo2 = new Foo() { StringValue = "Goodbye" }; hash2.Add(101, foo1); Assert.True(hash2.ContainsValue(foo2)); }); } [Fact] public void Keys_ModifyingHashtable_ModifiesCollection() { Hashtable hash = Helpers.CreateStringHashtable(100); ICollection keys = hash.Keys; // Removing a key from the hashtable should update the Keys ICollection. // This means that the Keys ICollection no longer contains the key. hash.Remove("Key_0"); IEnumerator enumerator = keys.GetEnumerator(); while (enumerator.MoveNext()) { Assert.NotEqual("Key_0", enumerator.Current); } } [Fact] public void Remove_SameHashcode() { // We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable // does not expand but have to tread through collision bit set positions to insert the new elements. We do this // by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that // the hashtable does not expand as long as we have at most 7 elements at any given time? var hash = new Hashtable(); var arrList = new ArrayList(); for (int i = 0; i < 7; i++) { var hashConfuse = new BadHashCode(i); arrList.Add(hashConfuse); hash.Add(hashConfuse, i); } var rand = new Random(-55); int iCount = 7; for (int i = 0; i < 100; i++) { for (int j = 0; j < 7; j++) { Assert.Equal(hash[arrList[j]], ((BadHashCode)arrList[j]).Value); } // Delete 3 elements from the hashtable for (int j = 0; j < 3; j++) { int iElement = rand.Next(6); hash.Remove(arrList[iElement]); Assert.False(hash.ContainsValue(null)); arrList.RemoveAt(iElement); int testInt = iCount++; var hashConfuse = new BadHashCode(testInt); arrList.Add(hashConfuse); hash.Add(hashConfuse, testInt); } } } [Fact] public void SynchronizedProperties() { // Ensure Synchronized correctly reflects a wrapped hashtable var hash1 = Helpers.CreateStringHashtable(100); var hash2 = Hashtable.Synchronized(hash1); Assert.Equal(hash1.Count, hash2.Count); Assert.Equal(hash1.IsReadOnly, hash2.IsReadOnly); Assert.Equal(hash1.IsFixedSize, hash2.IsFixedSize); Assert.True(hash2.IsSynchronized); Assert.Equal(hash1.SyncRoot, hash2.SyncRoot); for (int i = 0; i < hash2.Count; i++) { Assert.Equal("Value_" + i, hash2["Key_" + i]); } } [Fact] public void Synchronized_NullTable_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("table", () => Hashtable.Synchronized(null)); // Table is null } [Fact] public void Values_ModifyingHashtable_ModifiesCollection() { Hashtable hash = Helpers.CreateStringHashtable(100); ICollection values = hash.Values; // Removing a value from the hashtable should update the Values ICollection. // This means that the Values ICollection no longer contains the value. hash.Remove("Key_0"); IEnumerator enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) { Assert.NotEqual("Value_0", enumerator.Current); } } [Fact] public void HashCodeProvider_Set_ImpactsSearch() { var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); hash.Add("test", "test"); // Should be able to find with the same and different casing Assert.True(hash.ContainsKey("test")); Assert.True(hash.ContainsKey("TEST")); // Changing the hash code provider, we shouldn't be able to find either hash.HashCodeProvider = new FixedHashCodeProvider { FixedHashCode = CaseInsensitiveHashCodeProvider.DefaultInvariant.GetHashCode("test") + 1 }; Assert.False(hash.ContainsKey("test")); Assert.False(hash.ContainsKey("TEST")); // Changing it back, should be able to find both again hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant; Assert.True(hash.ContainsKey("test")); Assert.True(hash.ContainsKey("TEST")); } [Fact] public void HashCodeProvider_Comparer_CompatibleGetSet_Success() { var hash = new ComparableHashtable(); Assert.Null(hash.HashCodeProvider); Assert.Null(hash.Comparer); hash = new ComparableHashtable(); hash.HashCodeProvider = null; hash.Comparer = null; hash = new ComparableHashtable(); hash.Comparer = null; hash.HashCodeProvider = null; hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant; hash.Comparer = StringComparer.OrdinalIgnoreCase; } [Fact] public void HashCodeProvider_Comparer_IncompatibleGetSet_Throws() { var hash = new ComparableHashtable(StringComparer.CurrentCulture); AssertExtensions.Throws<ArgumentException>(null, () => hash.HashCodeProvider); AssertExtensions.Throws<ArgumentException>(null, () => hash.Comparer); AssertExtensions.Throws<ArgumentException>(null, () => hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant); AssertExtensions.Throws<ArgumentException>(null, () => hash.Comparer = StringComparer.OrdinalIgnoreCase); } [Fact] public void Comparer_Set_ImpactsSearch() { var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); hash.Add("test", "test"); // Should be able to find with the same and different casing Assert.True(hash.ContainsKey("test")); Assert.True(hash.ContainsKey("TEST")); // Changing the comparer, should only be able to find the matching case hash.Comparer = StringComparer.Ordinal; Assert.True(hash.ContainsKey("test")); Assert.False(hash.ContainsKey("TEST")); // Changing it back, should be able to find both again hash.Comparer = StringComparer.OrdinalIgnoreCase; Assert.True(hash.ContainsKey("test")); Assert.True(hash.ContainsKey("TEST")); } private class FixedHashCodeProvider : IHashCodeProvider { public int FixedHashCode; public int GetHashCode(object obj) => FixedHashCode; } private static void VerifyHashtable(ComparableHashtable hash1, Hashtable hash2, IEqualityComparer ikc) { if (hash2 == null) { Assert.Equal(0, hash1.Count); } else { // Make sure that construtor imports all keys and values Assert.Equal(hash2.Count, hash1.Count); for (int i = 0; i < 100; i++) { Assert.True(hash1.ContainsKey(i)); Assert.True(hash1.ContainsValue(i)); } // Make sure the new and old hashtables are not linked hash2.Clear(); for (int i = 0; i < 100; i++) { Assert.True(hash1.ContainsKey(i)); Assert.True(hash1.ContainsValue(i)); } } Assert.Equal(ikc, hash1.EqualityComparer); Assert.False(hash1.IsFixedSize); Assert.False(hash1.IsReadOnly); Assert.False(hash1.IsSynchronized); // Make sure we can add to the hashtable int count = hash1.Count; for (int i = count; i < count + 100; i++) { hash1.Add(i, i); Assert.True(hash1.ContainsKey(i)); Assert.True(hash1.ContainsValue(i)); } } private class ComparableHashtable : Hashtable { public ComparableHashtable() : base() { } public ComparableHashtable(int capacity) : base(capacity) { } public ComparableHashtable(int capacity, float loadFactor) : base(capacity, loadFactor) { } public ComparableHashtable(int capacity, IHashCodeProvider hcp, IComparer comparer) : base(capacity, hcp, comparer) { } public ComparableHashtable(int capacity, IEqualityComparer ikc) : base(capacity, ikc) { } public ComparableHashtable(IHashCodeProvider hcp, IComparer comparer) : base(hcp, comparer) { } public ComparableHashtable(IEqualityComparer ikc) : base(ikc) { } public ComparableHashtable(IDictionary d) : base(d) { } public ComparableHashtable(IDictionary d, float loadFactor) : base(d, loadFactor) { } public ComparableHashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer) : base(d, hcp, comparer) { } public ComparableHashtable(IDictionary d, IEqualityComparer ikc) : base(d, ikc) { } public ComparableHashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : base(d, loadFactor, hcp, comparer) { } public ComparableHashtable(IDictionary d, float loadFactor, IEqualityComparer ikc) : base(d, loadFactor, ikc) { } public ComparableHashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : base(capacity, loadFactor, hcp, comparer) { } public ComparableHashtable(int capacity, float loadFactor, IEqualityComparer ikc) : base(capacity, loadFactor, ikc) { } public new IEqualityComparer EqualityComparer => base.EqualityComparer; public IHashCodeProvider HashCodeProvider { get { return hcp; } set { hcp = value; } } public IComparer Comparer { get { return comparer; } set { comparer = value; } } } private class BadHashCode { public BadHashCode(int value) { Value = value; } public int Value { get; private set; } public override bool Equals(object o) { BadHashCode rhValue = o as BadHashCode; if (rhValue != null) { return Value.Equals(rhValue.Value); } else { throw new ArgumentException("is not BadHashCode type actual " + o.GetType(), nameof(o)); } } // Return 0 for everything to force hash collisions. public override int GetHashCode() => 0; public override string ToString() => Value.ToString(); } private class Foo { public string StringValue { get; set; } = "Hello World"; public override bool Equals(object obj) { Foo foo = obj as Foo; return foo != null && StringValue == foo.StringValue; } public override int GetHashCode() => StringValue.GetHashCode(); } } /// <summary> /// A hashtable can have a race condition: /// A read operation on hashtable has three steps: /// (1) calculate the hash and find the slot number. /// (2) compare the hashcode, if equal, go to step 3. Otherwise end. /// (3) compare the key, if equal, go to step 4. Otherwise end. /// (4) return the value contained in the bucket. /// The problem is that after step 3 and before step 4. A writer can kick in a remove the old item and add a new one /// in the same bukcet. In order to make this happen easily, I created two long with same hashcode. /// </summary> public class Hashtable_ItemThreadSafetyTests { private object _key1; private object _key2; private object _value1 = "value1"; private object _value2 = "value2"; private Hashtable _hash; private bool _errorOccurred = false; private bool _timeExpired = false; private const int MAX_TEST_TIME_MS = 10000; // 10 seconds [Fact] [OuterLoop] public void GetItem_ThreadSafety() { int i1 = 0x10; int i2 = 0x100; // Setup key1 and key2 so they are different values but have the same hashcode // To produce a hashcode long XOR's the first 32bits with the last 32 bits long l1 = (((long)i1) << 32) + i2; long l2 = (((long)i2) << 32) + i1; _key1 = l1; _key2 = l2; _hash = new Hashtable(3); // Just one item will be in the hashtable at a time int taskCount = 3; var readers1 = new Task[taskCount]; var readers2 = new Task[taskCount]; Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = 0; i < readers1.Length; i++) { readers1[i] = Task.Run(new Action(ReaderFunction1)); } for (int i = 0; i < readers2.Length; i++) { readers2[i] = Task.Run(new Action(ReaderFunction2)); } Task writer = Task.Run(new Action(WriterFunction)); var spin = new SpinWait(); while (!_errorOccurred && !_timeExpired) { if (MAX_TEST_TIME_MS < stopwatch.ElapsedMilliseconds) { _timeExpired = true; } spin.SpinOnce(); } Task.WaitAll(readers1); Task.WaitAll(readers2); writer.Wait(); Assert.False(_errorOccurred); } private void ReaderFunction1() { while (!_timeExpired) { object value = _hash[_key1]; if (value != null) { Assert.NotEqual(value, _value2); } } } private void ReaderFunction2() { while (!_errorOccurred && !_timeExpired) { object value = _hash[_key2]; if (value != null) { Assert.NotEqual(value, _value1); } } } private void WriterFunction() { while (!_errorOccurred && !_timeExpired) { _hash.Add(_key1, _value1); _hash.Remove(_key1); _hash.Add(_key2, _value2); _hash.Remove(_key2); } } } public class Hashtable_SynchronizedTests { private Hashtable _hash2; private int _iNumberOfElements = 20; [Fact] [OuterLoop] public void SynchronizedThreadSafety() { const int NumberOfWorkers = 3; // Synchronized returns a hashtable that is thread safe // We will try to test this by getting a number of threads to write some items // to a synchronized IList var hash1 = new Hashtable(); _hash2 = Hashtable.Synchronized(hash1); var workers = new Task[NumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { var name = "Thread worker " + i; var task = new Action(() => AddElements(name)); workers[i] = Task.Run(task); } Task.WaitAll(workers); // Check time Assert.Equal(_hash2.Count, _iNumberOfElements * NumberOfWorkers); for (int i = 0; i < NumberOfWorkers; i++) { for (int j = 0; j < _iNumberOfElements; j++) { string strValue = "Thread worker " + i + "_" + j; Assert.True(_hash2.Contains(strValue)); } } // We cannot can make an assumption on the order of these items but // now we are going to remove all of these workers = new Task[NumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { string name = "Thread worker " + i; var task = new Action(() => RemoveElements(name)); workers[i] = Task.Run(task); } Task.WaitAll(workers); Assert.Equal(_hash2.Count, 0); } private void AddElements(string strName) { for (int i = 0; i < _iNumberOfElements; i++) { _hash2.Add(strName + "_" + i, "string_" + i); } } private void RemoveElements(string strName) { for (int i = 0; i < _iNumberOfElements; i++) { _hash2.Remove(strName + "_" + i); } } } public class Hashtable_SyncRootTests { private Hashtable _hashDaughter; private Hashtable _hashGrandDaughter; private const int NumberOfElements = 100; [Fact] public void SyncRoot() { // Different hashtables have different SyncRoots var hash1 = new Hashtable(); var hash2 = new Hashtable(); Assert.NotEqual(hash1.SyncRoot, hash2.SyncRoot); Assert.Equal(hash1.SyncRoot.GetType(), typeof(object)); // Cloned hashtables have different SyncRoots hash1 = new Hashtable(); hash2 = Hashtable.Synchronized(hash1); Hashtable hash3 = (Hashtable)hash2.Clone(); Assert.NotEqual(hash2.SyncRoot, hash3.SyncRoot); Assert.NotEqual(hash1.SyncRoot, hash3.SyncRoot); // Testing SyncRoot is not as simple as its implementation looks like. This is the working // scenario we have in mind. // 1) Create your Down to earth mother Hashtable // 2) Get a synchronized wrapper from it // 3) Get a Synchronized wrapper from 2) // 4) Get a synchronized wrapper of the mother from 1) // 5) all of these should SyncRoot to the mother earth var hashMother = new Hashtable(); for (int i = 0; i < NumberOfElements; i++) { hashMother.Add("Key_" + i, "Value_" + i); } Hashtable hashSon = Hashtable.Synchronized(hashMother); _hashGrandDaughter = Hashtable.Synchronized(hashSon); _hashDaughter = Hashtable.Synchronized(hashMother); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); Assert.Equal(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot); Assert.Equal(_hashDaughter.SyncRoot, hashMother.SyncRoot); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); // We are going to rumble with the Hashtables with some threads int iNumberOfWorkers = 30; var workers = new Task[iNumberOfWorkers]; var ts2 = new Action(RemoveElements); for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2) { var name = "Thread_worker_" + iThreads; var ts1 = new Action(() => AddMoreElements(name)); workers[iThreads] = Task.Run(ts1); workers[iThreads + 1] = Task.Run(ts2); } Task.WaitAll(workers); // Check: // Either there should be some elements (the new ones we added and/or the original ones) or none var hshPossibleValues = new Hashtable(); for (int i = 0; i < NumberOfElements; i++) { hshPossibleValues.Add("Key_" + i, "Value_" + i); } for (int i = 0; i < iNumberOfWorkers; i++) { hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i); } IDictionaryEnumerator idic = hashMother.GetEnumerator(); while (idic.MoveNext()) { Assert.True(hshPossibleValues.ContainsKey(idic.Key)); Assert.True(hshPossibleValues.ContainsValue(idic.Value)); } } private void AddMoreElements(string threadName) { _hashGrandDaughter.Add("Key_" + threadName, threadName); } private void RemoveElements() { _hashDaughter.Clear(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using OrchardCore.Modules; using OrchardCore.Security.Services; using OrchardCore.Users.Handlers; using OrchardCore.Users.Indexes; using OrchardCore.Users.Models; using YesSql; namespace OrchardCore.Users.Services { public class UserStore : IUserClaimStore<IUser>, IUserRoleStore<IUser>, IUserPasswordStore<IUser>, IUserEmailStore<IUser>, IUserSecurityStampStore<IUser>, IUserLoginStore<IUser>, IUserAuthenticationTokenStore<IUser> { private const string TokenProtector = "OrchardCore.UserStore.Token"; private readonly ISession _session; private readonly IRoleService _roleService; private readonly ILookupNormalizer _keyNormalizer; private readonly ILogger _logger; private readonly IDataProtectionProvider _dataProtectionProvider; public UserStore(ISession session, IRoleService roleService, ILookupNormalizer keyNormalizer, ILogger<UserStore> logger, IEnumerable<IUserEventHandler> handlers, IDataProtectionProvider dataProtectionProvider) { _session = session; _roleService = roleService; _keyNormalizer = keyNormalizer; _logger = logger; _dataProtectionProvider = dataProtectionProvider; Handlers = handlers; } public IEnumerable<IUserEventHandler> Handlers { get; private set; } public void Dispose() { } public string NormalizeKey(string key) { return _keyNormalizer == null ? key : _keyNormalizer.NormalizeName(key); } #region IUserStore<IUser> public async Task<IdentityResult> CreateAsync(IUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } _session.Save(user); try { await _session.CommitAsync(); var context = new UserContext(user); await Handlers.InvokeAsync((handler, context) => handler.CreatedAsync(context), context, _logger); } catch { return IdentityResult.Failed(); } return IdentityResult.Success; } public async Task<IdentityResult> DeleteAsync(IUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } _session.Delete(user); try { await _session.CommitAsync(); } catch { return IdentityResult.Failed(); } return IdentityResult.Success; } public async Task<IUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) { int id; if (!int.TryParse(userId, out id)) { return null; } return await _session.GetAsync<User>(id); } public async Task<IUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken)) { return await _session.Query<User, UserIndex>(u => u.NormalizedUserName == normalizedUserName).FirstOrDefaultAsync(); } public Task<string> GetNormalizedUserNameAsync(IUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(((User)user).NormalizedUserName); } public Task<string> GetUserIdAsync(IUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(((User)user).Id.ToString(System.Globalization.CultureInfo.InvariantCulture)); } public Task<string> GetUserNameAsync(IUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(((User)user).UserName); } public Task SetNormalizedUserNameAsync(IUser user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } ((User)user).NormalizedUserName = normalizedName; return Task.CompletedTask; } public Task SetUserNameAsync(IUser user, string userName, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } ((User)user).UserName = userName; return Task.CompletedTask; } public Task<IdentityResult> UpdateAsync(IUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } _session.Save(user); return Task.FromResult(IdentityResult.Success); } #endregion IUserStore<IUser> #region IUserPasswordStore<IUser> public Task<string> GetPasswordHashAsync(IUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(((User)user).PasswordHash); } public Task SetPasswordHashAsync(IUser user, string passwordHash, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } ((User)user).PasswordHash = passwordHash; return Task.CompletedTask; } public Task<bool> HasPasswordAsync(IUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(((User)user).PasswordHash != null); } #endregion IUserPasswordStore<IUser> #region ISecurityStampValidator<IUser> public Task SetSecurityStampAsync(IUser user, string stamp, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } ((User)user).SecurityStamp = stamp; return Task.CompletedTask; } public Task<string> GetSecurityStampAsync(IUser user, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(((User)user).SecurityStamp); } #endregion ISecurityStampValidator<IUser> #region IUserEmailStore<IUser> public Task SetEmailAsync(IUser user, string email, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } ((User)user).Email = email; return Task.CompletedTask; } public Task<string> GetEmailAsync(IUser user, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(((User)user).Email); } public Task<bool> GetEmailConfirmedAsync(IUser user, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(((User)user).EmailConfirmed); } public Task SetEmailConfirmedAsync(IUser user, bool confirmed, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } ((User)user).EmailConfirmed = confirmed; return Task.CompletedTask; } public async Task<IUser> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken) { return await _session.Query<User, UserIndex>(u => u.NormalizedEmail == normalizedEmail).FirstOrDefaultAsync(); } public Task<string> GetNormalizedEmailAsync(IUser user, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(((User)user).NormalizedEmail); } public Task SetNormalizedEmailAsync(IUser user, string normalizedEmail, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } ((User)user).NormalizedEmail = normalizedEmail; return Task.CompletedTask; } #endregion IUserEmailStore<IUser> #region IUserRoleStore<IUser> public async Task AddToRoleAsync(IUser user, string normalizedRoleName, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } var roleNames = await _roleService.GetRoleNamesAsync(); var roleName = roleNames?.FirstOrDefault(r => NormalizeKey(r) == normalizedRoleName); if (string.IsNullOrWhiteSpace(roleName)) { throw new InvalidOperationException($"Role {normalizedRoleName} does not exist."); } ((User)user).RoleNames.Add(roleName); } public async Task RemoveFromRoleAsync(IUser user, string normalizedRoleName, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } var roleNames = await _roleService.GetRoleNamesAsync(); var roleName = roleNames?.FirstOrDefault(r => NormalizeKey(r) == normalizedRoleName); if (string.IsNullOrWhiteSpace(roleName)) { throw new InvalidOperationException($"Role {normalizedRoleName} does not exist."); } ((User)user).RoleNames.Remove(roleName); } public Task<IList<string>> GetRolesAsync(IUser user, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult<IList<string>>(((User)user).RoleNames); } public Task<bool> IsInRoleAsync(IUser user, string normalizedRoleName, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException("Value cannot be null or empty.", nameof(normalizedRoleName)); } return Task.FromResult(((User)user).RoleNames.Contains(normalizedRoleName, StringComparer.OrdinalIgnoreCase)); } public async Task<IList<IUser>> GetUsersInRoleAsync(string normalizedRoleName, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(normalizedRoleName)) { throw new ArgumentNullException(nameof(normalizedRoleName)); } var users = await _session.Query<User, UserByRoleNameIndex>(u => u.RoleName == normalizedRoleName).ListAsync(); return users == null ? new List<IUser>() : users.ToList<IUser>(); } #endregion IUserRoleStore<IUser> #region IUserLoginStore<IUser> public Task AddLoginAsync(IUser user, UserLoginInfo login, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (login == null) { throw new ArgumentNullException(nameof(login)); } if (((User)user).LoginInfos.Any(i => i.LoginProvider == login.LoginProvider)) throw new InvalidOperationException($"Provider {login.LoginProvider} is already linked for {user.UserName}"); ((User)user).LoginInfos.Add(login); return Task.CompletedTask; } public async Task<IUser> FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken) { return await _session.Query<User, UserByLoginInfoIndex>(u => u.LoginProvider == loginProvider && u.ProviderKey == providerKey).FirstOrDefaultAsync(); } public Task<IList<UserLoginInfo>> GetLoginsAsync(IUser user, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult<IList<UserLoginInfo>>(((User)user).LoginInfos); } public Task RemoveLoginAsync(IUser user, string loginProvider, string providerKey, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } var externalLogins = ((User)user).LoginInfos; if (externalLogins != null) { var item = externalLogins.FirstOrDefault(c => c.LoginProvider == loginProvider && c.ProviderKey == providerKey); if (item != null) { externalLogins.Remove(item); } } return Task.CompletedTask; } #endregion IUserLoginStore<IUser> #region IUserClaimStore<IUser> public Task<IList<Claim>> GetClaimsAsync(IUser user, CancellationToken cancellationToken) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult<IList<Claim>>(((User)user).UserClaims.Select(x => x.ToClaim()).ToList()); } public Task AddClaimsAsync(IUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken) { if (user == null) throw new ArgumentNullException(nameof(user)); if (claims == null) throw new ArgumentNullException(nameof(claims)); foreach (var claim in claims) { ((User)user).UserClaims.Add(new UserClaim { ClaimType = claim.Type, ClaimValue = claim.Value }); } return Task.CompletedTask; } public Task ReplaceClaimAsync(IUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken) { if (user == null) throw new ArgumentNullException(nameof(user)); if (claim == null) throw new ArgumentNullException(nameof(claim)); if (newClaim == null) throw new ArgumentNullException(nameof(newClaim)); foreach (var userClaim in ((User)user).UserClaims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type)) { userClaim.ClaimValue = newClaim.Value; userClaim.ClaimType = newClaim.Type; } return Task.CompletedTask; } public Task RemoveClaimsAsync(IUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken) { if (user == null) throw new ArgumentNullException(nameof(user)); if (claims == null) throw new ArgumentNullException(nameof(claims)); foreach (var claim in claims) { foreach (var userClaim in ((User)user).UserClaims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type).ToList()) ((User)user).UserClaims.Remove(userClaim); } return Task.CompletedTask; } public async Task<IList<IUser>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken) { if (claim == null) throw new ArgumentNullException(nameof(claim)); var users = await _session.Query<User, UserByClaimIndex>(uc => uc.ClaimType == claim.Type && uc.ClaimValue == claim.Value).ListAsync(); return users.Cast<IUser>().ToList(); } #endregion IUserClaimStore<IUser> #region IUserAuthenticationTokenStore public Task<string> GetTokenAsync(IUser user, string loginProvider, string name, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrEmpty(loginProvider)) { throw new ArgumentException("The login provider cannot be null or empty.", nameof(loginProvider)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("The name cannot be null or empty.", nameof(name)); } string tokenValue = null; var userToken = GetUserToken(user, loginProvider, name); if (userToken != null) { tokenValue = _dataProtectionProvider.CreateProtector(TokenProtector).Unprotect(userToken.Value); } return Task.FromResult(tokenValue); } public Task RemoveTokenAsync(IUser user, string loginProvider, string name, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrEmpty(loginProvider)) { throw new ArgumentException("The login provider cannot be null or empty.", nameof(loginProvider)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("The name cannot be null or empty.", nameof(name)); } var userToken = GetUserToken(user, loginProvider, name); if (userToken != null) { ((User)user).UserTokens.Remove(userToken); } return Task.CompletedTask; } public Task SetTokenAsync(IUser user, string loginProvider, string name, string value, CancellationToken cancellationToken = default(CancellationToken)) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrEmpty(loginProvider)) { throw new ArgumentException("The login provider cannot be null or empty.", nameof(loginProvider)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("The name cannot be null or empty.", nameof(name)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("The value cannot be null or empty.", nameof(value)); } var userToken = GetUserToken(user, loginProvider, name); if (userToken == null) { userToken = new UserToken { LoginProvider = loginProvider, Name = name }; ((User)user).UserTokens.Add(userToken); } // Encrypt the token userToken.Value = _dataProtectionProvider.CreateProtector(TokenProtector).Protect(value); return Task.CompletedTask; } private static UserToken GetUserToken(IUser user, string loginProvider, string name) { return ((User)user).UserTokens.FirstOrDefault(ut => ut.LoginProvider == loginProvider && ut.Name == name); } #endregion } }
// 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 gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAdParameterServiceClientTest { [Category("Autogenerated")][Test] public void GetAdParameterRequestObject() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); GetAdParameterRequest request = new GetAdParameterRequest { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), }; gagvr::AdParameter expectedResponse = new gagvr::AdParameter { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), ParameterIndex = 2776974389611536835L, InsertionText = "insertion_text562a41ad", }; mockGrpcClient.Setup(x => x.GetAdParameter(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdParameter response = client.GetAdParameter(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdParameterRequestObjectAsync() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); GetAdParameterRequest request = new GetAdParameterRequest { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), }; gagvr::AdParameter expectedResponse = new gagvr::AdParameter { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), ParameterIndex = 2776974389611536835L, InsertionText = "insertion_text562a41ad", }; mockGrpcClient.Setup(x => x.GetAdParameterAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdParameter>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdParameter responseCallSettings = await client.GetAdParameterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdParameter responseCancellationToken = await client.GetAdParameterAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdParameter() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); GetAdParameterRequest request = new GetAdParameterRequest { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), }; gagvr::AdParameter expectedResponse = new gagvr::AdParameter { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), ParameterIndex = 2776974389611536835L, InsertionText = "insertion_text562a41ad", }; mockGrpcClient.Setup(x => x.GetAdParameter(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdParameter response = client.GetAdParameter(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdParameterAsync() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); GetAdParameterRequest request = new GetAdParameterRequest { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), }; gagvr::AdParameter expectedResponse = new gagvr::AdParameter { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), ParameterIndex = 2776974389611536835L, InsertionText = "insertion_text562a41ad", }; mockGrpcClient.Setup(x => x.GetAdParameterAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdParameter>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdParameter responseCallSettings = await client.GetAdParameterAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdParameter responseCancellationToken = await client.GetAdParameterAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdParameterResourceNames() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); GetAdParameterRequest request = new GetAdParameterRequest { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), }; gagvr::AdParameter expectedResponse = new gagvr::AdParameter { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), ParameterIndex = 2776974389611536835L, InsertionText = "insertion_text562a41ad", }; mockGrpcClient.Setup(x => x.GetAdParameter(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdParameter response = client.GetAdParameter(request.ResourceNameAsAdParameterName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdParameterResourceNamesAsync() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); GetAdParameterRequest request = new GetAdParameterRequest { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), }; gagvr::AdParameter expectedResponse = new gagvr::AdParameter { ResourceNameAsAdParameterName = gagvr::AdParameterName.FromCustomerAdGroupCriterionParameterIndex("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[PARAMETER_INDEX]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), ParameterIndex = 2776974389611536835L, InsertionText = "insertion_text562a41ad", }; mockGrpcClient.Setup(x => x.GetAdParameterAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdParameter>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdParameter responseCallSettings = await client.GetAdParameterAsync(request.ResourceNameAsAdParameterName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdParameter responseCancellationToken = await client.GetAdParameterAsync(request.ResourceNameAsAdParameterName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdParametersRequestObject() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); MutateAdParametersRequest request = new MutateAdParametersRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdParameterOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateAdParametersResponse expectedResponse = new MutateAdParametersResponse { Results = { new MutateAdParameterResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); MutateAdParametersResponse response = client.MutateAdParameters(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdParametersRequestObjectAsync() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); MutateAdParametersRequest request = new MutateAdParametersRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdParameterOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateAdParametersResponse expectedResponse = new MutateAdParametersResponse { Results = { new MutateAdParameterResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); MutateAdParametersResponse responseCallSettings = await client.MutateAdParametersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdParametersResponse responseCancellationToken = await client.MutateAdParametersAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdParameters() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); MutateAdParametersRequest request = new MutateAdParametersRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdParameterOperation(), }, }; MutateAdParametersResponse expectedResponse = new MutateAdParametersResponse { Results = { new MutateAdParameterResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); MutateAdParametersResponse response = client.MutateAdParameters(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdParametersAsync() { moq::Mock<AdParameterService.AdParameterServiceClient> mockGrpcClient = new moq::Mock<AdParameterService.AdParameterServiceClient>(moq::MockBehavior.Strict); MutateAdParametersRequest request = new MutateAdParametersRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdParameterOperation(), }, }; MutateAdParametersResponse expectedResponse = new MutateAdParametersResponse { Results = { new MutateAdParameterResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdParameterServiceClient client = new AdParameterServiceClientImpl(mockGrpcClient.Object, null); MutateAdParametersResponse responseCallSettings = await client.MutateAdParametersAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdParametersResponse responseCancellationToken = await client.MutateAdParametersAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Data; using System.Collections; using System.Configuration; using System.Collections.Generic; using System.Runtime.Serialization; using System.Globalization; using System.Diagnostics; using DDay.Collections; namespace DDay.iCal { /// <summary> /// A class that represents an RFC 5545 VTIMEZONE component. /// </summary> #if !SILVERLIGHT [Serializable] #endif public partial class iCalTimeZone : CalendarComponent, ITimeZone { #region Static Public Methods #if !SILVERLIGHT static public iCalTimeZone FromLocalTimeZone() { return FromSystemTimeZone(System.TimeZoneInfo.Local); } static public iCalTimeZone FromLocalTimeZone(DateTime earlistDateTimeToSupport, bool includeHistoricalData) { return FromSystemTimeZone(System.TimeZoneInfo.Local, earlistDateTimeToSupport, includeHistoricalData); } static private void PopulateiCalTimeZoneInfo(ITimeZoneInfo tzi, System.TimeZoneInfo.TransitionTime transition, int year) { Calendar c = CultureInfo.CurrentCulture.Calendar; RecurrencePattern recurrence = new RecurrencePattern(); recurrence.Frequency = FrequencyType.Yearly; recurrence.ByMonth.Add(transition.Month); recurrence.ByHour.Add(transition.TimeOfDay.Hour); recurrence.ByMinute.Add(transition.TimeOfDay.Minute); if (transition.IsFixedDateRule) { recurrence.ByMonthDay.Add(transition.Day); } else { if( transition.Week != 5 ) recurrence.ByDay.Add(new WeekDay(transition.DayOfWeek, transition.Week )); else recurrence.ByDay.Add( new WeekDay( transition.DayOfWeek, -1 ) ); } tzi.RecurrenceRules.Add(recurrence); } public static iCalTimeZone FromSystemTimeZone(System.TimeZoneInfo tzinfo) { // Support date/times for January 1st of the previous year by default. return FromSystemTimeZone(tzinfo, new DateTime(DateTime.Now.Year, 1, 1).AddYears(-1), false); } public static iCalTimeZone FromSystemTimeZone(System.TimeZoneInfo tzinfo, DateTime earlistDateTimeToSupport, bool includeHistoricalData) { var adjustmentRules = tzinfo.GetAdjustmentRules(); var utcOffset = tzinfo.BaseUtcOffset; var dday_tz = new iCalTimeZone(); dday_tz.TZID = tzinfo.Id; IDateTime earliest = new iCalDateTime(earlistDateTimeToSupport); foreach (var adjustmentRule in adjustmentRules) { // Only include historical data if asked to do so. Otherwise, // use only the most recent adjustment rule available. if (!includeHistoricalData && adjustmentRule.DateEnd < earlistDateTimeToSupport) continue; var delta = adjustmentRule.DaylightDelta; var dday_tzinfo_standard = new DDay.iCal.iCalTimeZoneInfo(); dday_tzinfo_standard.Name = "STANDARD"; dday_tzinfo_standard.TimeZoneName = tzinfo.StandardName; dday_tzinfo_standard.Start = new iCalDateTime(new DateTime(adjustmentRule.DateStart.Year, adjustmentRule.DaylightTransitionEnd.Month, adjustmentRule.DaylightTransitionEnd.Day, adjustmentRule.DaylightTransitionEnd.TimeOfDay.Hour, adjustmentRule.DaylightTransitionEnd.TimeOfDay.Minute, adjustmentRule.DaylightTransitionEnd.TimeOfDay.Second).AddDays(1)); if (dday_tzinfo_standard.Start.LessThan(earliest)) dday_tzinfo_standard.Start = dday_tzinfo_standard.Start.AddYears(earliest.Year - dday_tzinfo_standard.Start.Year); dday_tzinfo_standard.OffsetFrom = new UTCOffset(utcOffset + delta); dday_tzinfo_standard.OffsetTo = new UTCOffset(utcOffset); PopulateiCalTimeZoneInfo(dday_tzinfo_standard, adjustmentRule.DaylightTransitionEnd, adjustmentRule.DateStart.Year); // Add the "standard" time rule to the time zone dday_tz.AddChild(dday_tzinfo_standard); if (tzinfo.SupportsDaylightSavingTime) { var dday_tzinfo_daylight = new DDay.iCal.iCalTimeZoneInfo(); dday_tzinfo_daylight.Name = "DAYLIGHT"; dday_tzinfo_daylight.TimeZoneName = tzinfo.DaylightName; dday_tzinfo_daylight.Start = new iCalDateTime(new DateTime(adjustmentRule.DateStart.Year, adjustmentRule.DaylightTransitionStart.Month, adjustmentRule.DaylightTransitionStart.Day, adjustmentRule.DaylightTransitionStart.TimeOfDay.Hour, adjustmentRule.DaylightTransitionStart.TimeOfDay.Minute, adjustmentRule.DaylightTransitionStart.TimeOfDay.Second)); if (dday_tzinfo_daylight.Start.LessThan(earliest)) dday_tzinfo_daylight.Start = dday_tzinfo_daylight.Start.AddYears(earliest.Year - dday_tzinfo_daylight.Start.Year); dday_tzinfo_daylight.OffsetFrom = new UTCOffset(utcOffset); dday_tzinfo_daylight.OffsetTo = new UTCOffset(utcOffset + delta); PopulateiCalTimeZoneInfo(dday_tzinfo_daylight, adjustmentRule.DaylightTransitionStart, adjustmentRule.DateStart.Year); // Add the "daylight" time rule to the time zone dday_tz.AddChild(dday_tzinfo_daylight); } } // If no time zone information was recorded, at least // add a STANDARD time zone element to indicate the // base time zone information. if (dday_tz.TimeZoneInfos.Count == 0) { var dday_tzinfo_standard = new DDay.iCal.iCalTimeZoneInfo(); dday_tzinfo_standard.Name = "STANDARD"; dday_tzinfo_standard.TimeZoneName = tzinfo.StandardName; dday_tzinfo_standard.Start = earliest; dday_tzinfo_standard.OffsetFrom = new UTCOffset(utcOffset); dday_tzinfo_standard.OffsetTo = new UTCOffset(utcOffset); // Add the "standard" time rule to the time zone dday_tz.AddChild(dday_tzinfo_standard); } return dday_tz; } #endif #endregion #region Private Fields TimeZoneEvaluator m_Evaluator; ICalendarObjectList<ITimeZoneInfo> m_TimeZoneInfos; #endregion #region Constructors public iCalTimeZone() { Initialize(); } private void Initialize() { this.Name = Components.TIMEZONE; m_Evaluator = new TimeZoneEvaluator(this); m_TimeZoneInfos = new CalendarObjectListProxy<ITimeZoneInfo>(Children); Children.ItemAdded += new EventHandler<ObjectEventArgs<ICalendarObject, int>>(Children_ItemAdded); Children.ItemRemoved += new EventHandler<ObjectEventArgs<ICalendarObject, int>>(Children_ItemRemoved); SetService(m_Evaluator); } #endregion #region Event Handlers void Children_ItemRemoved(object sender, ObjectEventArgs<ICalendarObject, int> e) { m_Evaluator.Clear(); } void Children_ItemAdded(object sender, ObjectEventArgs<ICalendarObject, int> e) { m_Evaluator.Clear(); } #endregion #region Overrides protected override void OnDeserializing(StreamingContext context) { base.OnDeserializing(context); Initialize(); } #endregion #region ITimeZone Members virtual public string ID { get { return Properties.Get<string>("TZID"); } set { Properties.Set("TZID", value); } } virtual public string TZID { get { return ID; } set { ID = value; } } virtual public IDateTime LastModified { get { return Properties.Get<IDateTime>("LAST-MODIFIED"); } set { Properties.Set("LAST-MODIFIED", value); } } virtual public Uri Url { get { return Properties.Get<Uri>("TZURL"); } set { Properties.Set("TZURL", value); } } virtual public Uri TZUrl { get { return Url; } set { Url = value; } } virtual public ICalendarObjectList<ITimeZoneInfo> TimeZoneInfos { get { return m_TimeZoneInfos; } set { m_TimeZoneInfos = value; } } /// <summary> /// Retrieves the iCalTimeZoneInfo object that contains information /// about the TimeZone, with the name of the current timezone, /// offset from UTC, etc. /// </summary> /// <param name="dt">The iCalDateTime object for which to retrieve the iCalTimeZoneInfo.</param> /// <returns>A TimeZoneInfo object for the specified iCalDateTime</returns> virtual public TimeZoneObservance? GetTimeZoneObservance(IDateTime dt) { Trace.TraceInformation("Getting time zone for '" + dt + "'...", "Time Zone"); foreach (ITimeZoneInfo tzi in TimeZoneInfos) { TimeZoneObservance? observance = tzi.GetObservance(dt); if (observance != null && observance.HasValue) return observance; } return null; } #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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ // These types were moved down to System.Runtime [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.CallingConventions))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.EventAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.FieldAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.GenericParameterAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.MethodAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.MethodImplAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.ParameterAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.PropertyAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.TypeAttributes))] namespace System.Reflection.Emit { public enum FlowControl { Branch = 0, Break = 1, Call = 2, Cond_Branch = 3, Meta = 4, Next = 5, [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] Phi = 6, Return = 7, Throw = 8, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OpCode { public System.Reflection.Emit.FlowControl FlowControl { get { throw null; } } public string Name { get { throw null; } } public System.Reflection.Emit.OpCodeType OpCodeType { get { throw null; } } public System.Reflection.Emit.OperandType OperandType { get { throw null; } } public int Size { get { throw null; } } public System.Reflection.Emit.StackBehaviour StackBehaviourPop { get { throw null; } } public System.Reflection.Emit.StackBehaviour StackBehaviourPush { get { throw null; } } public short Value { get { throw null; } } public override bool Equals(object obj) { throw null; } public bool Equals(System.Reflection.Emit.OpCode obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { throw null; } public static bool operator !=(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { throw null; } public override string ToString() { throw null; } } public partial class OpCodes { internal OpCodes() { } public static readonly System.Reflection.Emit.OpCode Add; public static readonly System.Reflection.Emit.OpCode Add_Ovf; public static readonly System.Reflection.Emit.OpCode Add_Ovf_Un; public static readonly System.Reflection.Emit.OpCode And; public static readonly System.Reflection.Emit.OpCode Arglist; public static readonly System.Reflection.Emit.OpCode Beq; public static readonly System.Reflection.Emit.OpCode Beq_S; public static readonly System.Reflection.Emit.OpCode Bge; public static readonly System.Reflection.Emit.OpCode Bge_S; public static readonly System.Reflection.Emit.OpCode Bge_Un; public static readonly System.Reflection.Emit.OpCode Bge_Un_S; public static readonly System.Reflection.Emit.OpCode Bgt; public static readonly System.Reflection.Emit.OpCode Bgt_S; public static readonly System.Reflection.Emit.OpCode Bgt_Un; public static readonly System.Reflection.Emit.OpCode Bgt_Un_S; public static readonly System.Reflection.Emit.OpCode Ble; public static readonly System.Reflection.Emit.OpCode Ble_S; public static readonly System.Reflection.Emit.OpCode Ble_Un; public static readonly System.Reflection.Emit.OpCode Ble_Un_S; public static readonly System.Reflection.Emit.OpCode Blt; public static readonly System.Reflection.Emit.OpCode Blt_S; public static readonly System.Reflection.Emit.OpCode Blt_Un; public static readonly System.Reflection.Emit.OpCode Blt_Un_S; public static readonly System.Reflection.Emit.OpCode Bne_Un; public static readonly System.Reflection.Emit.OpCode Bne_Un_S; public static readonly System.Reflection.Emit.OpCode Box; public static readonly System.Reflection.Emit.OpCode Br; public static readonly System.Reflection.Emit.OpCode Br_S; public static readonly System.Reflection.Emit.OpCode Break; public static readonly System.Reflection.Emit.OpCode Brfalse; public static readonly System.Reflection.Emit.OpCode Brfalse_S; public static readonly System.Reflection.Emit.OpCode Brtrue; public static readonly System.Reflection.Emit.OpCode Brtrue_S; public static readonly System.Reflection.Emit.OpCode Call; public static readonly System.Reflection.Emit.OpCode Calli; public static readonly System.Reflection.Emit.OpCode Callvirt; public static readonly System.Reflection.Emit.OpCode Castclass; public static readonly System.Reflection.Emit.OpCode Ceq; public static readonly System.Reflection.Emit.OpCode Cgt; public static readonly System.Reflection.Emit.OpCode Cgt_Un; public static readonly System.Reflection.Emit.OpCode Ckfinite; public static readonly System.Reflection.Emit.OpCode Clt; public static readonly System.Reflection.Emit.OpCode Clt_Un; public static readonly System.Reflection.Emit.OpCode Constrained; public static readonly System.Reflection.Emit.OpCode Conv_I; public static readonly System.Reflection.Emit.OpCode Conv_I1; public static readonly System.Reflection.Emit.OpCode Conv_I2; public static readonly System.Reflection.Emit.OpCode Conv_I4; public static readonly System.Reflection.Emit.OpCode Conv_I8; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8_Un; public static readonly System.Reflection.Emit.OpCode Conv_R_Un; public static readonly System.Reflection.Emit.OpCode Conv_R4; public static readonly System.Reflection.Emit.OpCode Conv_R8; public static readonly System.Reflection.Emit.OpCode Conv_U; public static readonly System.Reflection.Emit.OpCode Conv_U1; public static readonly System.Reflection.Emit.OpCode Conv_U2; public static readonly System.Reflection.Emit.OpCode Conv_U4; public static readonly System.Reflection.Emit.OpCode Conv_U8; public static readonly System.Reflection.Emit.OpCode Cpblk; public static readonly System.Reflection.Emit.OpCode Cpobj; public static readonly System.Reflection.Emit.OpCode Div; public static readonly System.Reflection.Emit.OpCode Div_Un; public static readonly System.Reflection.Emit.OpCode Dup; public static readonly System.Reflection.Emit.OpCode Endfilter; public static readonly System.Reflection.Emit.OpCode Endfinally; public static readonly System.Reflection.Emit.OpCode Initblk; public static readonly System.Reflection.Emit.OpCode Initobj; public static readonly System.Reflection.Emit.OpCode Isinst; public static readonly System.Reflection.Emit.OpCode Jmp; public static readonly System.Reflection.Emit.OpCode Ldarg; public static readonly System.Reflection.Emit.OpCode Ldarg_0; public static readonly System.Reflection.Emit.OpCode Ldarg_1; public static readonly System.Reflection.Emit.OpCode Ldarg_2; public static readonly System.Reflection.Emit.OpCode Ldarg_3; public static readonly System.Reflection.Emit.OpCode Ldarg_S; public static readonly System.Reflection.Emit.OpCode Ldarga; public static readonly System.Reflection.Emit.OpCode Ldarga_S; public static readonly System.Reflection.Emit.OpCode Ldc_I4; public static readonly System.Reflection.Emit.OpCode Ldc_I4_0; public static readonly System.Reflection.Emit.OpCode Ldc_I4_1; public static readonly System.Reflection.Emit.OpCode Ldc_I4_2; public static readonly System.Reflection.Emit.OpCode Ldc_I4_3; public static readonly System.Reflection.Emit.OpCode Ldc_I4_4; public static readonly System.Reflection.Emit.OpCode Ldc_I4_5; public static readonly System.Reflection.Emit.OpCode Ldc_I4_6; public static readonly System.Reflection.Emit.OpCode Ldc_I4_7; public static readonly System.Reflection.Emit.OpCode Ldc_I4_8; public static readonly System.Reflection.Emit.OpCode Ldc_I4_M1; public static readonly System.Reflection.Emit.OpCode Ldc_I4_S; public static readonly System.Reflection.Emit.OpCode Ldc_I8; public static readonly System.Reflection.Emit.OpCode Ldc_R4; public static readonly System.Reflection.Emit.OpCode Ldc_R8; public static readonly System.Reflection.Emit.OpCode Ldelem; public static readonly System.Reflection.Emit.OpCode Ldelem_I; public static readonly System.Reflection.Emit.OpCode Ldelem_I1; public static readonly System.Reflection.Emit.OpCode Ldelem_I2; public static readonly System.Reflection.Emit.OpCode Ldelem_I4; public static readonly System.Reflection.Emit.OpCode Ldelem_I8; public static readonly System.Reflection.Emit.OpCode Ldelem_R4; public static readonly System.Reflection.Emit.OpCode Ldelem_R8; public static readonly System.Reflection.Emit.OpCode Ldelem_Ref; public static readonly System.Reflection.Emit.OpCode Ldelem_U1; public static readonly System.Reflection.Emit.OpCode Ldelem_U2; public static readonly System.Reflection.Emit.OpCode Ldelem_U4; public static readonly System.Reflection.Emit.OpCode Ldelema; public static readonly System.Reflection.Emit.OpCode Ldfld; public static readonly System.Reflection.Emit.OpCode Ldflda; public static readonly System.Reflection.Emit.OpCode Ldftn; public static readonly System.Reflection.Emit.OpCode Ldind_I; public static readonly System.Reflection.Emit.OpCode Ldind_I1; public static readonly System.Reflection.Emit.OpCode Ldind_I2; public static readonly System.Reflection.Emit.OpCode Ldind_I4; public static readonly System.Reflection.Emit.OpCode Ldind_I8; public static readonly System.Reflection.Emit.OpCode Ldind_R4; public static readonly System.Reflection.Emit.OpCode Ldind_R8; public static readonly System.Reflection.Emit.OpCode Ldind_Ref; public static readonly System.Reflection.Emit.OpCode Ldind_U1; public static readonly System.Reflection.Emit.OpCode Ldind_U2; public static readonly System.Reflection.Emit.OpCode Ldind_U4; public static readonly System.Reflection.Emit.OpCode Ldlen; public static readonly System.Reflection.Emit.OpCode Ldloc; public static readonly System.Reflection.Emit.OpCode Ldloc_0; public static readonly System.Reflection.Emit.OpCode Ldloc_1; public static readonly System.Reflection.Emit.OpCode Ldloc_2; public static readonly System.Reflection.Emit.OpCode Ldloc_3; public static readonly System.Reflection.Emit.OpCode Ldloc_S; public static readonly System.Reflection.Emit.OpCode Ldloca; public static readonly System.Reflection.Emit.OpCode Ldloca_S; public static readonly System.Reflection.Emit.OpCode Ldnull; public static readonly System.Reflection.Emit.OpCode Ldobj; public static readonly System.Reflection.Emit.OpCode Ldsfld; public static readonly System.Reflection.Emit.OpCode Ldsflda; public static readonly System.Reflection.Emit.OpCode Ldstr; public static readonly System.Reflection.Emit.OpCode Ldtoken; public static readonly System.Reflection.Emit.OpCode Ldvirtftn; public static readonly System.Reflection.Emit.OpCode Leave; public static readonly System.Reflection.Emit.OpCode Leave_S; public static readonly System.Reflection.Emit.OpCode Localloc; public static readonly System.Reflection.Emit.OpCode Mkrefany; public static readonly System.Reflection.Emit.OpCode Mul; public static readonly System.Reflection.Emit.OpCode Mul_Ovf; public static readonly System.Reflection.Emit.OpCode Mul_Ovf_Un; public static readonly System.Reflection.Emit.OpCode Neg; public static readonly System.Reflection.Emit.OpCode Newarr; public static readonly System.Reflection.Emit.OpCode Newobj; public static readonly System.Reflection.Emit.OpCode Nop; public static readonly System.Reflection.Emit.OpCode Not; public static readonly System.Reflection.Emit.OpCode Or; public static readonly System.Reflection.Emit.OpCode Pop; public static readonly System.Reflection.Emit.OpCode Prefix1; public static readonly System.Reflection.Emit.OpCode Prefix2; public static readonly System.Reflection.Emit.OpCode Prefix3; public static readonly System.Reflection.Emit.OpCode Prefix4; public static readonly System.Reflection.Emit.OpCode Prefix5; public static readonly System.Reflection.Emit.OpCode Prefix6; public static readonly System.Reflection.Emit.OpCode Prefix7; public static readonly System.Reflection.Emit.OpCode Prefixref; public static readonly System.Reflection.Emit.OpCode Readonly; public static readonly System.Reflection.Emit.OpCode Refanytype; public static readonly System.Reflection.Emit.OpCode Refanyval; public static readonly System.Reflection.Emit.OpCode Rem; public static readonly System.Reflection.Emit.OpCode Rem_Un; public static readonly System.Reflection.Emit.OpCode Ret; public static readonly System.Reflection.Emit.OpCode Rethrow; public static readonly System.Reflection.Emit.OpCode Shl; public static readonly System.Reflection.Emit.OpCode Shr; public static readonly System.Reflection.Emit.OpCode Shr_Un; public static readonly System.Reflection.Emit.OpCode Sizeof; public static readonly System.Reflection.Emit.OpCode Starg; public static readonly System.Reflection.Emit.OpCode Starg_S; public static readonly System.Reflection.Emit.OpCode Stelem; public static readonly System.Reflection.Emit.OpCode Stelem_I; public static readonly System.Reflection.Emit.OpCode Stelem_I1; public static readonly System.Reflection.Emit.OpCode Stelem_I2; public static readonly System.Reflection.Emit.OpCode Stelem_I4; public static readonly System.Reflection.Emit.OpCode Stelem_I8; public static readonly System.Reflection.Emit.OpCode Stelem_R4; public static readonly System.Reflection.Emit.OpCode Stelem_R8; public static readonly System.Reflection.Emit.OpCode Stelem_Ref; public static readonly System.Reflection.Emit.OpCode Stfld; public static readonly System.Reflection.Emit.OpCode Stind_I; public static readonly System.Reflection.Emit.OpCode Stind_I1; public static readonly System.Reflection.Emit.OpCode Stind_I2; public static readonly System.Reflection.Emit.OpCode Stind_I4; public static readonly System.Reflection.Emit.OpCode Stind_I8; public static readonly System.Reflection.Emit.OpCode Stind_R4; public static readonly System.Reflection.Emit.OpCode Stind_R8; public static readonly System.Reflection.Emit.OpCode Stind_Ref; public static readonly System.Reflection.Emit.OpCode Stloc; public static readonly System.Reflection.Emit.OpCode Stloc_0; public static readonly System.Reflection.Emit.OpCode Stloc_1; public static readonly System.Reflection.Emit.OpCode Stloc_2; public static readonly System.Reflection.Emit.OpCode Stloc_3; public static readonly System.Reflection.Emit.OpCode Stloc_S; public static readonly System.Reflection.Emit.OpCode Stobj; public static readonly System.Reflection.Emit.OpCode Stsfld; public static readonly System.Reflection.Emit.OpCode Sub; public static readonly System.Reflection.Emit.OpCode Sub_Ovf; public static readonly System.Reflection.Emit.OpCode Sub_Ovf_Un; public static readonly System.Reflection.Emit.OpCode Switch; public static readonly System.Reflection.Emit.OpCode Tailcall; public static readonly System.Reflection.Emit.OpCode Throw; public static readonly System.Reflection.Emit.OpCode Unaligned; public static readonly System.Reflection.Emit.OpCode Unbox; public static readonly System.Reflection.Emit.OpCode Unbox_Any; public static readonly System.Reflection.Emit.OpCode Volatile; public static readonly System.Reflection.Emit.OpCode Xor; public static bool TakesSingleByteArgument(System.Reflection.Emit.OpCode inst) { throw null; } } public enum OpCodeType { [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] Annotation = 0, Macro = 1, Nternal = 2, Objmodel = 3, Prefix = 4, Primitive = 5, } public enum OperandType { InlineBrTarget = 0, InlineField = 1, InlineI = 2, InlineI8 = 3, InlineMethod = 4, InlineNone = 5, [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] InlinePhi = 6, InlineR = 7, InlineSig = 9, InlineString = 10, InlineSwitch = 11, InlineTok = 12, InlineType = 13, InlineVar = 14, ShortInlineBrTarget = 15, ShortInlineI = 16, ShortInlineR = 17, ShortInlineVar = 18, } public enum PackingSize { Size1 = 1, Size128 = 128, Size16 = 16, Size2 = 2, Size32 = 32, Size4 = 4, Size64 = 64, Size8 = 8, Unspecified = 0, } public enum StackBehaviour { Pop0 = 0, Pop1 = 1, Pop1_pop1 = 2, Popi = 3, Popi_pop1 = 4, Popi_popi = 5, Popi_popi_popi = 7, Popi_popi8 = 6, Popi_popr4 = 8, Popi_popr8 = 9, Popref = 10, Popref_pop1 = 11, Popref_popi = 12, Popref_popi_pop1 = 28, Popref_popi_popi = 13, Popref_popi_popi8 = 14, Popref_popi_popr4 = 15, Popref_popi_popr8 = 16, Popref_popi_popref = 17, Push0 = 18, Push1 = 19, Push1_push1 = 20, Pushi = 21, Pushi8 = 22, Pushr4 = 23, Pushr8 = 24, Pushref = 25, Varpop = 26, Varpush = 27, } }
/* * 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.IO; using System.Linq; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Util; using Bitcoin = QuantConnect.Algorithm.CSharp.LiveTradingFeaturesAlgorithm.Bitcoin; namespace QuantConnect.Tests.Common.Util { [TestFixture] public class LeanDataTests { [SetUp] public void SetUp() { SymbolCache.Clear(); } [TearDown] public void TearDown() { SymbolCache.Clear(); } [Test, TestCaseSource(nameof(GetLeanDataTestParameters))] public void GenerateZipFileName(LeanDataTestParameters parameters) { var zip = LeanData.GenerateZipFileName(parameters.Symbol, parameters.Date, parameters.Resolution, parameters.TickType); Assert.AreEqual(parameters.ExpectedZipFileName, zip); } [Test, TestCaseSource(nameof(GetLeanDataTestParameters))] public void GenerateZipEntryName(LeanDataTestParameters parameters) { var entry = LeanData.GenerateZipEntryName(parameters.Symbol, parameters.Date, parameters.Resolution, parameters.TickType); Assert.AreEqual(parameters.ExpectedZipEntryName, entry); } [Test, TestCaseSource(nameof(GetLeanDataTestParameters))] public void GenerateRelativeZipFilePath(LeanDataTestParameters parameters) { var relativePath = LeanData.GenerateRelativeZipFilePath(parameters.Symbol, parameters.Date, parameters.Resolution, parameters.TickType); Assert.AreEqual(parameters.ExpectedRelativeZipFilePath, relativePath); } [Test, TestCaseSource(nameof(GetLeanDataTestParameters))] public void GenerateZipFilePath(LeanDataTestParameters parameters) { var path = LeanData.GenerateZipFilePath(Globals.DataFolder, parameters.Symbol, parameters.Date, parameters.Resolution, parameters.TickType); Assert.AreEqual(parameters.ExpectedZipFilePath, path); } [Test, TestCaseSource(nameof(GetLeanDataLineTestParameters))] public void GenerateLine(LeanDataLineTestParameters parameters) { var line = LeanData.GenerateLine(parameters.Data, parameters.SecurityType, parameters.Resolution); Assert.AreEqual(parameters.ExpectedLine, line); if (parameters.Config.Type == typeof(QuoteBar)) { Assert.AreEqual(line.Split(',').Length, 11); } if (parameters.Config.Type == typeof(TradeBar)) { Assert.AreEqual(line.Split(',').Length, 6); } } [Test, TestCaseSource(nameof(GetLeanDataLineTestParameters))] public void ParsesGeneratedLines(LeanDataLineTestParameters parameters) { // ignore time zone issues here, we'll just say everything is UTC, so no conversions are performed var factory = (BaseData) Activator.CreateInstance(parameters.Data.GetType()); var parsed = factory.Reader(parameters.Config, parameters.ExpectedLine, parameters.Data.Time.Date, false); Assert.IsInstanceOf(parameters.Config.Type, parsed); Assert.AreEqual(parameters.Data.Time, parsed.Time); Assert.AreEqual(parameters.Data.EndTime, parsed.EndTime); Assert.AreEqual(parameters.Data.Symbol, parsed.Symbol); Assert.AreEqual(parameters.Data.Value, parsed.Value); if (parsed is Tick) { var expected = (Tick) parameters.Data; var actual = (Tick) parsed; Assert.AreEqual(expected.Quantity, actual.Quantity); Assert.AreEqual(expected.BidPrice, actual.BidPrice); Assert.AreEqual(expected.AskPrice, actual.AskPrice); Assert.AreEqual(expected.BidSize, actual.BidSize); Assert.AreEqual(expected.AskSize, actual.AskSize); Assert.AreEqual(expected.Exchange, actual.Exchange); Assert.AreEqual(expected.SaleCondition, actual.SaleCondition); Assert.AreEqual(expected.Suspicious, actual.Suspicious); } else if (parsed is TradeBar) { var expected = (TradeBar) parameters.Data; var actual = (TradeBar) parsed; AssertBarsAreEqual(expected, actual); Assert.AreEqual(expected.Volume, actual.Volume); } else if (parsed is QuoteBar) { var expected = (QuoteBar) parameters.Data; var actual = (QuoteBar) parsed; AssertBarsAreEqual(expected.Bid, actual.Bid); AssertBarsAreEqual(expected.Ask, actual.Ask); Assert.AreEqual(expected.LastBidSize, actual.LastBidSize); Assert.AreEqual(expected.LastAskSize, actual.LastAskSize); } } [Test, TestCaseSource(nameof(GetLeanDataLineTestParameters))] public void GetSourceMatchesGenerateZipFilePath(LeanDataLineTestParameters parameters) { var source = parameters.Data.GetSource(parameters.Config, parameters.Data.Time.Date, false); var normalizedSourcePath = new FileInfo(source.Source).FullName; var zipFilePath = LeanData.GenerateZipFilePath(Globals.DataFolder, parameters.Data.Symbol, parameters.Data.Time.Date, parameters.Resolution, parameters.TickType); var normalizeZipFilePath = new FileInfo(zipFilePath).FullName; var indexOfHash = normalizedSourcePath.LastIndexOf("#", StringComparison.Ordinal); if (indexOfHash > 0) { normalizedSourcePath = normalizedSourcePath.Substring(0, indexOfHash); } Assert.AreEqual(normalizeZipFilePath, normalizedSourcePath); } [Test, TestCaseSource(nameof(GetLeanDataTestParameters))] public void GetSource(LeanDataTestParameters parameters) { var factory = (BaseData)Activator.CreateInstance(parameters.BaseDataType); var source = factory.GetSource(parameters.Config, parameters.Date, false); var expected = parameters.ExpectedZipFilePath; if (parameters.SecurityType == SecurityType.Option || parameters.SecurityType == SecurityType.Future) { expected += "#" + parameters.ExpectedZipEntryName; } Assert.AreEqual(expected, source.Source); } [Test] public void GetDataType_ReturnsCorrectType() { var tickType = typeof(Tick); var openInterestType = typeof(OpenInterest); var quoteBarType = typeof(QuoteBar); var tradeBarType = typeof(TradeBar); Assert.AreEqual(LeanData.GetDataType(Resolution.Tick, TickType.OpenInterest), tickType); Assert.AreNotEqual(LeanData.GetDataType(Resolution.Daily, TickType.OpenInterest), tickType); Assert.AreEqual(LeanData.GetDataType(Resolution.Second, TickType.OpenInterest), openInterestType); Assert.AreNotEqual(LeanData.GetDataType(Resolution.Tick, TickType.OpenInterest), openInterestType); Assert.AreEqual(LeanData.GetDataType(Resolution.Minute, TickType.Quote), quoteBarType); Assert.AreNotEqual(LeanData.GetDataType(Resolution.Second, TickType.Trade), quoteBarType); Assert.AreEqual(LeanData.GetDataType(Resolution.Hour, TickType.Trade), tradeBarType); Assert.AreNotEqual(LeanData.GetDataType(Resolution.Tick, TickType.OpenInterest), tradeBarType); } [Test] public void LeanData_CanDetermineTheCorrectCommonDataTypes() { Assert.IsTrue(LeanData.IsCommonLeanDataType(typeof(OpenInterest))); Assert.IsTrue(LeanData.IsCommonLeanDataType(typeof(TradeBar))); Assert.IsTrue(LeanData.IsCommonLeanDataType(typeof(QuoteBar))); Assert.IsTrue(LeanData.IsCommonLeanDataType(typeof(Tick))); Assert.IsFalse(LeanData.IsCommonLeanDataType(typeof(Bitcoin))); } [Test] public void LeanData_GetCommonTickTypeForCommonDataTypes_ReturnsCorrectDataForTickResolution() { Assert.AreEqual(LeanData.GetCommonTickTypeForCommonDataTypes(typeof(Tick), SecurityType.Cfd), TickType.Quote); Assert.AreEqual(LeanData.GetCommonTickTypeForCommonDataTypes(typeof(Tick), SecurityType.Forex), TickType.Quote); } [TestCase("forex/fxcm/eurusd/20160101_quote.zip", true, SecurityType.Forex, Market.FXCM)] [TestCase("Data/f/fxcm/eurusd/20160101_quote.zip", false, SecurityType.Base, "")] [TestCase("ooooooooooooooooooooooooooooooooooooooooooooooooooooooo", false, SecurityType.Base, "")] [TestCase("", false, SecurityType.Base, "")] [TestCase(null, false, SecurityType.Base, "")] [TestCase("Data/option/u sa/minute/aapl/20140606_trade_american.zip", true, SecurityType.Option, "")] [TestCase("../Data/equity/usa/daily/aapl.zip", true, SecurityType.Equity, "usa")] [TestCase("Data/cfd/oanda/minute/bcousd/20160101_trade.zip", true, SecurityType.Cfd, "oanda")] [TestCase("Data\\alternative\\estimize\\consensus\\aapl.csv", true, SecurityType.Base, "")] [TestCase("../../../Data/option/usa/minute/spy/20200922_quote_american.zip", true, SecurityType.Option, "usa")] [TestCase("../../../Data/futureoption/comex/minute/og/20200428/20200105_quote_american.zip", true, SecurityType.FutureOption, "comex")] public void TryParseSecurityType(string path, bool result, SecurityType expectedSecurityType, string market) { Assert.AreEqual(result, LeanData.TryParseSecurityType(path, out var securityType, out var parsedMarket)); Assert.AreEqual(expectedSecurityType, securityType); Assert.AreEqual(market, parsedMarket); } [Test] public void IncorrectPaths_CannotBeParsed() { DateTime date; Symbol symbol; Resolution resolution; var invalidPath = "forex/fxcm/eurusd/20160101_quote.zip"; Assert.IsFalse(LeanData.TryParsePath(invalidPath, out symbol, out date, out resolution)); var nonExistantPath = "Data/f/fxcm/eurusd/20160101_quote.zip"; Assert.IsFalse(LeanData.TryParsePath(nonExistantPath, out symbol, out date, out resolution)); var notAPath = "ooooooooooooooooooooooooooooooooooooooooooooooooooooooo"; Assert.IsFalse(LeanData.TryParsePath(notAPath, out symbol, out date, out resolution)); var emptyPath = ""; Assert.IsFalse(LeanData.TryParsePath(emptyPath, out symbol, out date, out resolution)); string nullPath = null; Assert.IsFalse(LeanData.TryParsePath(nullPath, out symbol, out date, out resolution)); var optionsTradePath = "Data/option/u sa/minute/aapl/20140606_trade_american.zip"; Assert.IsFalse(LeanData.TryParsePath(optionsTradePath, out symbol, out date, out resolution)); } [Test] public void CorrectPaths_CanBeParsedCorrectly() { DateTime date; Symbol symbol; Resolution resolution; var customPath = "a/very/custom/path/forex/oanda/tick/eurusd/20170104_quote.zip"; Assert.IsTrue(LeanData.TryParsePath(customPath, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Forex); Assert.AreEqual(symbol.ID.Market, Market.Oanda); Assert.AreEqual(resolution, Resolution.Tick); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "eurusd"); Assert.AreEqual(date.Date, Parse.DateTime("2017-01-04").Date); var mixedPathSeperators = @"Data//forex/fxcm\/minute//eurusd\\20160101_quote.zip"; Assert.IsTrue(LeanData.TryParsePath(mixedPathSeperators, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Forex); Assert.AreEqual(symbol.ID.Market, Market.FXCM); Assert.AreEqual(resolution, Resolution.Minute); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "eurusd"); Assert.AreEqual(date.Date, Parse.DateTime("2016-01-01").Date); var longRelativePath = "../../../../../../../../../Data/forex/fxcm/hour/gbpusd.zip"; Assert.IsTrue(LeanData.TryParsePath(longRelativePath, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Forex); Assert.AreEqual(symbol.ID.Market, Market.FXCM); Assert.AreEqual(resolution, Resolution.Hour); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "gbpusd"); Assert.AreEqual(date.Date, DateTime.MinValue); var shortRelativePath = "Data/forex/fxcm/minute/eurusd/20160102_quote.zip"; Assert.IsTrue(LeanData.TryParsePath(shortRelativePath, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Forex); Assert.AreEqual(symbol.ID.Market, Market.FXCM); Assert.AreEqual(resolution, Resolution.Minute); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "eurusd"); Assert.AreEqual(date.Date, Parse.DateTime("2016-01-02").Date); var dailyEquitiesPath = "Data/equity/usa/daily/aapl.zip"; Assert.IsTrue(LeanData.TryParsePath(dailyEquitiesPath, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Equity); Assert.AreEqual(symbol.ID.Market, Market.USA); Assert.AreEqual(resolution, Resolution.Daily); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "aapl"); Assert.AreEqual(date.Date, DateTime.MinValue); var minuteEquitiesPath = "Data/equity/usa/minute/googl/20070103_trade.zip"; Assert.IsTrue(LeanData.TryParsePath(minuteEquitiesPath, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Equity); Assert.AreEqual(symbol.ID.Market, Market.USA); Assert.AreEqual(resolution, Resolution.Minute); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "goog"); Assert.AreEqual(date.Date, Parse.DateTime("2007-01-03").Date); var cfdPath = "Data/cfd/oanda/minute/bcousd/20160101_trade.zip"; Assert.IsTrue(LeanData.TryParsePath(cfdPath, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Cfd); Assert.AreEqual(symbol.ID.Market, Market.Oanda); Assert.AreEqual(resolution, Resolution.Minute); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "bcousd"); Assert.AreEqual(date.Date, Parse.DateTime("2016-01-01").Date); } [TestCase("Data\\alternative\\estimize\\consensus\\aapl.csv", "aapl", null)] [TestCase("Data\\alternative\\psychsignal\\aapl\\20161007.zip", "aapl", "2016-10-07")] [TestCase("Data\\alternative\\sec\\aapl\\20161007_8K.zip", "aapl", "2016-10-07")] [TestCase("Data\\alternative\\smartinsider\\intentions\\aapl.tsv", "aapl", null)] [TestCase("Data\\alternative\\trading-economics\\calendar\\fdtr\\20161007.zip", "fdtr", "2016-10-07")] [TestCase("Data\\alternative\\ustreasury\\yieldcurverates.zip", "yieldcurverates", null)] public void AlternativePaths_CanBeParsedCorrectly(string path, string expectedSymbol, string expectedDate) { DateTime date; Symbol symbol; Resolution resolution; Assert.IsTrue(LeanData.TryParsePath(path, out symbol, out date, out resolution)); Assert.AreEqual(SecurityType.Base, symbol.SecurityType); Assert.AreEqual(Market.USA, symbol.ID.Market); Assert.AreEqual(Resolution.Daily, resolution); Assert.AreEqual(expectedSymbol, symbol.ID.Symbol.ToLowerInvariant()); Assert.AreEqual(expectedDate == null ? default(DateTime) : Parse.DateTime(expectedDate).Date, date); } [Test] public void CryptoPaths_CanBeParsedCorrectly() { DateTime date; Symbol symbol; Resolution resolution; var cryptoPath = "Data\\crypto\\gdax\\daily\\btcusd_quote.zip"; Assert.IsTrue(LeanData.TryParsePath(cryptoPath, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Crypto); Assert.AreEqual(symbol.ID.Market, Market.GDAX); Assert.AreEqual(resolution, Resolution.Daily); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "btcusd"); cryptoPath = "Data\\crypto\\gdax\\hour\\btcusd_quote.zip"; Assert.IsTrue(LeanData.TryParsePath(cryptoPath, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Crypto); Assert.AreEqual(symbol.ID.Market, Market.GDAX); Assert.AreEqual(resolution, Resolution.Hour); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "btcusd"); cryptoPath = "Data\\crypto\\gdax\\minute\\btcusd\\20161007_quote.zip"; Assert.IsTrue(LeanData.TryParsePath(cryptoPath, out symbol, out date, out resolution)); Assert.AreEqual(symbol.SecurityType, SecurityType.Crypto); Assert.AreEqual(symbol.ID.Market, Market.GDAX); Assert.AreEqual(resolution, Resolution.Minute); Assert.AreEqual(symbol.ID.Symbol.ToLowerInvariant(), "btcusd"); Assert.AreEqual(date.Date, Parse.DateTime("2016-10-07").Date); } [TestCase(SecurityType.Base, "alteRNative")] [TestCase(SecurityType.Equity, "Equity")] [TestCase(SecurityType.Cfd, "Cfd")] [TestCase(SecurityType.Commodity, "Commodity")] [TestCase(SecurityType.Crypto, "Crypto")] [TestCase(SecurityType.Forex, "Forex")] [TestCase(SecurityType.Future, "Future")] [TestCase(SecurityType.Option, "Option")] [TestCase(SecurityType.FutureOption, "FutureOption")] public void ParsesDataSecurityType(SecurityType type, string path) { Assert.AreEqual(type, LeanData.ParseDataSecurityType(path)); } [Test] public void SecurityTypeAsDataPath() { Assert.IsTrue(LeanData.SecurityTypeAsDataPath.Contains("alternative")); Assert.IsTrue(LeanData.SecurityTypeAsDataPath.Contains("equity")); Assert.IsTrue(LeanData.SecurityTypeAsDataPath.Contains("base")); Assert.IsTrue(LeanData.SecurityTypeAsDataPath.Contains("option")); Assert.IsTrue(LeanData.SecurityTypeAsDataPath.Contains("cfd")); Assert.IsTrue(LeanData.SecurityTypeAsDataPath.Contains("crypto")); Assert.IsTrue(LeanData.SecurityTypeAsDataPath.Contains("future")); Assert.IsTrue(LeanData.SecurityTypeAsDataPath.Contains("forex")); } [Test] public void OptionZipFilePathWithUnderlyingEquity() { var underlying = Symbol.Create("SPY", SecurityType.Equity, QuantConnect.Market.USA); var optionSymbol = Symbol.CreateOption( underlying, Market.USA, OptionStyle.American, OptionRight.Put, 4200m, new DateTime(2020, 12, 31)); var optionZipFilePath = LeanData.GenerateZipFilePath(Globals.DataFolder, optionSymbol, new DateTime(2020, 9, 22), Resolution.Minute, TickType.Quote) .Replace(Path.DirectorySeparatorChar, '/'); var optionEntryFilePath = LeanData.GenerateZipEntryName(optionSymbol, new DateTime(2020, 9, 22), Resolution.Minute, TickType.Quote); Assert.AreEqual("../../../Data/option/usa/minute/spy/20200922_quote_american.zip", optionZipFilePath); Assert.AreEqual("20200922_spy_minute_quote_american_put_42000000_20201231.csv", optionEntryFilePath); } [TestCase("ES", "ES")] [TestCase("DC", "DC")] [TestCase("GC", "OG")] [TestCase("ZT", "OZT")] public void OptionZipFilePathWithUnderlyingFuture(string futureOptionTicker, string expectedFutureOptionTicker) { var underlying = Symbol.CreateFuture(futureOptionTicker, Market.CME, new DateTime(2021, 3, 19)); var optionSymbol = Symbol.CreateOption( underlying, Market.CME, OptionStyle.American, OptionRight.Put, 4200m, new DateTime(2021, 3, 18)); var optionZipFilePath = LeanData.GenerateZipFilePath(Globals.DataFolder, optionSymbol, new DateTime(2020, 9, 22), Resolution.Minute, TickType.Quote) .Replace(Path.DirectorySeparatorChar, '/'); var optionEntryFilePath = LeanData.GenerateZipEntryName(optionSymbol, new DateTime(2020, 9, 22), Resolution.Minute, TickType.Quote); Assert.AreEqual($"../../../Data/futureoption/cme/minute/{expectedFutureOptionTicker.ToLowerInvariant()}/{underlying.ID.Date:yyyyMMdd}/20200922_quote_american.zip", optionZipFilePath); Assert.AreEqual($"20200922_{expectedFutureOptionTicker.ToLowerInvariant()}_minute_quote_american_put_42000000_{optionSymbol.ID.Date:yyyyMMdd}.csv", optionEntryFilePath); } [TestCase(OptionRight.Call, 1650, 2020, 3, 26)] [TestCase(OptionRight.Call, 1540, 2020, 3, 26)] [TestCase(OptionRight.Call, 1600, 2020, 2, 25)] [TestCase(OptionRight.Call, 1545, 2020, 2, 25)] public void FutureOptionSingleZipFileContainingMultipleFuturesOptionsContracts(OptionRight right, int strike, int year, int month, int day) { var underlying = Symbol.CreateFuture("GC", Market.COMEX, new DateTime(2020, 4, 28)); var expiry = new DateTime(year, month, day); var optionSymbol = Symbol.CreateOption( underlying, Market.COMEX, OptionStyle.American, right, (decimal)strike, expiry); var optionZipFilePath = LeanData.GenerateZipFilePath(Globals.DataFolder, optionSymbol, new DateTime(2020, 1, 5), Resolution.Minute, TickType.Quote) .Replace(Path.DirectorySeparatorChar, '/'); var optionEntryFilePath = LeanData.GenerateZipEntryName(optionSymbol, new DateTime(2020, 1, 5), Resolution.Minute, TickType.Quote); Assert.AreEqual("../../../Data/futureoption/comex/minute/og/20200428/20200105_quote_american.zip", optionZipFilePath); Assert.AreEqual($"20200105_og_minute_quote_american_{right.ToLower()}_{strike}0000_{expiry:yyyyMMdd}.csv", optionEntryFilePath); } [Test, TestCaseSource(nameof(AggregateTradeBarsTestData))] public void AggregateTradeBarsTest(TimeSpan resolution, TradeBar expectedFirstTradeBar) { var initialTime = new DateTime(2020, 1, 5, 12, 0, 0); var symbol = Symbols.AAPL; var initialBars = new[] { new TradeBar {Time = initialTime, Open = 10, High = 15, Low = 8, Close = 11, Volume = 50, Period = TimeSpan.FromSeconds(1), Symbol = symbol}, new TradeBar {Time = initialTime.Add(TimeSpan.FromSeconds(15)), Open = 13, High = 14, Low = 7, Close = 9, Volume = 150, Period = TimeSpan.FromSeconds(1), Symbol = symbol}, new TradeBar {Time = initialTime.Add(TimeSpan.FromMinutes(15)), Open = 11, High = 25, Low = 10, Close = 21, Volume = 90, Period = TimeSpan.FromMinutes(1), Symbol = symbol}, new TradeBar {Time = initialTime.Add(TimeSpan.FromHours(6)), Open = 17, High = 19, Low = 12, Close = 11, Volume = 20, Period = TimeSpan.FromMinutes(1), Symbol = symbol}, }; var aggregated = LeanData.AggregateTradeBars(initialBars, symbol, resolution).ToList(); Assert.True(aggregated.All(i => i.Period == resolution)); var firstBar = aggregated.First(); AssertBarsAreEqual(expectedFirstTradeBar, firstBar); } [Test, TestCaseSource(nameof(AggregateQuoteBarsTestData))] public void AggregateQuoteBarsTest(TimeSpan resolution, QuoteBar expectedFirstBar) { var initialTime = new DateTime(2020, 1, 5, 12, 0, 0); var symbol = Symbols.AAPL; var initialBars = new[] { new QuoteBar {Time = initialTime, Ask = new Bar {Open = 10, High = 15, Low = 8, Close = 11}, Bid = {Open = 7, High = 14, Low = 5, Close = 10}, Period = TimeSpan.FromMinutes(1), Symbol = symbol}, new QuoteBar {Time = initialTime.Add(TimeSpan.FromSeconds(15)), Ask = new Bar {Open = 13, High = 14, Low = 7, Close = 9}, Bid = {Open = 10, High = 11, Low = 4, Close = 5}, Period = TimeSpan.FromMinutes(1), Symbol = symbol}, new QuoteBar {Time = initialTime.Add(TimeSpan.FromMinutes(15)), Ask = new Bar {Open = 11, High = 25, Low = 10, Close = 21}, Bid = {Open = 10, High = 22, Low = 9, Close = 20}, Period = TimeSpan.FromMinutes(1), Symbol = symbol}, new QuoteBar {Time = initialTime.Add(TimeSpan.FromHours(6)), Ask = new Bar {Open = 17, High = 19, Low = 12, Close = 11}, Bid = {Open = 16, High = 17, Low = 10, Close = 10}, Period = TimeSpan.FromMinutes(1), Symbol = symbol}, }; var aggregated = LeanData.AggregateQuoteBars(initialBars, symbol, resolution).ToList(); Assert.True(aggregated.All(i => i.Period == resolution)); var firstBar = aggregated.First(); AssertBarsAreEqual(expectedFirstBar.Ask, firstBar.Ask); AssertBarsAreEqual(expectedFirstBar.Bid, firstBar.Bid); } [Test, TestCaseSource(nameof(AggregateTickTestData))] public void AggregateTicksTest(TimeSpan resolution, QuoteBar expectedFirstBar) { var initialTime = new DateTime(2020, 1, 5, 12, 0, 0); var symbol = Symbols.AAPL; var initialTicks = new[] { new Tick(initialTime, symbol, string.Empty, string.Empty, 10, 11, 12, 13), new Tick(initialTime.Add(TimeSpan.FromSeconds(1)), symbol, string.Empty, string.Empty, 14, 15, 16, 17), new Tick(initialTime.Add(TimeSpan.FromSeconds(10)), symbol, string.Empty, string.Empty, 18, 19, 20, 21), new Tick(initialTime.Add(TimeSpan.FromSeconds(61)), symbol, string.Empty, string.Empty, 22, 23, 24, 25), }; var aggregated = LeanData.AggregateTicks(initialTicks, symbol, resolution).ToList(); Assert.True(aggregated.All(i => i.Period == resolution)); var firstBar = aggregated.First(); AssertBarsAreEqual(expectedFirstBar.Ask, firstBar.Ask); AssertBarsAreEqual(expectedFirstBar.Bid, firstBar.Bid); } private static void AssertBarsAreEqual(IBar expected, IBar actual) { if (expected == null && actual == null) { return; } if (expected == null && actual != null) { Assert.Fail("Expected null bar"); } Assert.AreEqual(expected.Open, actual.Open); Assert.AreEqual(expected.High, actual.High); Assert.AreEqual(expected.Low, actual.Low); Assert.AreEqual(expected.Close, actual.Close); } private static TestCaseData[] GetLeanDataTestParameters() { var date = new DateTime(2016, 02, 17); var dateFutures = new DateTime(2018, 12, 10); return new List<LeanDataTestParameters> { // equity new LeanDataTestParameters(Symbols.SPY, date, Resolution.Tick, TickType.Trade, "20160217_trade.zip", "20160217_spy_Trade_Tick.csv", "equity/usa/tick/spy"), new LeanDataTestParameters(Symbols.SPY, date, Resolution.Second, TickType.Trade, "20160217_trade.zip", "20160217_spy_second_trade.csv", "equity/usa/second/spy"), new LeanDataTestParameters(Symbols.SPY, date, Resolution.Minute, TickType.Trade, "20160217_trade.zip", "20160217_spy_minute_trade.csv", "equity/usa/minute/spy"), new LeanDataTestParameters(Symbols.SPY, date, Resolution.Hour, TickType.Trade, "spy.zip", "spy.csv", "equity/usa/hour"), new LeanDataTestParameters(Symbols.SPY, date, Resolution.Daily, TickType.Trade, "spy.zip", "spy.csv", "equity/usa/daily"), // equity option trades new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Tick, TickType.Trade, "20160217_trade_american.zip", "20160217_spy_tick_trade_american_put_1920000_20160219.csv", "option/usa/tick/spy"), new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Tick, TickType.Quote, "20160217_quote_american.zip", "20160217_spy_tick_quote_american_put_1920000_20160219.csv", "option/usa/tick/spy"), new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Second, TickType.Trade, "20160217_trade_american.zip", "20160217_spy_second_trade_american_put_1920000_20160219.csv", "option/usa/second/spy"), new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Second, TickType.Quote, "20160217_quote_american.zip", "20160217_spy_second_quote_american_put_1920000_20160219.csv", "option/usa/second/spy"), new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Minute, TickType.Trade, "20160217_trade_american.zip", "20160217_spy_minute_trade_american_put_1920000_20160219.csv", "option/usa/minute/spy"), new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Minute, TickType.Quote, "20160217_quote_american.zip", "20160217_spy_minute_quote_american_put_1920000_20160219.csv", "option/usa/minute/spy"), new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Hour, TickType.Trade, "spy_2016_trade_american.zip", "spy_trade_american_put_1920000_20160219.csv", "option/usa/hour"), new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Hour, TickType.Quote, "spy_2016_quote_american.zip", "spy_quote_american_put_1920000_20160219.csv", "option/usa/hour"), new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Daily, TickType.Trade, "spy_2016_trade_american.zip", "spy_trade_american_put_1920000_20160219.csv", "option/usa/daily"), new LeanDataTestParameters(Symbols.SPY_P_192_Feb19_2016, date, Resolution.Daily, TickType.Quote, "spy_2016_quote_american.zip", "spy_quote_american_put_1920000_20160219.csv", "option/usa/daily"), // forex new LeanDataTestParameters(Symbols.EURUSD, date, Resolution.Tick, TickType.Quote, "20160217_quote.zip", "20160217_eurusd_tick_quote.csv", "forex/oanda/tick/eurusd"), new LeanDataTestParameters(Symbols.EURUSD, date, Resolution.Second, TickType.Quote, "20160217_quote.zip", "20160217_eurusd_second_quote.csv", "forex/oanda/second/eurusd"), new LeanDataTestParameters(Symbols.EURUSD, date, Resolution.Minute, TickType.Quote, "20160217_quote.zip", "20160217_eurusd_minute_quote.csv", "forex/oanda/minute/eurusd"), new LeanDataTestParameters(Symbols.EURUSD, date, Resolution.Hour, TickType.Quote, "eurusd.zip", "eurusd.csv", "forex/oanda/hour"), new LeanDataTestParameters(Symbols.EURUSD, date, Resolution.Daily, TickType.Quote, "eurusd.zip", "eurusd.csv", "forex/oanda/daily"), // cfd new LeanDataTestParameters(Symbols.DE10YBEUR, date, Resolution.Tick, TickType.Quote, "20160217_quote.zip", "20160217_de10ybeur_tick_quote.csv", "cfd/oanda/tick/de10ybeur"), new LeanDataTestParameters(Symbols.DE10YBEUR, date, Resolution.Second, TickType.Quote, "20160217_quote.zip", "20160217_de10ybeur_second_quote.csv", "cfd/oanda/second/de10ybeur"), new LeanDataTestParameters(Symbols.DE10YBEUR, date, Resolution.Minute, TickType.Quote, "20160217_quote.zip", "20160217_de10ybeur_minute_quote.csv", "cfd/oanda/minute/de10ybeur"), new LeanDataTestParameters(Symbols.DE10YBEUR, date, Resolution.Hour, TickType.Quote, "de10ybeur.zip", "de10ybeur.csv", "cfd/oanda/hour"), new LeanDataTestParameters(Symbols.DE10YBEUR, date, Resolution.Daily, TickType.Quote, "de10ybeur.zip", "de10ybeur.csv", "cfd/oanda/daily"), // Crypto - trades new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Tick, TickType.Trade, "20160217_trade.zip", "20160217_btcusd_tick_trade.csv", "crypto/gdax/tick/btcusd"), new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Second, TickType.Trade, "20160217_trade.zip", "20160217_btcusd_second_trade.csv", "crypto/gdax/second/btcusd"), new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Minute, TickType.Trade, "20160217_trade.zip", "20160217_btcusd_minute_trade.csv", "crypto/gdax/minute/btcusd"), new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Hour, TickType.Trade, "btcusd_trade.zip", "btcusd.csv", "crypto/gdax/hour"), new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Daily, TickType.Trade, "btcusd_trade.zip", "btcusd.csv", "crypto/gdax/daily"), // Crypto - quotes new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Tick, TickType.Quote, "20160217_quote.zip", "20160217_btcusd_tick_quote.csv", "crypto/gdax/tick/btcusd"), new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Second, TickType.Quote, "20160217_quote.zip", "20160217_btcusd_second_quote.csv", "crypto/gdax/second/btcusd"), new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Minute, TickType.Quote, "20160217_quote.zip", "20160217_btcusd_minute_quote.csv", "crypto/gdax/minute/btcusd"), new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Hour, TickType.Quote, "btcusd_quote.zip", "btcusd.csv", "crypto/gdax/hour"), new LeanDataTestParameters(Symbols.BTCUSD, date, Resolution.Daily, TickType.Quote, "btcusd_quote.zip", "btcusd.csv", "crypto/gdax/daily"), // Futures (expiration month == contract month) - trades new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Tick, TickType.Trade, "20181210_trade.zip", "20181210_es_tick_trade_201812_20181221.csv", "future/cme/tick/es"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Second, TickType.Trade, "20181210_trade.zip", "20181210_es_second_trade_201812_20181221.csv", "future/cme/second/es"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Minute, TickType.Trade, "20181210_trade.zip", "20181210_es_minute_trade_201812_20181221.csv", "future/cme/minute/es"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Hour, TickType.Trade, "es_trade.zip", "es_trade_201812_20181221.csv", "future/cme/hour"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Daily, TickType.Trade, "es_trade.zip", "es_trade_201812_20181221.csv", "future/cme/daily"), // Futures (expiration month == contract month) - quotes new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Tick, TickType.Quote, "20181210_quote.zip", "20181210_es_tick_quote_201812_20181221.csv", "future/cme/tick/es"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Second, TickType.Quote, "20181210_quote.zip", "20181210_es_second_quote_201812_20181221.csv", "future/cme/second/es"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Minute, TickType.Quote, "20181210_quote.zip", "20181210_es_minute_quote_201812_20181221.csv", "future/cme/minute/es"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Hour, TickType.Quote, "es_quote.zip", "es_quote_201812_20181221.csv", "future/cme/hour"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Daily, TickType.Quote, "es_quote.zip", "es_quote_201812_20181221.csv", "future/cme/daily"), // Futures (expiration month == contract month) - OpenInterest new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Tick, TickType.OpenInterest, "20181210_openinterest.zip", "20181210_es_tick_openinterest_201812_20181221.csv", "future/cme/tick/es"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Second, TickType.OpenInterest, "20181210_openinterest.zip", "20181210_es_second_openinterest_201812_20181221.csv", "future/cme/second/es"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Minute, TickType.OpenInterest, "20181210_openinterest.zip", "20181210_es_minute_openinterest_201812_20181221.csv", "future/cme/minute/es"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Hour, TickType.OpenInterest, "es_openinterest.zip", "es_openinterest_201812_20181221.csv", "future/cme/hour"), new LeanDataTestParameters(Symbols.Future_ESZ18_Dec2018, dateFutures, Resolution.Daily, TickType.OpenInterest, "es_openinterest.zip", "es_openinterest_201812_20181221.csv", "future/cme/daily"), // Futures (expiration month < contract month) - trades new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Tick, TickType.Trade, "20181210_trade.zip", "20181210_cl_tick_trade_201901_20181219.csv", "future/nymex/tick/cl"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Second, TickType.Trade, "20181210_trade.zip", "20181210_cl_second_trade_201901_20181219.csv", "future/nymex/second/cl"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Minute, TickType.Trade, "20181210_trade.zip", "20181210_cl_minute_trade_201901_20181219.csv", "future/nymex/minute/cl"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Hour, TickType.Trade, "cl_trade.zip", "cl_trade_201901_20181219.csv", "future/nymex/hour"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Daily, TickType.Trade, "cl_trade.zip", "cl_trade_201901_20181219.csv", "future/nymex/daily"), // Futures (expiration month < contract month) - quotes new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Tick, TickType.Quote, "20181210_quote.zip", "20181210_cl_tick_quote_201901_20181219.csv", "future/nymex/tick/cl"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Second, TickType.Quote, "20181210_quote.zip", "20181210_cl_second_quote_201901_20181219.csv", "future/nymex/second/cl"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Minute, TickType.Quote, "20181210_quote.zip", "20181210_cl_minute_quote_201901_20181219.csv", "future/nymex/minute/cl"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Hour, TickType.Quote, "cl_quote.zip", "cl_quote_201901_20181219.csv", "future/nymex/hour"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Daily, TickType.Quote, "cl_quote.zip", "cl_quote_201901_20181219.csv", "future/nymex/daily"), // Futures (expiration month < contract month) - open interest new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Tick, TickType.OpenInterest, "20181210_openinterest.zip", "20181210_cl_tick_openinterest_201901_20181219.csv", "future/nymex/tick/cl"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Second, TickType.OpenInterest, "20181210_openinterest.zip", "20181210_cl_second_openinterest_201901_20181219.csv", "future/nymex/second/cl"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Minute, TickType.OpenInterest, "20181210_openinterest.zip", "20181210_cl_minute_openinterest_201901_20181219.csv", "future/nymex/minute/cl"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Hour, TickType.OpenInterest, "cl_openinterest.zip", "cl_openinterest_201901_20181219.csv", "future/nymex/hour"), new LeanDataTestParameters(Symbols.Future_CLF19_Jan2019, dateFutures, Resolution.Daily, TickType.OpenInterest, "cl_openinterest.zip", "cl_openinterest_201901_20181219.csv", "future/nymex/daily"), }.Select(x => new TestCaseData(x).SetName(x.Name)).ToArray(); } private static TestCaseData[] GetLeanDataLineTestParameters() { var time = new DateTime(2016, 02, 18, 9, 30, 0); return new List<LeanDataLineTestParameters> { //equity new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.SPY, Value = 1, Quantity = 2, TickType = TickType.Trade, Exchange = Exchange.BATS_Y, SaleCondition = "SC", Suspicious = true}, SecurityType.Equity, Resolution.Tick, "34200000,10000,2,Y,SC,1"), new LeanDataLineTestParameters(new TradeBar(time, Symbols.SPY, 1, 2, 3, 4, 5, TimeSpan.FromMinutes(1)), SecurityType.Equity, Resolution.Minute, "34200000,10000,20000,30000,40000,5"), new LeanDataLineTestParameters(new TradeBar(time.Date, Symbols.SPY, 1, 2, 3, 4, 5, TimeSpan.FromDays(1)), SecurityType.Equity, Resolution.Daily, "20160218 00:00,10000,20000,30000,40000,5"), // options new LeanDataLineTestParameters(new QuoteBar(time, Symbols.SPY_P_192_Feb19_2016, null, 0, new Bar(6, 7, 8, 9), 10, TimeSpan.FromMinutes(1)) {Bid = null}, SecurityType.Option, Resolution.Minute, "34200000,,,,,0,60000,70000,80000,90000,10"), new LeanDataLineTestParameters(new QuoteBar(time.Date, Symbols.SPY_P_192_Feb19_2016, new Bar(1, 2, 3, 4), 5, null, 0, TimeSpan.FromDays(1)) {Ask = null}, SecurityType.Option, Resolution.Daily, "20160218 00:00,10000,20000,30000,40000,5,,,,,0"), new LeanDataLineTestParameters(new QuoteBar(time, Symbols.SPY_P_192_Feb19_2016, new Bar(1, 2, 3, 4), 5, new Bar(6, 7, 8, 9), 10, TimeSpan.FromMinutes(1)), SecurityType.Option, Resolution.Minute, "34200000,10000,20000,30000,40000,5,60000,70000,80000,90000,10"), new LeanDataLineTestParameters(new QuoteBar(time.Date, Symbols.SPY_P_192_Feb19_2016, new Bar(1, 2, 3, 4), 5, new Bar(6, 7, 8, 9), 10, TimeSpan.FromDays(1)), SecurityType.Option, Resolution.Daily, "20160218 00:00,10000,20000,30000,40000,5,60000,70000,80000,90000,10"), new LeanDataLineTestParameters(new Tick(time, Symbols.SPY_P_192_Feb19_2016, 0, 1, 3) {Value = 2m, TickType = TickType.Quote, BidSize = 2, AskSize = 4, Exchange = Exchange.C2, Suspicious = true}, SecurityType.Option, Resolution.Tick, "34200000,10000,2,30000,4,W,1"), new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.SPY_P_192_Feb19_2016, Value = 1, Quantity = 2,TickType = TickType.Trade, Exchange = Exchange.C2, SaleCondition = "SC", Suspicious = true}, SecurityType.Option, Resolution.Tick, "34200000,10000,2,W,SC,1"), new LeanDataLineTestParameters(new TradeBar(time, Symbols.SPY_P_192_Feb19_2016, 1, 2, 3, 4, 5, TimeSpan.FromMinutes(1)), SecurityType.Option, Resolution.Minute, "34200000,10000,20000,30000,40000,5"), new LeanDataLineTestParameters(new TradeBar(time.Date, Symbols.SPY_P_192_Feb19_2016, 1, 2, 3, 4, 5, TimeSpan.FromDays(1)), SecurityType.Option, Resolution.Daily, "20160218 00:00,10000,20000,30000,40000,5"), // forex new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.EURUSD, BidPrice = 1, Value =1.5m, AskPrice = 2, TickType = TickType.Quote}, SecurityType.Forex, Resolution.Tick, "34200000,1,2"), new LeanDataLineTestParameters(new QuoteBar(time, Symbols.EURUSD, new Bar(1, 2, 3, 4), 0, new Bar(1, 2, 3, 4), 0, TimeSpan.FromMinutes(1)), SecurityType.Forex, Resolution.Minute, "34200000,1,2,3,4,0,1,2,3,4,0"), new LeanDataLineTestParameters(new QuoteBar(time.Date, Symbols.EURUSD, new Bar(1, 2, 3, 4), 0, new Bar(1, 2, 3, 4), 0, TimeSpan.FromDays(1)), SecurityType.Forex, Resolution.Daily, "20160218 00:00,1,2,3,4,0,1,2,3,4,0"), // cfd new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.DE10YBEUR, BidPrice = 1, Value = 1.5m, AskPrice = 2, TickType = TickType.Quote}, SecurityType.Cfd, Resolution.Tick, "34200000,1,2"), new LeanDataLineTestParameters(new QuoteBar(time, Symbols.DE10YBEUR, new Bar(1, 2, 3, 4), 0, new Bar(1, 2, 3, 4), 0, TimeSpan.FromMinutes(1)), SecurityType.Cfd, Resolution.Minute, "34200000,1,2,3,4,0,1,2,3,4,0"), new LeanDataLineTestParameters(new QuoteBar(time.Date, Symbols.DE10YBEUR, new Bar(1, 2, 3, 4), 0, new Bar(1, 2, 3, 4), 0, TimeSpan.FromDays(1)), SecurityType.Cfd, Resolution.Daily, "20160218 00:00,1,2,3,4,0,1,2,3,4,0"), // crypto - trades new LeanDataLineTestParameters(new QuoteBar(time, Symbols.BTCUSD, null, 0, new Bar(6, 7, 8, 9), 10, TimeSpan.FromMinutes(1)) {Bid = null}, SecurityType.Crypto, Resolution.Minute, "34200000,,,,,0,6,7,8,9,10"), new LeanDataLineTestParameters(new QuoteBar(time.Date, Symbols.BTCUSD, new Bar(1, 2, 3, 4), 5, null, 0, TimeSpan.FromDays(1)) {Ask = null}, SecurityType.Crypto, Resolution.Daily, "20160218 00:00,1,2,3,4,5,,,,,0"), new LeanDataLineTestParameters(new QuoteBar(time, Symbols.BTCUSD, new Bar(1, 2, 3, 4), 5, new Bar(6, 7, 8, 9), 10, TimeSpan.FromMinutes(1)), SecurityType.Crypto, Resolution.Minute, "34200000,1,2,3,4,5,6,7,8,9,10"), new LeanDataLineTestParameters(new QuoteBar(time.Date, Symbols.BTCUSD, new Bar(1, 2, 3, 4), 5, new Bar(6, 7, 8, 9), 10, TimeSpan.FromDays(1)), SecurityType.Crypto, Resolution.Daily, "20160218 00:00,1,2,3,4,5,6,7,8,9,10"), new LeanDataLineTestParameters(new Tick(time, Symbols.BTCUSD, 0, 1, 3) {Value = 2m, TickType = TickType.Quote, BidSize = 2, AskSize = 4, Exchange = "gdax", Suspicious = false}, SecurityType.Crypto, Resolution.Tick, "34200000,1,2,3,4,0"), new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.BTCUSD, Value = 1, Quantity = 2,TickType = TickType.Trade, Exchange = "gdax", Suspicious = false}, SecurityType.Crypto, Resolution.Tick, "34200000,1,2,0"), new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.BTCUSD, Value = 1, Quantity = 2,TickType = TickType.Trade, Exchange = "gdax", Suspicious = true}, SecurityType.Crypto, Resolution.Tick, "34200000,1,2,1"), new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.BTCUSD, BidPrice = 1m, AskPrice = 3m, Value = 2m, TickType = TickType.Quote, BidSize = 2, AskSize = 4, Exchange = "gdax", Suspicious = true}, SecurityType.Crypto, Resolution.Tick, "34200000,1,2,3,4,1"), new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.BTCUSD, BidPrice = 1.25m, AskPrice = 1.50m, Value = 1.375m, TickType = TickType.Quote, BidSize = 2, AskSize = 4, Exchange = "gdax", Suspicious = true}, SecurityType.Crypto, Resolution.Tick, "34200000,1.25,2,1.5,4,1"), new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.BTCUSD, BidPrice = 1.25m, AskPrice = 1.50m, Value = 1.375m, TickType = TickType.Quote, BidSize = 2, AskSize = 4, Exchange = "gdax", Suspicious = false}, SecurityType.Crypto, Resolution.Tick, "34200000,1.25,2,1.5,4,0"), new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.BTCUSD, BidPrice = 1.25m, AskPrice = 1.50m, Value = 1.375m, TickType = TickType.Quote, BidSize = 2, AskSize = 4, Exchange = "gdax", Suspicious = false}, SecurityType.Crypto, Resolution.Tick, "34200000,1.25,2,1.5,4,0"), new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.BTCUSD, BidPrice = -1m, AskPrice = -1m, Value = -1m, TickType = TickType.Quote, BidSize = 0, AskSize = 0, Exchange = "gdax", Suspicious = false}, SecurityType.Crypto, Resolution.Tick, "34200000,-1,0,-1,0,0"), new LeanDataLineTestParameters(new Tick {Time = time, Symbol = Symbols.BTCUSD, BidPrice = -1m, AskPrice = -1m, Value = -1m, TickType = TickType.Quote, BidSize = 0, AskSize = 0, Exchange = "gdax", Suspicious = true}, SecurityType.Crypto, Resolution.Tick, "34200000,-1,0,-1,0,1"), new LeanDataLineTestParameters(new TradeBar(time, Symbols.BTCUSD, 1, 2, 3, 4, 5, TimeSpan.FromMinutes(1)), SecurityType.Crypto, Resolution.Minute, "34200000,1,2,3,4,5"), new LeanDataLineTestParameters(new TradeBar(time.Date, Symbols.BTCUSD, 1, 2, 3, 4, 5, TimeSpan.FromDays(1)), SecurityType.Crypto, Resolution.Daily, "20160218 00:00,1,2,3,4,5"), }.Select(x => new TestCaseData(x).SetName(x.Name)).ToArray(); } private static TestCaseData[] AggregateTradeBarsTestData { get { return new[] { new TestCaseData(TimeSpan.FromMinutes(1), new TradeBar {Open = 10, Close = 9, High = 15, Low = 7, Volume = 200, Period = TimeSpan.FromMinutes(1)}), new TestCaseData(TimeSpan.FromHours(1), new TradeBar {Open = 10, Close = 21, High = 25, Low = 7, Volume = 290, Period = TimeSpan.FromHours(1)}), new TestCaseData(TimeSpan.FromDays(1), new TradeBar {Open = 10, Close = 11, High = 25, Low = 7, Volume = 310, Period = TimeSpan.FromDays(1)}), }; } } private static TestCaseData[] AggregateQuoteBarsTestData { get { return new[] { new TestCaseData(TimeSpan.FromMinutes(1), new QuoteBar {Ask = new Bar {Open = 10, High = 15, Low = 7, Close = 9}, Bid = {Open = 7, High = 14, Low = 4, Close = 5}, Period = TimeSpan.FromMinutes(1)}), new TestCaseData(TimeSpan.FromHours(1), new QuoteBar {Ask = new Bar {Open = 10, High = 25, Low = 7, Close = 21}, Bid = {Open = 7, High = 22, Low = 4, Close = 20}, Period = TimeSpan.FromMinutes(1)}), new TestCaseData(TimeSpan.FromDays(1), new QuoteBar {Ask = new Bar {Open = 10, High = 25, Low = 7, Close = 11}, Bid = {Open = 7, High = 22, Low = 4, Close = 10}, Period = TimeSpan.FromMinutes(1)}), }; } } private static TestCaseData[] AggregateTickTestData { get { return new[] { new TestCaseData(TimeSpan.FromSeconds(1), new QuoteBar {Ask = new Bar {Open = 13, High = 13, Low = 13, Close = 13}, Bid = {Open = 11, High = 11, Low = 11, Close = 11}, Period = TimeSpan.FromSeconds(1)}), new TestCaseData(TimeSpan.FromMinutes(1), new QuoteBar {Ask = new Bar {Open = 13, High = 21, Low = 13, Close = 21}, Bid = {Open = 11, High = 19, Low = 11, Close = 19}, Period = TimeSpan.FromMinutes(1)}), }; } } public class LeanDataTestParameters { public readonly string Name; public readonly Symbol Symbol; public readonly DateTime Date; public readonly Resolution Resolution; public readonly TickType TickType; public readonly Type BaseDataType; public readonly SubscriptionDataConfig Config; public readonly string ExpectedZipFileName; public readonly string ExpectedZipEntryName; public readonly string ExpectedRelativeZipFilePath; public readonly string ExpectedZipFilePath; public SecurityType SecurityType { get { return Symbol.ID.SecurityType; } } public LeanDataTestParameters(Symbol symbol, DateTime date, Resolution resolution, TickType tickType, string expectedZipFileName, string expectedZipEntryName, string expectedRelativeZipFileDirectory = "") { Symbol = symbol; Date = date; Resolution = resolution; TickType = tickType; ExpectedZipFileName = expectedZipFileName; ExpectedZipEntryName = expectedZipEntryName; ExpectedRelativeZipFilePath = Path.Combine(expectedRelativeZipFileDirectory, expectedZipFileName).Replace("/", Path.DirectorySeparatorChar.ToStringInvariant()); ExpectedZipFilePath = Path.Combine(Globals.DataFolder, ExpectedRelativeZipFilePath); Name = SecurityType + "_" + resolution + "_" + symbol.Value + "_" + tickType; BaseDataType = resolution == Resolution.Tick ? typeof(Tick) : typeof(TradeBar); if (symbol.ID.SecurityType == SecurityType.Option && resolution != Resolution.Tick) { BaseDataType = typeof(QuoteBar); } Config = new SubscriptionDataConfig(BaseDataType, symbol, resolution, TimeZones.NewYork, TimeZones.NewYork, true, false, false, false, tickType); } } public class LeanDataLineTestParameters { public readonly string Name; public readonly BaseData Data; public readonly SecurityType SecurityType; public readonly Resolution Resolution; public readonly string ExpectedLine; public readonly SubscriptionDataConfig Config; public readonly TickType TickType; public LeanDataLineTestParameters(BaseData data, SecurityType securityType, Resolution resolution, string expectedLine) { Data = data; SecurityType = securityType; Resolution = resolution; ExpectedLine = expectedLine; if (data is Tick) { var tick = (Tick) data; TickType = tick.TickType; } else if (data is TradeBar) { TickType = TickType.Trade; } else if (data is QuoteBar) { TickType = TickType.Quote; } else { throw new NotImplementedException(); } // override for forex/cfd if (data.Symbol.ID.SecurityType == SecurityType.Forex || data.Symbol.ID.SecurityType == SecurityType.Cfd) { TickType = TickType.Quote; } Config = new SubscriptionDataConfig(Data.GetType(), Data.Symbol, Resolution, TimeZones.Utc, TimeZones.Utc, false, true, false, false, TickType); Name = SecurityType + "_" + data.GetType().Name; if (data.GetType() != typeof (Tick) || Resolution != Resolution.Tick) { Name += "_" + Resolution; } if (data is Tick) { Name += "_" + ((Tick) data).TickType; } } } } }
using System; using System.Collections.Generic; namespace UnityEngine.UI { /// <summary> /// Labels are graphics that display text. /// </summary> [AddComponentMenu("UI/Text", 11)] public class Text : MaskableGraphic, ILayoutElement { [SerializeField] private FontData m_FontData = FontData.defaultFontData; [TextArea(3, 10)][SerializeField] protected string m_Text = String.Empty; private TextGenerator m_TextCache; private TextGenerator m_TextCacheForLayout; private static float kEpsilon = 0.0001f; static protected Material s_DefaultText = null; // We use this flag instead of Unregistering/Registering the callback to avoid allocation. [NonSerialized] private bool m_DisableFontTextureChangedCallback = false; protected Text() { } /// <summary> /// Get or set the material used by this Text. /// </summary> public TextGenerator cachedTextGenerator { get { return m_TextCache ?? (m_TextCache = m_Text.Length != 0 ? new TextGenerator(m_Text.Length) : new TextGenerator()); } } public TextGenerator cachedTextGeneratorForLayout { get { return m_TextCacheForLayout ?? (m_TextCacheForLayout = new TextGenerator()); } } public override Material defaultMaterial { get { if (s_DefaultText == null) s_DefaultText = Canvas.GetDefaultCanvasTextMaterial(); return s_DefaultText; } } /// <summary> /// Text's texture comes from the font. /// </summary> public override Texture mainTexture { get { if (font != null && font.material != null && font.material.mainTexture != null) return font.material.mainTexture; if (m_Material != null) return m_Material.mainTexture; return base.mainTexture; } } public void FontTextureChanged() { // Only invoke if we are not destroyed. if (!this) { FontUpdateTracker.UntrackText(this); return; } if (m_DisableFontTextureChangedCallback) return; cachedTextGenerator.Invalidate(); if (!IsActive()) return; // this is a bit hacky, but it is currently the // cleanest solution.... // if we detect the font texture has changed and are in a rebuild loop // we just regenerate the verts for the new UV's if (CanvasUpdateRegistry.IsRebuildingGraphics() || CanvasUpdateRegistry.IsRebuildingLayout()) UpdateGeometry(); else SetAllDirty(); } public Font font { get { return m_FontData.font; } set { if (m_FontData.font == value) return; FontUpdateTracker.UntrackText(this); m_FontData.font = value; FontUpdateTracker.TrackText(this); SetAllDirty(); } } /// <summary> /// Text that's being displayed by the Text. /// </summary> public virtual string text { get { return m_Text; } set { if (String.IsNullOrEmpty(value)) { if (String.IsNullOrEmpty(m_Text)) return; m_Text = ""; SetVerticesDirty(); } else if (m_Text != value) { m_Text = value; SetVerticesDirty(); SetLayoutDirty(); } } } /// <summary> /// Whether this Text will support rich text. /// </summary> public bool supportRichText { get { return m_FontData.richText; } set { if (m_FontData.richText == value) return; m_FontData.richText = value; SetVerticesDirty(); SetLayoutDirty(); } } /// <summary> /// Wrap mode used by the text. /// </summary> public bool resizeTextForBestFit { get { return m_FontData.bestFit; } set { if (m_FontData.bestFit == value) return; m_FontData.bestFit = value; SetVerticesDirty(); SetLayoutDirty(); } } public int resizeTextMinSize { get { return m_FontData.minSize; } set { if (m_FontData.minSize == value) return; m_FontData.minSize = value; SetVerticesDirty(); SetLayoutDirty(); } } public int resizeTextMaxSize { get { return m_FontData.maxSize; } set { if (m_FontData.maxSize == value) return; m_FontData.maxSize = value; SetVerticesDirty(); SetLayoutDirty(); } } /// <summary> /// Alignment anchor used by the text. /// </summary> public TextAnchor alignment { get { return m_FontData.alignment; } set { if (m_FontData.alignment == value) return; m_FontData.alignment = value; SetVerticesDirty(); SetLayoutDirty(); } } public int fontSize { get { return m_FontData.fontSize; } set { if (m_FontData.fontSize == value) return; m_FontData.fontSize = value; SetVerticesDirty(); SetLayoutDirty(); } } public HorizontalWrapMode horizontalOverflow { get { return m_FontData.horizontalOverflow; } set { if (m_FontData.horizontalOverflow == value) return; m_FontData.horizontalOverflow = value; SetVerticesDirty(); SetLayoutDirty(); } } public VerticalWrapMode verticalOverflow { get { return m_FontData.verticalOverflow; } set { if (m_FontData.verticalOverflow == value) return; m_FontData.verticalOverflow = value; SetVerticesDirty(); SetLayoutDirty(); } } public float lineSpacing { get { return m_FontData.lineSpacing; } set { if (m_FontData.lineSpacing == value) return; m_FontData.lineSpacing = value; SetVerticesDirty(); SetLayoutDirty(); } } /// <summary> /// Font style used by the Text's text. /// </summary> public FontStyle fontStyle { get { return m_FontData.fontStyle; } set { if (m_FontData.fontStyle == value) return; m_FontData.fontStyle = value; SetVerticesDirty(); SetLayoutDirty(); } } public float pixelsPerUnit { get { var localCanvas = canvas; if (!localCanvas) return 1; // For dynamic fonts, ensure we use one pixel per pixel on the screen. if (!font || font.dynamic) return localCanvas.scaleFactor; // For non-dynamic fonts, calculate pixels per unit based on specified font size relative to font object's own font size. if (m_FontData.fontSize <= 0 || font.fontSize <= 0) return 1; return font.fontSize / (float)m_FontData.fontSize; } } protected override void OnEnable() { base.OnEnable(); cachedTextGenerator.Invalidate(); FontUpdateTracker.TrackText(this); } protected override void OnDisable() { FontUpdateTracker.UntrackText(this); base.OnDisable(); } protected override void UpdateGeometry() { if (font != null) { base.UpdateGeometry(); } } #if UNITY_EDITOR protected override void Reset() { font = Resources.GetBuiltinResource<Font>("Arial.ttf"); } #endif public TextGenerationSettings GetGenerationSettings(Vector2 extents) { var settings = new TextGenerationSettings(); // Settings affected by pixels density var pixelsPerUnitCached = pixelsPerUnit; settings.generationExtents = extents * pixelsPerUnitCached + Vector2.one * kEpsilon; if (font != null && font.dynamic) { settings.fontSize = Mathf.Min(Mathf.FloorToInt(m_FontData.fontSize * pixelsPerUnitCached), 1000); settings.resizeTextMinSize = Mathf.Min(Mathf.FloorToInt(m_FontData.minSize * pixelsPerUnitCached), 1000); settings.resizeTextMaxSize = Mathf.Min(Mathf.FloorToInt(m_FontData.maxSize * pixelsPerUnitCached), 1000); } // Other settings settings.textAnchor = m_FontData.alignment; settings.color = color; settings.font = font; settings.pivot = rectTransform.pivot; settings.richText = m_FontData.richText; settings.lineSpacing = m_FontData.lineSpacing; settings.fontStyle = m_FontData.fontStyle; settings.resizeTextForBestFit = m_FontData.bestFit; settings.updateBounds = false; settings.horizontalOverflow = m_FontData.horizontalOverflow; settings.verticalOverflow = m_FontData.verticalOverflow; return settings; } static public Vector2 GetTextAnchorPivot(TextAnchor anchor) { switch (anchor) { case TextAnchor.LowerLeft: return new Vector2(0, 0); case TextAnchor.LowerCenter: return new Vector2(0.5f, 0); case TextAnchor.LowerRight: return new Vector2(1, 0); case TextAnchor.MiddleLeft: return new Vector2(0, 0.5f); case TextAnchor.MiddleCenter: return new Vector2(0.5f, 0.5f); case TextAnchor.MiddleRight: return new Vector2(1, 0.5f); case TextAnchor.UpperLeft: return new Vector2(0, 1); case TextAnchor.UpperCenter: return new Vector2(0.5f, 1); case TextAnchor.UpperRight: return new Vector2(1, 1); default: return Vector2.zero; } } /// <summary> /// Draw the Text. /// </summary> protected override void OnFillVBO(List<UIVertex> vbo) { if (font == null) return; // We dont care if we the font Texture changes while we are doing our Update. // The end result of cachedTextGenerator will be valid for this instance. // Otherwise we can get issues like Case 619238. m_DisableFontTextureChangedCallback = true; Vector2 extents = rectTransform.rect.size; var settings = GetGenerationSettings(extents); cachedTextGenerator.Populate(m_Text, settings); Rect inputRect = rectTransform.rect; // get the text alignment anchor point for the text in local space Vector2 textAnchorPivot = GetTextAnchorPivot(m_FontData.alignment); Vector2 refPoint = Vector2.zero; refPoint.x = (textAnchorPivot.x == 1 ? inputRect.xMax : inputRect.xMin); refPoint.y = (textAnchorPivot.y == 0 ? inputRect.yMin : inputRect.yMax); // Determine fraction of pixel to offset text mesh. Vector2 roundingOffset = PixelAdjustPoint(refPoint) - refPoint; // Apply the offset to the vertices IList<UIVertex> verts = cachedTextGenerator.verts; float unitsPerPixel = 1 / pixelsPerUnit; if (roundingOffset != Vector2.zero) { for (int i = 0; i < verts.Count; i++) { UIVertex uiv = verts[i]; uiv.position *= unitsPerPixel; uiv.position.x += roundingOffset.x; uiv.position.y += roundingOffset.y; vbo.Add(uiv); } } else { for (int i = 0; i < verts.Count; i++) { UIVertex uiv = verts[i]; uiv.position *= unitsPerPixel; vbo.Add(uiv); } } m_DisableFontTextureChangedCallback = false; } public virtual void CalculateLayoutInputHorizontal() { } public virtual void CalculateLayoutInputVertical() { } public virtual float minWidth { get { return 0; } } public virtual float preferredWidth { get { var settings = GetGenerationSettings(Vector2.zero); return cachedTextGeneratorForLayout.GetPreferredWidth(m_Text, settings) / pixelsPerUnit; } } public virtual float flexibleWidth { get { return -1; } } public virtual float minHeight { get { return 0; } } public virtual float preferredHeight { get { var settings = GetGenerationSettings(new Vector2(rectTransform.rect.size.x, 0.0f)); return cachedTextGeneratorForLayout.GetPreferredHeight(m_Text, settings) / pixelsPerUnit; } } public virtual float flexibleHeight { get { return -1; } } public virtual int layoutPriority { get { return 0; } } #if UNITY_EDITOR public override void OnRebuildRequested() { // After a Font asset gets re-imported the managed side gets deleted and recreated, // that means the delegates are not persisted. // so we need to properly enforce a consistent state here. FontUpdateTracker.UntrackText(this); FontUpdateTracker.TrackText(this); // Also the textgenerator is no longer valid. cachedTextGenerator.Invalidate(); base.OnRebuildRequested(); } #endif // if UNITY_EDITOR } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #region Using directives using System; using System.Collections.Generic; using System.Globalization; using System.Management.Automation; using Microsoft.PowerShell.Commands; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// Enables the user to subscribe to indications using Filter Expression or /// Query Expression. /// -SourceIdentifier is a name given to the subscription /// The Cmdlet should return a PS EventSubscription object that can be used to /// cancel the subscription /// Should we have the second parameter set with a -Query? /// </summary> [Cmdlet(VerbsLifecycle.Register, "CimIndicationEvent", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227960")] public class RegisterCimIndicationCommand : ObjectEventRegistrationBase { #region parameters /// <summary> /// <para> /// The following is the definition of the input parameter "Namespace". /// Specifies the NameSpace under which to look for the specified class name. /// </para> /// <para> /// Default value is root\cimv2 /// </para> /// </summary> [Parameter] public string Namespace { get { return nameSpace; } set { nameSpace = value; } } private string nameSpace; /// <summary> /// The following is the definition of the input parameter "ClassName". /// Specifies the Class Name to register the indication on. /// </summary> [Parameter( Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter(Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] public string ClassName { get { return className; } set { className = value; this.SetParameter(value, nameClassName); } } private string className; /// <summary> /// The following is the definition of the input parameter "Query". /// The Query Expression to pass. /// </summary> [Parameter( Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] [Parameter( Mandatory = true, Position = 0, ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] public string Query { get { return query; } set { query = value; this.SetParameter(value, nameQuery); } } private string query; /// <summary> /// <para> /// The following is the definition of the input parameter "QueryDialect". /// Specifies the dialect used by the query Engine that interprets the Query /// string. /// </para> /// </summary> [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] public string QueryDialect { get { return queryDialect; } set { queryDialect = value; this.SetParameter(value, nameQueryDialect); } } private string queryDialect; /// <summary> /// The following is the definition of the input parameter "OperationTimeoutSec". /// Enables the user to specify the operation timeout in Seconds. This value /// overwrites the value specified by the CimSession Operation timeout. /// </summary> [Alias(CimBaseCommand.AliasOT)] [Parameter] public UInt32 OperationTimeoutSec { get { return operationTimeout; } set { operationTimeout = value; } } private UInt32 operationTimeout; /// <summary> /// The following is the definition of the input parameter "Session". /// Uses a CimSession context. /// </summary> [Parameter( Mandatory = true, ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)] [Parameter( Mandatory = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] public CimSession CimSession { get { return cimSession; } set { cimSession = value; this.SetParameter(value, nameCimSession); } } private CimSession cimSession; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Specifies the computer on which the commands associated with this session /// will run. The default value is LocalHost. /// </summary> [Alias(CimBaseCommand.AliasCN, CimBaseCommand.AliasServerName)] [Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)] [Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)] public string ComputerName { get { return computername; } set { computername = value; this.SetParameter(value, nameComputerName); } } private string computername; #endregion /// <summary> /// Returns the object that generates events to be monitored. /// </summary> protected override object GetSourceObject() { CimIndicationWatcher watcher = null; string parameterSetName = null; try { parameterSetName = this.parameterBinder.GetParameterSet(); } finally { this.parameterBinder.reset(); } string tempQueryExpression = string.Empty; switch (parameterSetName) { case CimBaseCommand.QueryExpressionSessionSet: case CimBaseCommand.QueryExpressionComputerSet: tempQueryExpression = this.Query; break; case CimBaseCommand.ClassNameSessionSet: case CimBaseCommand.ClassNameComputerSet: // validate the classname this.CheckArgument(); tempQueryExpression = string.Format(CultureInfo.CurrentCulture, "Select * from {0}", this.ClassName); break; } switch (parameterSetName) { case CimBaseCommand.QueryExpressionSessionSet: case CimBaseCommand.ClassNameSessionSet: { watcher = new CimIndicationWatcher(this.CimSession, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); } break; case CimBaseCommand.QueryExpressionComputerSet: case CimBaseCommand.ClassNameComputerSet: { watcher = new CimIndicationWatcher(this.ComputerName, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec); } break; } if (watcher != null) { watcher.SetCmdlet(this); } return watcher; } /// <summary> /// Returns the event name to be monitored on the input object. /// </summary> protected override string GetSourceObjectEventName() { return "CimIndicationArrived"; } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { DebugHelper.WriteLogEx(); base.EndProcessing(); // Register for the "Unsubscribed" event so that we can stop the // Cimindication event watcher. PSEventSubscriber newSubscriber = NewSubscriber; if (newSubscriber != null) { DebugHelper.WriteLog("RegisterCimIndicationCommand::EndProcessing subscribe to Unsubscribed event", 4); newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed); } } /// <summary> /// <para> /// Handler to handle unsubscribe event /// </para> /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void newSubscriber_Unsubscribed( object sender, PSEventUnsubscribedEventArgs e) { DebugHelper.WriteLogEx(); CimIndicationWatcher watcher = sender as CimIndicationWatcher; if (watcher != null) { watcher.Stop(); } } #region private members /// <summary> /// Check argument value. /// </summary> private void CheckArgument() { this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); } /// <summary> /// Parameter binder used to resolve parameter set name. /// </summary> private ParameterBinder parameterBinder = new ParameterBinder( parameters, parameterSets); /// <summary> /// Set the parameter. /// </summary> /// <param name="parameterName"></param> private void SetParameter(object value, string parameterName) { if (value == null) { return; } this.parameterBinder.SetParameter(parameterName, true); } #region const string of parameter names internal const string nameClassName = "ClassName"; internal const string nameQuery = "Query"; internal const string nameQueryDialect = "QueryDialect"; internal const string nameCimSession = "CimSession"; internal const string nameComputerName = "ComputerName"; #endregion /// <summary> /// Static parameter definition entries. /// </summary> static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>> { { nameClassName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), } }, { nameQuery, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, true), } }, { nameQueryDialect, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false), } }, { nameCimSession, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), } }, { nameComputerName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), } }, }; /// <summary> /// Static parameter set entries. /// </summary> static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry> { { CimBaseCommand.QueryExpressionSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.QueryExpressionComputerSet, new ParameterSetEntry(1) }, { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) }, }; #endregion } }
#region License /* * RequestStream.cs * * This code is derived from System.Net.RequestStream.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.IO; namespace WebSocketSharp.Net { internal class RequestStream : Stream { #region Private Fields private byte [] _buffer; private bool _disposed; private int _length; private int _offset; private long _remainingBody; private Stream _stream; #endregion #region Internal Constructors internal RequestStream (Stream stream, byte [] buffer, int offset, int length) : this (stream, buffer, offset, length, -1) { } internal RequestStream ( Stream stream, byte [] buffer, int offset, int length, long contentlength) { _stream = stream; _buffer = buffer; _offset = offset; _length = length; _remainingBody = contentlength; } #endregion #region Public Properties public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { throw new NotSupportedException (); } } public override long Position { get { throw new NotSupportedException (); } set { throw new NotSupportedException (); } } #endregion #region Private Methods // Returns 0 if we can keep reading from the base stream, // > 0 if we read something from the buffer. // -1 if we had a content length set and we finished reading that many bytes. private int fillFromBuffer (byte [] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "Less than zero."); if (count < 0) throw new ArgumentOutOfRangeException ("count", "Less than zero."); var len = buffer.Length; if (offset > len) throw new ArgumentException ("'offset' is greater than 'buffer' size."); if (offset > len - count) throw new ArgumentException ("Reading would overrun 'buffer'."); if (_remainingBody == 0) return -1; if (_length == 0) return 0; var size = _length < count ? _length : count; if (_remainingBody > 0 && _remainingBody < size) size = (int) _remainingBody; var remainingBuffer = _buffer.Length - _offset; if (remainingBuffer < size) size = remainingBuffer; if (size == 0) return 0; Buffer.BlockCopy (_buffer, _offset, buffer, offset, size); _offset += size; _length -= size; if (_remainingBody > 0) _remainingBody -= size; return size; } #endregion #region Public Methods public override IAsyncResult BeginRead ( byte [] buffer, int offset, int count, AsyncCallback callback, object state) { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); var nread = fillFromBuffer (buffer, offset, count); if (nread > 0 || nread == -1) { var ares = new HttpStreamAsyncResult (callback, state); ares.Buffer = buffer; ares.Offset = offset; ares.Count = count; ares.SyncRead = nread > 0 ? nread : 0; ares.Complete (); return ares; } // Avoid reading past the end of the request to allow for HTTP pipelining. if (_remainingBody >= 0 && _remainingBody < count) count = (int) _remainingBody; return _stream.BeginRead (buffer, offset, count, callback, state); } public override IAsyncResult BeginWrite ( byte [] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException (); } public override void Close () { _disposed = true; } public override int EndRead (IAsyncResult asyncResult) { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); if (asyncResult == null) throw new ArgumentNullException ("asyncResult"); if (asyncResult is HttpStreamAsyncResult) { var ares = (HttpStreamAsyncResult) asyncResult; if (!ares.IsCompleted) ares.AsyncWaitHandle.WaitOne (); return ares.SyncRead; } // Close on exception? var nread = _stream.EndRead (asyncResult); if (nread > 0 && _remainingBody > 0) _remainingBody -= nread; return nread; } public override void EndWrite (IAsyncResult asyncResult) { throw new NotSupportedException (); } public override void Flush () { } public override int Read (byte [] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); // Call fillFromBuffer to check for buffer boundaries even when // _remainingBody is 0. var nread = fillFromBuffer (buffer, offset, count); if (nread == -1) // No more bytes available (Content-Length). return 0; if (nread > 0) return nread; nread = _stream.Read (buffer, offset, count); if (nread > 0 && _remainingBody > 0) _remainingBody -= nread; return nread; } public override long Seek (long offset, SeekOrigin origin) { throw new NotSupportedException (); } public override void SetLength (long value) { throw new NotSupportedException (); } public override void Write (byte [] buffer, int offset, int count) { throw new NotSupportedException (); } #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.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Runtime.Serialization; namespace System.Data { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DataException : SystemException { protected DataException(SerializationInfo info, StreamingContext context) : base(info, context) { } public DataException() : base(SR.DataSet_DefaultDataException) { HResult = HResults.Data; } public DataException(string s) : base(s) { HResult = HResults.Data; } public DataException(string s, Exception innerException) : base(s, innerException) { } }; [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ConstraintException : DataException { protected ConstraintException(SerializationInfo info, StreamingContext context) : base(info, context) { } public ConstraintException() : base(SR.DataSet_DefaultConstraintException) { HResult = HResults.DataConstraint; } public ConstraintException(string s) : base(s) { HResult = HResults.DataConstraint; } public ConstraintException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataConstraint; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DeletedRowInaccessibleException : DataException { protected DeletedRowInaccessibleException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Initializes a new instance of the <see cref='System.Data.DeletedRowInaccessibleException'/> class. /// </summary> public DeletedRowInaccessibleException() : base(SR.DataSet_DefaultDeletedRowInaccessibleException) { HResult = HResults.DataDeletedRowInaccessible; } /// <summary> /// Initializes a new instance of the <see cref='System.Data.DeletedRowInaccessibleException'/> class with the specified string. /// </summary> public DeletedRowInaccessibleException(string s) : base(s) { HResult = HResults.DataDeletedRowInaccessible; } public DeletedRowInaccessibleException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataDeletedRowInaccessible; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DuplicateNameException : DataException { protected DuplicateNameException(SerializationInfo info, StreamingContext context) : base(info, context) { } public DuplicateNameException() : base(SR.DataSet_DefaultDuplicateNameException) { HResult = HResults.DataDuplicateName; } public DuplicateNameException(string s) : base(s) { HResult = HResults.DataDuplicateName; } public DuplicateNameException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataDuplicateName; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InRowChangingEventException : DataException { protected InRowChangingEventException(SerializationInfo info, StreamingContext context) : base(info, context) { } public InRowChangingEventException() : base(SR.DataSet_DefaultInRowChangingEventException) { HResult = HResults.DataInRowChangingEvent; } public InRowChangingEventException(string s) : base(s) { HResult = HResults.DataInRowChangingEvent; } public InRowChangingEventException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataInRowChangingEvent; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidConstraintException : DataException { protected InvalidConstraintException(SerializationInfo info, StreamingContext context) : base(info, context) { } public InvalidConstraintException() : base(SR.DataSet_DefaultInvalidConstraintException) { HResult = HResults.DataInvalidConstraint; } public InvalidConstraintException(string s) : base(s) { HResult = HResults.DataInvalidConstraint; } public InvalidConstraintException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataInvalidConstraint; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingPrimaryKeyException : DataException { protected MissingPrimaryKeyException(SerializationInfo info, StreamingContext context) : base(info, context) { } public MissingPrimaryKeyException() : base(SR.DataSet_DefaultMissingPrimaryKeyException) { HResult = HResults.DataMissingPrimaryKey; } public MissingPrimaryKeyException(string s) : base(s) { HResult = HResults.DataMissingPrimaryKey; } public MissingPrimaryKeyException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataMissingPrimaryKey; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class NoNullAllowedException : DataException { protected NoNullAllowedException(SerializationInfo info, StreamingContext context) : base(info, context) { } public NoNullAllowedException() : base(SR.DataSet_DefaultNoNullAllowedException) { HResult = HResults.DataNoNullAllowed; } public NoNullAllowedException(string s) : base(s) { HResult = HResults.DataNoNullAllowed; } public NoNullAllowedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataNoNullAllowed; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ReadOnlyException : DataException { protected ReadOnlyException(SerializationInfo info, StreamingContext context) : base(info, context) { } public ReadOnlyException() : base(SR.DataSet_DefaultReadOnlyException) { HResult = HResults.DataReadOnly; } public ReadOnlyException(string s) : base(s) { HResult = HResults.DataReadOnly; } public ReadOnlyException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataReadOnly; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class RowNotInTableException : DataException { protected RowNotInTableException(SerializationInfo info, StreamingContext context) : base(info, context) { } public RowNotInTableException() : base(SR.DataSet_DefaultRowNotInTableException) { HResult = HResults.DataRowNotInTable; } public RowNotInTableException(string s) : base(s) { HResult = HResults.DataRowNotInTable; } public RowNotInTableException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataRowNotInTable; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class VersionNotFoundException : DataException { protected VersionNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } public VersionNotFoundException() : base(SR.DataSet_DefaultVersionNotFoundException) { HResult = HResults.DataVersionNotFound; } public VersionNotFoundException(string s) : base(s) { HResult = HResults.DataVersionNotFound; } public VersionNotFoundException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.DataVersionNotFound; } } internal static class ExceptionBuilder { // The class defines the exceptions that are specific to the DataSet. // The class contains functions that take the proper informational variables and then construct // the appropriate exception with an error string obtained from the resource Data.txt. // The exception is then returned to the caller, so that the caller may then throw from its // location so that the catcher of the exception will have the appropriate call stack. // This class is used so that there will be compile time checking of error messages. // The resource Data.txt will ensure proper string text based on the appropriate locale. // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it private static void TraceException(string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); if (e != null) { DataCommonEventSource.Log.Trace(trace, e); } } internal static Exception TraceExceptionAsReturnValue(Exception e) { TraceException("<comm.ADP.TraceException|ERR|THROW> '{0}'", e); return e; } internal static Exception TraceExceptionForCapture(Exception e) { TraceException("<comm.ADP.TraceException|ERR|CATCH> '{0}'", e); return e; } internal static Exception TraceExceptionWithoutRethrow(Exception e) { TraceException("<comm.ADP.TraceException|ERR|CATCH> '{0}'", e); return e; } internal static Exception _Argument(string error) => TraceExceptionAsReturnValue(new ArgumentException(error)); internal static Exception _Argument(string paramName, string error) => TraceExceptionAsReturnValue(new ArgumentException(error)); internal static Exception _Argument(string error, Exception innerException) => TraceExceptionAsReturnValue(new ArgumentException(error, innerException)); private static Exception _ArgumentNull(string paramName, string msg) => TraceExceptionAsReturnValue(new ArgumentNullException(paramName, msg)); internal static Exception _ArgumentOutOfRange(string paramName, string msg) => TraceExceptionAsReturnValue(new ArgumentOutOfRangeException(paramName, msg)); private static Exception _IndexOutOfRange(string error) => TraceExceptionAsReturnValue(new IndexOutOfRangeException(error)); private static Exception _InvalidOperation(string error) => TraceExceptionAsReturnValue(new InvalidOperationException(error)); private static Exception _InvalidEnumArgumentException(string error) => TraceExceptionAsReturnValue(new InvalidEnumArgumentException(error)); private static Exception _InvalidEnumArgumentException<T>(T value) => _InvalidEnumArgumentException(SR.Format(SR.ADP_InvalidEnumerationValue, typeof(T).Name, value.ToString())); // // System.Data exceptions // private static void ThrowDataException(string error, Exception innerException) { throw TraceExceptionAsReturnValue(new DataException(error, innerException)); } private static Exception _Data(string error) => TraceExceptionAsReturnValue(new DataException(error)); private static Exception _Constraint(string error) => TraceExceptionAsReturnValue(new ConstraintException(error)); private static Exception _InvalidConstraint(string error) => TraceExceptionAsReturnValue(new InvalidConstraintException(error)); private static Exception _DeletedRowInaccessible(string error) => TraceExceptionAsReturnValue(new DeletedRowInaccessibleException(error)); private static Exception _DuplicateName(string error) => TraceExceptionAsReturnValue(new DuplicateNameException(error)); private static Exception _InRowChangingEvent(string error) => TraceExceptionAsReturnValue(new InRowChangingEventException(error)); private static Exception _MissingPrimaryKey(string error) => TraceExceptionAsReturnValue(new MissingPrimaryKeyException(error)); private static Exception _NoNullAllowed(string error) => TraceExceptionAsReturnValue(new NoNullAllowedException(error)); private static Exception _ReadOnly(string error) => TraceExceptionAsReturnValue(new ReadOnlyException(error)); private static Exception _RowNotInTable(string error) => TraceExceptionAsReturnValue(new RowNotInTableException(error)); private static Exception _VersionNotFound(string error) => TraceExceptionAsReturnValue(new VersionNotFoundException(error)); public static Exception ArgumentNull(string paramName) => _ArgumentNull(paramName, SR.Format(SR.Data_ArgumentNull, paramName)); public static Exception ArgumentOutOfRange(string paramName) => _ArgumentOutOfRange(paramName, SR.Format(SR.Data_ArgumentOutOfRange, paramName)); public static Exception BadObjectPropertyAccess(string error) => _InvalidOperation(SR.Format(SR.DataConstraint_BadObjectPropertyAccess, error)); public static Exception ArgumentContainsNull(string paramName) => _Argument(paramName, SR.Format(SR.Data_ArgumentContainsNull, paramName)); // // Collections // public static Exception CannotModifyCollection() => _Argument(SR.Data_CannotModifyCollection); public static Exception CaseInsensitiveNameConflict(string name) => _Argument(SR.Format(SR.Data_CaseInsensitiveNameConflict, name)); public static Exception NamespaceNameConflict(string name) => _Argument(SR.Format(SR.Data_NamespaceNameConflict, name)); public static Exception InvalidOffsetLength() => _Argument(SR.Data_InvalidOffsetLength); // // DataColumnCollection // public static Exception ColumnNotInTheTable(string column, string table) => _Argument(SR.Format(SR.DataColumn_NotInTheTable, column, table)); public static Exception ColumnNotInAnyTable() => _Argument(SR.DataColumn_NotInAnyTable); public static Exception ColumnOutOfRange(int index) => _IndexOutOfRange(SR.Format(SR.DataColumns_OutOfRange, (index).ToString(CultureInfo.InvariantCulture))); public static Exception ColumnOutOfRange(string column) => _IndexOutOfRange(SR.Format(SR.DataColumns_OutOfRange, column)); public static Exception CannotAddColumn1(string column) => _Argument(SR.Format(SR.DataColumns_Add1, column)); public static Exception CannotAddColumn2(string column) => _Argument(SR.Format(SR.DataColumns_Add2, column)); public static Exception CannotAddColumn3() => _Argument(SR.DataColumns_Add3); public static Exception CannotAddColumn4(string column) => _Argument(SR.Format(SR.DataColumns_Add4, column)); public static Exception CannotAddDuplicate(string column) => _DuplicateName(SR.Format(SR.DataColumns_AddDuplicate, column)); public static Exception CannotAddDuplicate2(string table) => _DuplicateName(SR.Format(SR.DataColumns_AddDuplicate2, table)); public static Exception CannotAddDuplicate3(string table) => _DuplicateName(SR.Format(SR.DataColumns_AddDuplicate3, table)); public static Exception CannotRemoveColumn() => _Argument(SR.DataColumns_Remove); public static Exception CannotRemovePrimaryKey() => _Argument(SR.DataColumns_RemovePrimaryKey); public static Exception CannotRemoveChildKey(string relation) => _Argument(SR.Format(SR.DataColumns_RemoveChildKey, relation)); public static Exception CannotRemoveConstraint(string constraint, string table) => _Argument(SR.Format(SR.DataColumns_RemoveConstraint, constraint, table)); public static Exception CannotRemoveExpression(string column, string expression) => _Argument(SR.Format(SR.DataColumns_RemoveExpression, column, expression)); public static Exception ColumnNotInTheUnderlyingTable(string column, string table) => _Argument(SR.Format(SR.DataColumn_NotInTheUnderlyingTable, column, table)); public static Exception InvalidOrdinal(string name, int ordinal) => _ArgumentOutOfRange(name, SR.Format(SR.DataColumn_OrdinalExceedMaximun, (ordinal).ToString(CultureInfo.InvariantCulture))); // // _Constraint and ConstrainsCollection // public static Exception AddPrimaryKeyConstraint() => _Argument(SR.DataConstraint_AddPrimaryKeyConstraint); public static Exception NoConstraintName() => _Argument(SR.DataConstraint_NoName); public static Exception ConstraintViolation(string constraint) => _Constraint(SR.Format(SR.DataConstraint_Violation, constraint)); public static Exception ConstraintNotInTheTable(string constraint) => _Argument(SR.Format(SR.DataConstraint_NotInTheTable, constraint)); public static string KeysToString(object[] keys) { string values = string.Empty; for (int i = 0; i < keys.Length; i++) { values += Convert.ToString(keys[i], null) + (i < keys.Length - 1 ? ", " : string.Empty); } return values; } public static string UniqueConstraintViolationText(DataColumn[] columns, object[] values) { if (columns.Length > 1) { string columnNames = string.Empty; for (int i = 0; i < columns.Length; i++) { columnNames += columns[i].ColumnName + (i < columns.Length - 1 ? ", " : ""); } return SR.Format(SR.DataConstraint_ViolationValue, columnNames, KeysToString(values)); } else { return SR.Format(SR.DataConstraint_ViolationValue, columns[0].ColumnName, Convert.ToString(values[0], null)); } } public static Exception ConstraintViolation(DataColumn[] columns, object[] values) => _Constraint(UniqueConstraintViolationText(columns, values)); public static Exception ConstraintOutOfRange(int index) => _IndexOutOfRange(SR.Format(SR.DataConstraint_OutOfRange, (index).ToString(CultureInfo.InvariantCulture))); public static Exception DuplicateConstraint(string constraint) => _Data(SR.Format(SR.DataConstraint_Duplicate, constraint)); public static Exception DuplicateConstraintName(string constraint) => _DuplicateName(SR.Format(SR.DataConstraint_DuplicateName, constraint)); public static Exception NeededForForeignKeyConstraint(UniqueConstraint key, ForeignKeyConstraint fk) => _Argument(SR.Format(SR.DataConstraint_NeededForForeignKeyConstraint, key.ConstraintName, fk.ConstraintName)); public static Exception UniqueConstraintViolation() => _Argument(SR.DataConstraint_UniqueViolation); public static Exception ConstraintForeignTable() => _Argument(SR.DataConstraint_ForeignTable); public static Exception ConstraintParentValues() => _Argument(SR.DataConstraint_ParentValues); public static Exception ConstraintAddFailed(DataTable table) => _InvalidConstraint(SR.Format(SR.DataConstraint_AddFailed, table.TableName)); public static Exception ConstraintRemoveFailed() => _Argument(SR.DataConstraint_RemoveFailed); public static Exception FailedCascadeDelete(string constraint) => _InvalidConstraint(SR.Format(SR.DataConstraint_CascadeDelete, constraint)); public static Exception FailedCascadeUpdate(string constraint) => _InvalidConstraint(SR.Format(SR.DataConstraint_CascadeUpdate, constraint)); public static Exception FailedClearParentTable(string table, string constraint, string childTable) => _InvalidConstraint(SR.Format(SR.DataConstraint_ClearParentTable, table, constraint, childTable)); public static Exception ForeignKeyViolation(string constraint, object[] keys) => _InvalidConstraint(SR.Format(SR.DataConstraint_ForeignKeyViolation, constraint, KeysToString(keys))); public static Exception RemoveParentRow(ForeignKeyConstraint constraint) => _InvalidConstraint(SR.Format(SR.DataConstraint_RemoveParentRow, constraint.ConstraintName)); public static string MaxLengthViolationText(string columnName) => SR.Format(SR.DataColumn_ExceedMaxLength, columnName); public static string NotAllowDBNullViolationText(string columnName) => SR.Format(SR.DataColumn_NotAllowDBNull, columnName); public static Exception CantAddConstraintToMultipleNestedTable(string tableName) => _Argument(SR.Format(SR.DataConstraint_CantAddConstraintToMultipleNestedTable, tableName)); // // DataColumn Set Properties conflicts // public static Exception AutoIncrementAndExpression() => _Argument(SR.DataColumn_AutoIncrementAndExpression); public static Exception AutoIncrementAndDefaultValue() => _Argument(SR.DataColumn_AutoIncrementAndDefaultValue); public static Exception AutoIncrementSeed() => _Argument(SR.DataColumn_AutoIncrementSeed); public static Exception CantChangeDataType() => _Argument(SR.DataColumn_ChangeDataType); public static Exception NullDataType() => _Argument(SR.DataColumn_NullDataType); public static Exception ColumnNameRequired() => _Argument(SR.DataColumn_NameRequired); public static Exception DefaultValueAndAutoIncrement() => _Argument(SR.DataColumn_DefaultValueAndAutoIncrement); public static Exception DefaultValueDataType(string column, Type defaultType, Type columnType, Exception inner) => column.Length == 0 ? _Argument(SR.Format(SR.DataColumn_DefaultValueDataType1, defaultType.FullName, columnType.FullName), inner) : _Argument(SR.Format(SR.DataColumn_DefaultValueDataType, column, defaultType.FullName, columnType.FullName), inner); public static Exception DefaultValueColumnDataType(string column, Type defaultType, Type columnType, Exception inner) => _Argument(SR.Format(SR.DataColumn_DefaultValueColumnDataType, column, defaultType.FullName, columnType.FullName), inner); public static Exception ExpressionAndUnique() => _Argument(SR.DataColumn_ExpressionAndUnique); public static Exception ExpressionAndReadOnly() => _Argument(SR.DataColumn_ExpressionAndReadOnly); public static Exception ExpressionAndConstraint(DataColumn column, Constraint constraint) => _Argument(SR.Format(SR.DataColumn_ExpressionAndConstraint, column.ColumnName, constraint.ConstraintName)); public static Exception ExpressionInConstraint(DataColumn column) => _Argument(SR.Format(SR.DataColumn_ExpressionInConstraint, column.ColumnName)); public static Exception ExpressionCircular() => _Argument(SR.DataColumn_ExpressionCircular); public static Exception NonUniqueValues(string column) => _InvalidConstraint(SR.Format(SR.DataColumn_NonUniqueValues, column)); public static Exception NullKeyValues(string column) => _Data(SR.Format(SR.DataColumn_NullKeyValues, column)); public static Exception NullValues(string column) => _NoNullAllowed(SR.Format(SR.DataColumn_NullValues, column)); public static Exception ReadOnlyAndExpression() => _ReadOnly(SR.DataColumn_ReadOnlyAndExpression); public static Exception ReadOnly(string column) => _ReadOnly(SR.Format(SR.DataColumn_ReadOnly, column)); public static Exception UniqueAndExpression() => _Argument(SR.DataColumn_UniqueAndExpression); public static Exception SetFailed(object value, DataColumn column, Type type, Exception innerException) => _Argument(innerException.Message + SR.Format(SR.DataColumn_SetFailed, value.ToString(), column.ColumnName, type.Name), innerException); public static Exception CannotSetToNull(DataColumn column) => _Argument(SR.Format(SR.DataColumn_CannotSetToNull, column.ColumnName)); public static Exception LongerThanMaxLength(DataColumn column) => _Argument(SR.Format(SR.DataColumn_LongerThanMaxLength, column.ColumnName)); public static Exception CannotSetMaxLength(DataColumn column, int value) => _Argument(SR.Format(SR.DataColumn_CannotSetMaxLength, column.ColumnName, value.ToString(CultureInfo.InvariantCulture))); public static Exception CannotSetMaxLength2(DataColumn column) => _Argument(SR.Format(SR.DataColumn_CannotSetMaxLength2, column.ColumnName)); public static Exception CannotSetSimpleContentType(string columnName, Type type) => _Argument(SR.Format(SR.DataColumn_CannotSimpleContentType, columnName, type)); public static Exception CannotSetSimpleContent(string columnName, Type type) => _Argument(SR.Format(SR.DataColumn_CannotSimpleContent, columnName, type)); public static Exception CannotChangeNamespace(string columnName) => _Argument(SR.Format(SR.DataColumn_CannotChangeNamespace, columnName)); public static Exception HasToBeStringType(DataColumn column) => _Argument(SR.Format(SR.DataColumn_HasToBeStringType, column.ColumnName)); public static Exception AutoIncrementCannotSetIfHasData(string typeName) => _Argument(SR.Format(SR.DataColumn_AutoIncrementCannotSetIfHasData, typeName)); public static Exception INullableUDTwithoutStaticNull(string typeName) => _Argument(SR.Format(SR.DataColumn_INullableUDTwithoutStaticNull, typeName)); public static Exception IComparableNotImplemented(string typeName) => _Data(SR.Format(SR.DataStorage_IComparableNotDefined, typeName)); public static Exception UDTImplementsIChangeTrackingButnotIRevertible(string typeName) => _InvalidOperation(SR.Format(SR.DataColumn_UDTImplementsIChangeTrackingButnotIRevertible, typeName)); public static Exception SetAddedAndModifiedCalledOnnonUnchanged() => _InvalidOperation(SR.DataColumn_SetAddedAndModifiedCalledOnNonUnchanged); public static Exception InvalidDataColumnMapping(Type type) => _Argument(SR.Format(SR.DataColumn_InvalidDataColumnMapping, type.AssemblyQualifiedName)); public static Exception CannotSetDateTimeModeForNonDateTimeColumns() => _InvalidOperation(SR.DataColumn_CannotSetDateTimeModeForNonDateTimeColumns); public static Exception InvalidDateTimeMode(DataSetDateTime mode) => _InvalidEnumArgumentException(mode); public static Exception CantChangeDateTimeMode(DataSetDateTime oldValue, DataSetDateTime newValue) => _InvalidOperation(SR.Format(SR.DataColumn_DateTimeMode, oldValue.ToString(), newValue.ToString())); public static Exception ColumnTypeNotSupported() => Common.ADP.NotSupported(SR.DataColumn_NullableTypesNotSupported); // // DataView // public static Exception SetFailed(string name) => _Data(SR.Format(SR.DataView_SetFailed, name)); public static Exception SetDataSetFailed() => _Data(SR.DataView_SetDataSetFailed); public static Exception SetRowStateFilter() => _Data(SR.DataView_SetRowStateFilter); public static Exception CanNotSetDataSet() => _Data(SR.DataView_CanNotSetDataSet); public static Exception CanNotUseDataViewManager() => _Data(SR.DataView_CanNotUseDataViewManager); public static Exception CanNotSetTable() => _Data(SR.DataView_CanNotSetTable); public static Exception CanNotUse() => _Data(SR.DataView_CanNotUse); public static Exception CanNotBindTable() => _Data(SR.DataView_CanNotBindTable); public static Exception SetTable() => _Data(SR.DataView_SetTable); public static Exception SetIListObject() => _Argument(SR.DataView_SetIListObject); public static Exception AddNewNotAllowNull() => _Data(SR.DataView_AddNewNotAllowNull); public static Exception NotOpen() => _Data(SR.DataView_NotOpen); public static Exception CreateChildView() => _Argument(SR.DataView_CreateChildView); public static Exception CanNotDelete() => _Data(SR.DataView_CanNotDelete); public static Exception CanNotEdit() => _Data(SR.DataView_CanNotEdit); public static Exception GetElementIndex(int index) => _IndexOutOfRange(SR.Format(SR.DataView_GetElementIndex, (index).ToString(CultureInfo.InvariantCulture))); public static Exception AddExternalObject() => _Argument(SR.DataView_AddExternalObject); public static Exception CanNotClear() => _Argument(SR.DataView_CanNotClear); public static Exception InsertExternalObject() => _Argument(SR.DataView_InsertExternalObject); public static Exception RemoveExternalObject() => _Argument(SR.DataView_RemoveExternalObject); public static Exception PropertyNotFound(string property, string table) => _Argument(SR.Format(SR.DataROWView_PropertyNotFound, property, table)); public static Exception ColumnToSortIsOutOfRange(string column) => _Argument(SR.Format(SR.DataColumns_OutOfRange, column)); // // Keys // public static Exception KeyTableMismatch() => _InvalidConstraint(SR.DataKey_TableMismatch); public static Exception KeyNoColumns() => _InvalidConstraint(SR.DataKey_NoColumns); public static Exception KeyTooManyColumns(int cols) => _InvalidConstraint(SR.Format(SR.DataKey_TooManyColumns, (cols).ToString(CultureInfo.InvariantCulture))); public static Exception KeyDuplicateColumns(string columnName) => _InvalidConstraint(SR.Format(SR.DataKey_DuplicateColumns, columnName)); // // Relations, constraints // public static Exception RelationDataSetMismatch() => _InvalidConstraint(SR.DataRelation_DataSetMismatch); public static Exception NoRelationName() => _Argument(SR.DataRelation_NoName); public static Exception ColumnsTypeMismatch() => _InvalidConstraint(SR.DataRelation_ColumnsTypeMismatch); public static Exception KeyLengthMismatch() => _Argument(SR.DataRelation_KeyLengthMismatch); public static Exception KeyLengthZero() => _Argument(SR.DataRelation_KeyZeroLength); public static Exception ForeignRelation() => _Argument(SR.DataRelation_ForeignDataSet); public static Exception KeyColumnsIdentical() => _InvalidConstraint(SR.DataRelation_KeyColumnsIdentical); public static Exception RelationForeignTable(string t1, string t2) => _InvalidConstraint(SR.Format(SR.DataRelation_ForeignTable, t1, t2)); public static Exception GetParentRowTableMismatch(string t1, string t2) => _InvalidConstraint(SR.Format(SR.DataRelation_GetParentRowTableMismatch, t1, t2)); public static Exception SetParentRowTableMismatch(string t1, string t2) => _InvalidConstraint(SR.Format(SR.DataRelation_SetParentRowTableMismatch, t1, t2)); public static Exception RelationForeignRow() => _Argument(SR.DataRelation_ForeignRow); public static Exception RelationNestedReadOnly() => _Argument(SR.DataRelation_RelationNestedReadOnly); public static Exception TableCantBeNestedInTwoTables(string tableName) => _Argument(SR.Format(SR.DataRelation_TableCantBeNestedInTwoTables, tableName)); public static Exception LoopInNestedRelations(string tableName) => _Argument(SR.Format(SR.DataRelation_LoopInNestedRelations, tableName)); public static Exception RelationDoesNotExist() => _Argument(SR.DataRelation_DoesNotExist); public static Exception ParentRowNotInTheDataSet() => _Argument(SR.DataRow_ParentRowNotInTheDataSet); public static Exception ParentOrChildColumnsDoNotHaveDataSet() => _InvalidConstraint(SR.DataRelation_ParentOrChildColumnsDoNotHaveDataSet); public static Exception InValidNestedRelation(string childTableName) => _InvalidOperation(SR.Format(SR.DataRelation_InValidNestedRelation, childTableName)); public static Exception InvalidParentNamespaceinNestedRelation(string childTableName) => _InvalidOperation(SR.Format(SR.DataRelation_InValidNamespaceInNestedRelation, childTableName)); // // Rows // public static Exception RowNotInTheDataSet() => _Argument(SR.DataRow_NotInTheDataSet); public static Exception RowNotInTheTable() => _RowNotInTable(SR.DataRow_NotInTheTable); public static Exception EditInRowChanging() => _InRowChangingEvent(SR.DataRow_EditInRowChanging); public static Exception EndEditInRowChanging() => _InRowChangingEvent(SR.DataRow_EndEditInRowChanging); public static Exception BeginEditInRowChanging() => _InRowChangingEvent(SR.DataRow_BeginEditInRowChanging); public static Exception CancelEditInRowChanging() => _InRowChangingEvent(SR.DataRow_CancelEditInRowChanging); public static Exception DeleteInRowDeleting() => _InRowChangingEvent(SR.DataRow_DeleteInRowDeleting); public static Exception ValueArrayLength() => _Argument(SR.DataRow_ValuesArrayLength); public static Exception NoCurrentData() => _VersionNotFound(SR.DataRow_NoCurrentData); public static Exception NoOriginalData() => _VersionNotFound(SR.DataRow_NoOriginalData); public static Exception NoProposedData() => _VersionNotFound(SR.DataRow_NoProposedData); public static Exception RowRemovedFromTheTable() => _RowNotInTable(SR.DataRow_RemovedFromTheTable); public static Exception DeletedRowInaccessible() => _DeletedRowInaccessible(SR.DataRow_DeletedRowInaccessible); public static Exception RowAlreadyDeleted() => _DeletedRowInaccessible(SR.DataRow_AlreadyDeleted); public static Exception RowEmpty() => _Argument(SR.DataRow_Empty); public static Exception InvalidRowVersion() => _Data(SR.DataRow_InvalidVersion); public static Exception RowOutOfRange() => _IndexOutOfRange(SR.DataRow_RowOutOfRange); public static Exception RowOutOfRange(int index) => _IndexOutOfRange(SR.Format(SR.DataRow_OutOfRange, (index).ToString(CultureInfo.InvariantCulture))); public static Exception RowInsertOutOfRange(int index) => _IndexOutOfRange(SR.Format(SR.DataRow_RowInsertOutOfRange, (index).ToString(CultureInfo.InvariantCulture))); public static Exception RowInsertTwice(int index, string tableName) => _IndexOutOfRange(SR.Format(SR.DataRow_RowInsertTwice, (index).ToString(CultureInfo.InvariantCulture), tableName)); public static Exception RowInsertMissing(string tableName) => _IndexOutOfRange(SR.Format(SR.DataRow_RowInsertMissing, tableName)); public static Exception RowAlreadyRemoved() => _Data(SR.DataRow_AlreadyRemoved); public static Exception MultipleParents() => _Data(SR.DataRow_MultipleParents); public static Exception InvalidRowState(DataRowState state) => _InvalidEnumArgumentException<DataRowState>(state); public static Exception InvalidRowBitPattern() => _Argument(SR.DataRow_InvalidRowBitPattern); // // DataSet // internal static Exception SetDataSetNameToEmpty() => _Argument(SR.DataSet_SetNameToEmpty); internal static Exception SetDataSetNameConflicting(string name) => _Argument(SR.Format(SR.DataSet_SetDataSetNameConflicting, name)); public static Exception DataSetUnsupportedSchema(string ns) => _Argument(SR.Format(SR.DataSet_UnsupportedSchema, ns)); public static Exception MergeMissingDefinition(string obj) => _Argument(SR.Format(SR.DataMerge_MissingDefinition, obj)); public static Exception TablesInDifferentSets() => _Argument(SR.DataRelation_TablesInDifferentSets); public static Exception RelationAlreadyExists() => _Argument(SR.DataRelation_AlreadyExists); public static Exception RowAlreadyInOtherCollection() => _Argument(SR.DataRow_AlreadyInOtherCollection); public static Exception RowAlreadyInTheCollection() => _Argument(SR.DataRow_AlreadyInTheCollection); public static Exception TableMissingPrimaryKey() => _MissingPrimaryKey(SR.DataTable_MissingPrimaryKey); public static Exception RecordStateRange() => _Argument(SR.DataIndex_RecordStateRange); public static Exception IndexKeyLength(int length, int keyLength) => length == 0 ? _Argument(SR.DataIndex_FindWithoutSortOrder) : _Argument(SR.Format(SR.DataIndex_KeyLength, (length).ToString(CultureInfo.InvariantCulture), (keyLength).ToString(CultureInfo.InvariantCulture))); public static Exception RemovePrimaryKey(DataTable table) => table.TableName.Length == 0 ? _Argument(SR.DataKey_RemovePrimaryKey) : _Argument(SR.Format(SR.DataKey_RemovePrimaryKey1, table.TableName)); public static Exception RelationAlreadyInOtherDataSet() => _Argument(SR.DataRelation_AlreadyInOtherDataSet); public static Exception RelationAlreadyInTheDataSet() => _Argument(SR.DataRelation_AlreadyInTheDataSet); public static Exception RelationNotInTheDataSet(string relation) => _Argument(SR.Format(SR.DataRelation_NotInTheDataSet, relation)); public static Exception RelationOutOfRange(object index) => _IndexOutOfRange(SR.Format(SR.DataRelation_OutOfRange, Convert.ToString(index, null))); public static Exception DuplicateRelation(string relation) => _DuplicateName(SR.Format(SR.DataRelation_DuplicateName, relation)); public static Exception RelationTableNull() => _Argument(SR.DataRelation_TableNull); public static Exception RelationDataSetNull() => _Argument(SR.DataRelation_TableNull); public static Exception RelationTableWasRemoved() => _Argument(SR.DataRelation_TableWasRemoved); public static Exception ParentTableMismatch() => _Argument(SR.DataRelation_ParentTableMismatch); public static Exception ChildTableMismatch() => _Argument(SR.DataRelation_ChildTableMismatch); public static Exception EnforceConstraint() => _Constraint(SR.Data_EnforceConstraints); public static Exception CaseLocaleMismatch() => _Argument(SR.DataRelation_CaseLocaleMismatch); public static Exception CannotChangeCaseLocale() => CannotChangeCaseLocale(null); public static Exception CannotChangeCaseLocale(Exception innerException) => _Argument(SR.DataSet_CannotChangeCaseLocale, innerException); public static Exception CannotChangeSchemaSerializationMode() => _InvalidOperation(SR.DataSet_CannotChangeSchemaSerializationMode); public static Exception InvalidSchemaSerializationMode(Type enumType, string mode) => _InvalidEnumArgumentException(SR.Format(SR.ADP_InvalidEnumerationValue, enumType.Name, mode)); public static Exception InvalidRemotingFormat(SerializationFormat mode) => _InvalidEnumArgumentException<SerializationFormat>(mode); // // DataTable and DataTableCollection // public static Exception TableForeignPrimaryKey() => _Argument(SR.DataTable_ForeignPrimaryKey); public static Exception TableCannotAddToSimpleContent() => _Argument(SR.DataTable_CannotAddToSimpleContent); public static Exception NoTableName() => _Argument(SR.DataTable_NoName); public static Exception MultipleTextOnlyColumns() => _Argument(SR.DataTable_MultipleSimpleContentColumns); public static Exception InvalidSortString(string sort) => _Argument(SR.Format(SR.DataTable_InvalidSortString, sort)); public static Exception DuplicateTableName(string table) => _DuplicateName(SR.Format(SR.DataTable_DuplicateName, table)); public static Exception DuplicateTableName2(string table, string ns) => _DuplicateName(SR.Format(SR.DataTable_DuplicateName2, table, ns)); public static Exception SelfnestedDatasetConflictingName(string table) => _DuplicateName(SR.Format(SR.DataTable_SelfnestedDatasetConflictingName, table)); public static Exception DatasetConflictingName(string table) => _DuplicateName(SR.Format(SR.DataTable_DatasetConflictingName, table)); public static Exception TableAlreadyInOtherDataSet() => _Argument(SR.DataTable_AlreadyInOtherDataSet); public static Exception TableAlreadyInTheDataSet() => _Argument(SR.DataTable_AlreadyInTheDataSet); public static Exception TableOutOfRange(int index) => _IndexOutOfRange(SR.Format(SR.DataTable_OutOfRange, (index).ToString(CultureInfo.InvariantCulture))); public static Exception TableNotInTheDataSet(string table) => _Argument(SR.Format(SR.DataTable_NotInTheDataSet, table)); public static Exception TableInRelation() => _Argument(SR.DataTable_InRelation); public static Exception TableInConstraint(DataTable table, Constraint constraint) => _Argument(SR.Format(SR.DataTable_InConstraint, table.TableName, constraint.ConstraintName)); public static Exception CanNotSerializeDataTableHierarchy() => _InvalidOperation(SR.DataTable_CanNotSerializeDataTableHierarchy); public static Exception CanNotRemoteDataTable() => _InvalidOperation(SR.DataTable_CanNotRemoteDataTable); public static Exception CanNotSetRemotingFormat() => _Argument(SR.DataTable_CanNotSetRemotingFormat); public static Exception CanNotSerializeDataTableWithEmptyName() => _InvalidOperation(SR.DataTable_CanNotSerializeDataTableWithEmptyName); public static Exception TableNotFound(string tableName) => _Argument(SR.Format(SR.DataTable_TableNotFound, tableName)); // // Storage // public static Exception AggregateException(AggregateType aggregateType, Type type) => _Data(SR.Format(SR.DataStorage_AggregateException, aggregateType.ToString(), type.Name)); public static Exception InvalidStorageType(TypeCode typecode) => _Data(SR.Format(SR.DataStorage_InvalidStorageType, typecode.ToString())); public static Exception RangeArgument(int min, int max) => _Argument(SR.Format(SR.Range_Argument, (min).ToString(CultureInfo.InvariantCulture), (max).ToString(CultureInfo.InvariantCulture))); public static Exception NullRange() => _Data(SR.Range_NullRange); public static Exception NegativeMinimumCapacity() => _Argument(SR.RecordManager_MinimumCapacity); public static Exception ProblematicChars(char charValue) => _Argument(SR.Format(SR.DataStorage_ProblematicChars, "0x" + ((ushort)charValue).ToString("X", CultureInfo.InvariantCulture))); public static Exception StorageSetFailed() => _Argument(SR.DataStorage_SetInvalidDataType); // // XML schema // public static Exception SimpleTypeNotSupported() => _Data(SR.Xml_SimpleTypeNotSupported); public static Exception MissingAttribute(string attribute) => MissingAttribute(string.Empty, attribute); public static Exception MissingAttribute(string element, string attribute) => _Data(SR.Format(SR.Xml_MissingAttribute, element, attribute)); public static Exception InvalidAttributeValue(string name, string value) => _Data(SR.Format(SR.Xml_ValueOutOfRange, name, value)); public static Exception AttributeValues(string name, string value1, string value2) => _Data(SR.Format(SR.Xml_AttributeValues, name, value1, value2)); public static Exception ElementTypeNotFound(string name) => _Data(SR.Format(SR.Xml_ElementTypeNotFound, name)); public static Exception RelationParentNameMissing(string rel) => _Data(SR.Format(SR.Xml_RelationParentNameMissing, rel)); public static Exception RelationChildNameMissing(string rel) => _Data(SR.Format(SR.Xml_RelationChildNameMissing, rel)); public static Exception RelationTableKeyMissing(string rel) => _Data(SR.Format(SR.Xml_RelationTableKeyMissing, rel)); public static Exception RelationChildKeyMissing(string rel) => _Data(SR.Format(SR.Xml_RelationChildKeyMissing, rel)); public static Exception UndefinedDatatype(string name) => _Data(SR.Format(SR.Xml_UndefinedDatatype, name)); public static Exception DatatypeNotDefined() => _Data(SR.Xml_DatatypeNotDefined); public static Exception MismatchKeyLength() => _Data(SR.Xml_MismatchKeyLength); public static Exception InvalidField(string name) => _Data(SR.Format(SR.Xml_InvalidField, name)); public static Exception InvalidSelector(string name) => _Data(SR.Format(SR.Xml_InvalidSelector, name)); public static Exception CircularComplexType(string name) => _Data(SR.Format(SR.Xml_CircularComplexType, name)); public static Exception CannotInstantiateAbstract(string name) => _Data(SR.Format(SR.Xml_CannotInstantiateAbstract, name)); public static Exception InvalidKey(string name) => _Data(SR.Format(SR.Xml_InvalidKey, name)); public static Exception DiffgramMissingTable(string name) => _Data(SR.Format(SR.Xml_MissingTable, name)); public static Exception DiffgramMissingSQL() => _Data(SR.Xml_MissingSQL); public static Exception DuplicateConstraintRead(string str) => _Data(SR.Format(SR.Xml_DuplicateConstraint, str)); public static Exception ColumnTypeConflict(string name) => _Data(SR.Format(SR.Xml_ColumnConflict, name)); public static Exception CannotConvert(string name, string type) => _Data(SR.Format(SR.Xml_CannotConvert, name, type)); public static Exception MissingRefer(string name) => _Data(SR.Format(SR.Xml_MissingRefer, Keywords.REFER, Keywords.XSD_KEYREF, name)); public static Exception InvalidPrefix(string name) => _Data(SR.Format(SR.Xml_InvalidPrefix_SpecialCharacters, name)); public static Exception CanNotDeserializeObjectType() => _InvalidOperation(SR.Xml_CanNotDeserializeObjectType); public static Exception IsDataSetAttributeMissingInSchema() => _Data(SR.Xml_IsDataSetAttributeMissingInSchema); public static Exception TooManyIsDataSetAttributesInSchema() => _Data(SR.Xml_TooManyIsDataSetAttributesInSchema); // XML save public static Exception NestedCircular(string name) => _Data(SR.Format(SR.Xml_NestedCircular, name)); public static Exception MultipleParentRows(string tableQName) => _Data(SR.Format(SR.Xml_MultipleParentRows, tableQName)); public static Exception PolymorphismNotSupported(string typeName) => _InvalidOperation(SR.Format(SR.Xml_PolymorphismNotSupported, typeName)); public static Exception DataTableInferenceNotSupported() => _InvalidOperation(SR.Xml_DataTableInferenceNotSupported); /// <summary>throw DataException for multitarget failure</summary> internal static void ThrowMultipleTargetConverter(Exception innerException) { string res = (null != innerException) ? SR.Xml_MultipleTargetConverterError : SR.Xml_MultipleTargetConverterEmpty; ThrowDataException(res, innerException); } // Merge public static Exception DuplicateDeclaration(string name) => _Data(SR.Format(SR.Xml_MergeDuplicateDeclaration, name)); //Read Xml data public static Exception FoundEntity() => _Data(SR.Xml_FoundEntity); public static Exception MergeFailed(string name) => _Data(name); // SqlConvert public static Exception ConvertFailed(Type type1, Type type2) => _Data(SR.Format(SR.SqlConvert_ConvertFailed, type1.FullName, type2.FullName)); // DataTableReader public static Exception InvalidDataTableReader(string tableName) => _InvalidOperation(SR.Format(SR.DataTableReader_InvalidDataTableReader, tableName)); public static Exception DataTableReaderSchemaIsInvalid(string tableName) => _InvalidOperation(SR.Format(SR.DataTableReader_SchemaInvalidDataTableReader, tableName)); public static Exception CannotCreateDataReaderOnEmptyDataSet() => _Argument(SR.DataTableReader_CannotCreateDataReaderOnEmptyDataSet); public static Exception DataTableReaderArgumentIsEmpty() => _Argument(SR.DataTableReader_DataTableReaderArgumentIsEmpty); public static Exception ArgumentContainsNullValue() => _Argument(SR.DataTableReader_ArgumentContainsNullValue); public static Exception InvalidCurrentRowInDataTableReader() => _DeletedRowInaccessible(SR.DataTableReader_InvalidRowInDataTableReader); public static Exception EmptyDataTableReader(string tableName) => _DeletedRowInaccessible(SR.Format(SR.DataTableReader_DataTableCleared, tableName)); internal static Exception InvalidDuplicateNamedSimpleTypeDelaration(string stName, string errorStr) => _Argument(SR.Format(SR.NamedSimpleType_InvalidDuplicateNamedSimpleTypeDelaration, stName, errorStr)); // RbTree internal static Exception InternalRBTreeError(RBTreeError internalError) => _InvalidOperation(SR.Format(SR.RbTree_InvalidState, (int)internalError)); public static Exception EnumeratorModified() => _InvalidOperation(SR.RbTree_EnumerationBroken); } }
/*! Copyright (C) 2003-2013 Kody Brown (kody@bricksoft.com). MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; namespace Bricksoft.PowerCode { /// <summary> /// Provides an easier way to get environment variables. /// </summary> internal class EnvironmentVariables { public string prefix { get { return _prefix + "_"; } set { if (value.IndexOfAny(new char[] { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', '{', '[', '}', '}', '|', '\\', ':', ';', '"', '\'', '<', '>', ',', '.', '?', '/' }) > -1) { throw new ArgumentException("only alphanumeric characters and underscores (_) are allowed for environment variable names."); } _prefix = value != null && value.Trim().Length > 0 ? value.Trim() : ""; if (_prefix.EndsWith("_")) { _prefix = _prefix.Substring(0, _prefix.Length - 1); } } } private string _prefix = ""; public string postfix { get { return _postfix + "_"; } set { if (value.IndexOfAny(new char[] { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', '{', '[', '}', '}', '|', '\\', ':', ';', '"', '\'', '<', '>', ',', '.', '?', '/' }) > -1) { throw new ArgumentException("only alphanumeric characters and underscores (_) are allowed for environment variable names."); } _postfix = value != null && value.Trim().Length > 0 ? value.Trim() : ""; if (_postfix.EndsWith("_")) { _postfix = _postfix.Substring(0, _postfix.Length - 1); } } } private string _postfix = ""; public EnvironmentVariableTarget target { get { return _target; } set { _target = value; } } private EnvironmentVariableTarget _target; public EnvironmentVariables() { this.prefix = "_"; this.postfix = ""; this.target = EnvironmentVariableTarget.Process; } public EnvironmentVariables( string prefix, string postfix = "", EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { this.prefix = prefix; this.postfix = postfix; this.target = target; } /// <summary> /// Returns a dictionary of all environment variables that begin with the current instance's prefix (and ends with this instance's postfix, if specified). /// </summary> /// <returns></returns> /// <remarks> /// If prefix (and postfix) is empty, ALL environment variables are returned. /// </remarks> public Dictionary<string, string> all( EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { Dictionary<string, string> l = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> p in Environment.GetEnvironmentVariables(target)) { if ((prefix.Length == 0 && postfix.Length == 0) || (p.Key.StartsWith(prefix, StringComparison.CurrentCultureIgnoreCase) && p.Key.EndsWith(postfix, StringComparison.CurrentCultureIgnoreCase))) { l.Add(p.Key, p.Value); } } return l; } /// <summary> /// Returns a list of all environment variable names that begin with prefix (and end with postfix, if specified). /// </summary> /// <returns></returns> /// <remarks> /// If prefix (and postfix) is empty, ALL environment variable names are returned. /// </remarks> public List<string> keys( EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { List<string> l = new List<string>(); foreach (KeyValuePair<string, string> p in Environment.GetEnvironmentVariables(target)) { //if (prefix.Length == 0 || p.Key.StartsWith(prefix, StringComparison.CurrentCultureIgnoreCase)) { if ((prefix.Length == 0 && postfix.Length == 0) || (p.Key.StartsWith(prefix, StringComparison.CurrentCultureIgnoreCase) && p.Key.EndsWith(postfix, StringComparison.CurrentCultureIgnoreCase))) { l.Add(p.Key); } } return l; } /// <summary> /// Returns whether the specified environment variable exists. /// The key is automatically prefixed by this instance's prefix property. /// The target (scope) is specified by <paramref name="target"/>. /// </summary> /// <param name="key"></param> /// <param name="target"></param> /// <returns></returns> public bool contains( string key, EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { if (Environment.GetEnvironmentVariable(prefix + key + postfix, target) != null) { return true; } return false; } /// <summary> /// Returns the index of the first environment variable that exists. /// The target (scope) is the current process. /// </summary> /// <param name="key"></param> /// <returns></returns> public int indexOfAny( params string[] keys ) { return indexOfAny(EnvironmentVariableTarget.Process, keys); } /// <summary> /// Returns the index of the first environment variable that exists. /// The target (scope) is specified by <paramref name="target"/>. /// </summary> /// <param name="target"></param> /// <param name="key"></param> /// <returns></returns> public int indexOfAny( EnvironmentVariableTarget target, params string[] keys ) { for (int i = 0; i < keys.Length; i++) { if (Environment.GetEnvironmentVariable(prefix + keys[i] + postfix, target) != null) { return i; } } return -1; } /// <summary> /// Gets the value of <paramref name="key"/> from the environment variables. /// Returns it as type T. /// The target (scope) is specified by <paramref name="target"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <param name="separator"></param> /// <param name="target"></param> /// <returns></returns> public T attr<T>( string key, T defaultValue = default(T), string separator = "||", EnvironmentVariableTarget target = EnvironmentVariableTarget.Process ) { if (key == null || key.Length == 0) { throw new InvalidOperationException("key is required"); } if (contains(key)) { string keydata = Environment.GetEnvironmentVariable(prefix + key + postfix, target); if (typeof(T) == typeof(bool) || typeof(T).IsSubclassOf(typeof(bool))) { if ((object)keydata != null) { return (T)(object)(keydata.StartsWith("t", StringComparison.CurrentCultureIgnoreCase)); } } else if (typeof(T) == typeof(DateTime) || typeof(T).IsSubclassOf(typeof(DateTime))) { DateTime dt; if ((object)keydata != null && DateTime.TryParse(keydata, out dt)) { return (T)(object)dt; } } else if (typeof(T) == typeof(short) || typeof(T).IsSubclassOf(typeof(short))) { short i; if ((object)keydata != null && short.TryParse(keydata, out i)) { return (T)(object)i; } } else if (typeof(T) == typeof(int) || typeof(T).IsSubclassOf(typeof(int))) { int i; if ((object)keydata != null && int.TryParse(keydata, out i)) { return (T)(object)i; } } else if (typeof(T) == typeof(long) || typeof(T).IsSubclassOf(typeof(long))) { long i; if ((object)keydata != null && long.TryParse(keydata, out i)) { return (T)(object)i; } } else if (typeof(T) == typeof(ulong) || typeof(T).IsSubclassOf(typeof(ulong))) { ulong i; if ((object)keydata != null && ulong.TryParse(keydata, out i)) { return (T)(object)i; } } else if (typeof(T) == typeof(string) || typeof(T).IsSubclassOf(typeof(string))) { // string if ((object)keydata != null) { return (T)(object)(keydata).ToString(); } } else if (typeof(T) == typeof(string[]) || typeof(T).IsSubclassOf(typeof(string[]))) { // string[] if ((object)keydata != null) { // string array data SHOULD always be saved to the environment as a string||string||string.. return (T)(object)keydata.Split(new string[] { separator }, StringSplitOptions.None); } } else if (typeof(T) == typeof(List<string>) || typeof(T).IsSubclassOf(typeof(List<string>))) { // List<string> if ((object)keydata != null) { // string array data SHOULD always be saved to the environment as a string||string||string.. return (T)(object)new List<string>(keydata.Split(new string[] { separator }, StringSplitOptions.None)); } } else { throw new InvalidOperationException("unknown or unsupported data type was requested"); } } return defaultValue; } } }
/* * 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.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Reflection; using System.Threading; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps=OpenSim.Framework.Capabilities.Caps; using OSDArray=OpenMetaverse.StructuredData.OSDArray; using OSDMap=OpenMetaverse.StructuredData.OSDMap; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.World.WorldMap { public class WorldMapModule : INonSharedRegionModule, IWorldMapModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string DEFAULT_WORLD_MAP_EXPORT_PATH = "exportmap.jpg"; private static readonly UUID STOP_UUID = UUID.Random(); private static readonly string m_mapLayerPath = "0001/"; private OpenSim.Framework.BlockingQueue<MapRequestState> requests = new OpenSim.Framework.BlockingQueue<MapRequestState>(); //private IConfig m_config; protected Scene m_scene; private List<MapBlockData> cachedMapBlocks = new List<MapBlockData>(); private int cachedTime = 0; private byte[] myMapImageJPEG; protected volatile bool m_Enabled = false; private Dictionary<UUID, MapRequestState> m_openRequests = new Dictionary<UUID, MapRequestState>(); private Dictionary<string, int> m_blacklistedurls = new Dictionary<string, int>(); private Dictionary<ulong, int> m_blacklistedregions = new Dictionary<ulong, int>(); private Dictionary<ulong, string> m_cachedRegionMapItemsAddress = new Dictionary<ulong, string>(); private List<UUID> m_rootAgents = new List<UUID>(); private volatile bool threadrunning = false; //private int CacheRegionsDistance = 256; #region INonSharedRegionModule Members public virtual void Initialise (IConfigSource config) { IConfig startupConfig = config.Configs["Startup"]; if (startupConfig.GetString("WorldMapModule", "WorldMap") == "WorldMap") m_Enabled = true; } public virtual void AddRegion (Scene scene) { if (!m_Enabled) return; lock (scene) { m_scene = scene; m_scene.RegisterModuleInterface<IWorldMapModule>(this); m_scene.AddCommand( this, "export-map", "export-map [<path>]", "Save an image of the world map", HandleExportWorldMapConsoleCommand); AddHandlers(); } } public virtual void RemoveRegion (Scene scene) { if (!m_Enabled) return; lock (m_scene) { m_Enabled = false; RemoveHandlers(); m_scene = null; } } public virtual void RegionLoaded (Scene scene) { } public virtual void Close() { } public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "WorldMapModule"; } } #endregion // this has to be called with a lock on m_scene protected virtual void AddHandlers() { myMapImageJPEG = new byte[0]; string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString(); regionimage = regionimage.Replace("-", ""); m_log.Info("[WORLD MAP]: JPEG Map location: http://" + m_scene.RegionInfo.ExternalEndPoint.Address.ToString() + ":" + m_scene.RegionInfo.HttpPort.ToString() + "/index.php?method=" + regionimage); MainServer.Instance.AddHTTPHandler(regionimage, OnHTTPGetMapImage); MainServer.Instance.AddLLSDHandler( "/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest); m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.EventManager.OnNewClient += OnNewClient; m_scene.EventManager.OnClientClosed += ClientLoggedOut; m_scene.EventManager.OnMakeChildAgent += MakeChildAgent; m_scene.EventManager.OnMakeRootAgent += MakeRootAgent; } // this has to be called with a lock on m_scene protected virtual void RemoveHandlers() { m_scene.EventManager.OnMakeRootAgent -= MakeRootAgent; m_scene.EventManager.OnMakeChildAgent -= MakeChildAgent; m_scene.EventManager.OnClientClosed -= ClientLoggedOut; m_scene.EventManager.OnNewClient -= OnNewClient; m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps; string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString(); regionimage = regionimage.Replace("-", ""); MainServer.Instance.RemoveLLSDHandler("/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest); MainServer.Instance.RemoveHTTPHandler("", regionimage); } public void OnRegisterCaps(UUID agentID, Caps caps) { //m_log.DebugFormat("[WORLD MAP]: OnRegisterCaps: agentID {0} caps {1}", agentID, caps); string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("MapLayer", new RestStreamHandler("POST", capsBase + m_mapLayerPath, delegate(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return MapLayerRequest(request, path, param, agentID, caps); })); } /// <summary> /// Callback for a map layer request /// </summary> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> public string MapLayerRequest(string request, string path, string param, UUID agentID, Caps caps) { //try //{ //m_log.DebugFormat("[MAPLAYER]: request: {0}, path: {1}, param: {2}, agent:{3}", //request, path, param,agentID.ToString()); // this is here because CAPS map requests work even beyond the 10,000 limit. ScenePresence avatarPresence = null; m_scene.TryGetScenePresence(agentID, out avatarPresence); if (avatarPresence != null) { bool lookup = false; lock (cachedMapBlocks) { if (cachedMapBlocks.Count > 0 && ((cachedTime + 1800) > Util.UnixTimeSinceEpoch())) { List<MapBlockData> mapBlocks; mapBlocks = cachedMapBlocks; avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0); } else { lookup = true; } } if (lookup) { List<MapBlockData> mapBlocks = new List<MapBlockData>(); ; List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID, (int)(m_scene.RegionInfo.RegionLocX - 8) * (int)Constants.RegionSize, (int)(m_scene.RegionInfo.RegionLocX + 8) * (int)Constants.RegionSize, (int)(m_scene.RegionInfo.RegionLocY - 8) * (int)Constants.RegionSize, (int)(m_scene.RegionInfo.RegionLocY + 8) * (int)Constants.RegionSize); foreach (GridRegion r in regions) { MapBlockData block = new MapBlockData(); MapBlockFromGridRegion(block, r); mapBlocks.Add(block); } avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0); lock (cachedMapBlocks) cachedMapBlocks = mapBlocks; cachedTime = Util.UnixTimeSinceEpoch(); } } LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse()); return mapResponse.ToString(); } /// <summary> /// /// </summary> /// <param name="mapReq"></param> /// <returns></returns> public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq) { m_log.Debug("[WORLD MAP]: MapLayer Request in region: " + m_scene.RegionInfo.RegionName); LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse()); return mapResponse; } /// <summary> /// /// </summary> /// <returns></returns> protected static OSDMapLayer GetOSDMapLayerResponse() { OSDMapLayer mapLayer = new OSDMapLayer(); mapLayer.Right = 5000; mapLayer.Top = 5000; mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006"); return mapLayer; } #region EventHandlers /// <summary> /// Registered for event /// </summary> /// <param name="client"></param> private void OnNewClient(IClientAPI client) { client.OnRequestMapBlocks += RequestMapBlocks; client.OnMapItemRequest += HandleMapItemRequest; } /// <summary> /// Client logged out, check to see if there are any more root agents in the simulator /// If not, stop the mapItemRequest Thread /// Event handler /// </summary> /// <param name="AgentId">AgentID that logged out</param> private void ClientLoggedOut(UUID AgentId, Scene scene) { lock (m_rootAgents) { m_rootAgents.Remove(AgentId); if (m_rootAgents.Count == 0) StopThread(); } } #endregion /// <summary> /// Starts the MapItemRequest Thread /// Note that this only gets started when there are actually agents in the region /// Additionally, it gets stopped when there are none. /// </summary> /// <param name="o"></param> private void StartThread(object o) { if (threadrunning) return; threadrunning = true; // m_log.Debug("[WORLD MAP]: Starting remote MapItem request thread"); Watchdog.StartThread(process, "MapItemRequestThread", ThreadPriority.BelowNormal, true); } /// <summary> /// Enqueues a 'stop thread' MapRequestState. Causes the MapItemRequest thread to end /// </summary> private void StopThread() { MapRequestState st = new MapRequestState(); st.agentID=STOP_UUID; st.EstateID=0; st.flags=0; st.godlike=false; st.itemtype=0; st.regionhandle=0; requests.Enqueue(st); } public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { lock (m_rootAgents) { if (!m_rootAgents.Contains(remoteClient.AgentId)) return; } uint xstart = 0; uint ystart = 0; Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out xstart, out ystart); if (itemtype == 6) // we only sevice 6 right now (avatar green dots) { if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle) { // Local Map Item Request int tc = Environment.TickCount; List<mapItemReply> mapitems = new List<mapItemReply>(); mapItemReply mapitem = new mapItemReply(); if (m_scene.GetRootAgentCount() <= 1) { mapitem = new mapItemReply(); mapitem.x = (uint)(xstart + 1); mapitem.y = (uint)(ystart + 1); mapitem.id = UUID.Zero; mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()); mapitem.Extra = 0; mapitem.Extra2 = 0; mapitems.Add(mapitem); } else { m_scene.ForEachScenePresence(delegate(ScenePresence sp) { // Don't send a green dot for yourself if (!sp.IsChildAgent && sp.UUID != remoteClient.AgentId) { mapitem = new mapItemReply(); mapitem.x = (uint)(xstart + sp.AbsolutePosition.X); mapitem.y = (uint)(ystart + sp.AbsolutePosition.Y); mapitem.id = UUID.Zero; mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()); mapitem.Extra = 1; mapitem.Extra2 = 0; mapitems.Add(mapitem); } }); } remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); } else { // Remote Map Item Request // ensures that the blockingqueue doesn't get borked if the GetAgents() timing changes. // Note that we only start up a remote mapItem Request thread if there's users who could // be making requests if (!threadrunning) { m_log.Warn("[WORLD MAP]: Starting new remote request thread manually. This means that AvatarEnteringParcel never fired! This needs to be fixed! Don't Mantis this, as the developers can see it in this message"); StartThread(new object()); } RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle); } } } /// <summary> /// Processing thread main() loop for doing remote mapitem requests /// </summary> public void process() { try { while (true) { MapRequestState st = requests.Dequeue(1000); // end gracefully if (st.agentID == STOP_UUID) break; if (st.agentID != UUID.Zero) { bool dorequest = true; lock (m_rootAgents) { if (!m_rootAgents.Contains(st.agentID)) dorequest = false; } if (dorequest) { OSDMap response = RequestMapItemsAsync("", st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle); RequestMapItemsCompleted(response); } } Watchdog.UpdateThread(); } } catch (Exception e) { m_log.ErrorFormat("[WORLD MAP]: Map item request thread terminated abnormally with exception {0}", e); } threadrunning = false; Watchdog.RemoveThread(); } /// <summary> /// Enqueues the map item request into the processing thread /// </summary> /// <param name="state"></param> public void EnqueueMapItemRequest(MapRequestState state) { requests.Enqueue(state); } /// <summary> /// Sends the mapitem response to the IClientAPI /// </summary> /// <param name="response">The OSDMap Response for the mapitem</param> private void RequestMapItemsCompleted(OSDMap response) { UUID requestID = response["requestID"].AsUUID(); if (requestID != UUID.Zero) { MapRequestState mrs = new MapRequestState(); mrs.agentID = UUID.Zero; lock (m_openRequests) { if (m_openRequests.ContainsKey(requestID)) { mrs = m_openRequests[requestID]; m_openRequests.Remove(requestID); } } if (mrs.agentID != UUID.Zero) { ScenePresence av = null; m_scene.TryGetScenePresence(mrs.agentID, out av); if (av != null) { if (response.ContainsKey(mrs.itemtype.ToString())) { List<mapItemReply> returnitems = new List<mapItemReply>(); OSDArray itemarray = (OSDArray)response[mrs.itemtype.ToString()]; for (int i = 0; i < itemarray.Count; i++) { OSDMap mapitem = (OSDMap)itemarray[i]; mapItemReply mi = new mapItemReply(); mi.x = (uint)mapitem["X"].AsInteger(); mi.y = (uint)mapitem["Y"].AsInteger(); mi.id = mapitem["ID"].AsUUID(); mi.Extra = mapitem["Extra"].AsInteger(); mi.Extra2 = mapitem["Extra2"].AsInteger(); mi.name = mapitem["Name"].AsString(); returnitems.Add(mi); } av.ControllingClient.SendMapItemReply(returnitems.ToArray(), mrs.itemtype, mrs.flags); } } } } } /// <summary> /// Enqueue the MapItem request for remote processing /// </summary> /// <param name="httpserver">blank string, we discover this in the process</param> /// <param name="id">Agent ID that we are making this request on behalf</param> /// <param name="flags">passed in from packet</param> /// <param name="EstateID">passed in from packet</param> /// <param name="godlike">passed in from packet</param> /// <param name="itemtype">passed in from packet</param> /// <param name="regionhandle">Region we're looking up</param> public void RequestMapItems(string httpserver, UUID id, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { MapRequestState st = new MapRequestState(); st.agentID = id; st.flags = flags; st.EstateID = EstateID; st.godlike = godlike; st.itemtype = itemtype; st.regionhandle = regionhandle; EnqueueMapItemRequest(st); } /// <summary> /// Does the actual remote mapitem request /// This should be called from an asynchronous thread /// Request failures get blacklisted until region restart so we don't /// continue to spend resources trying to contact regions that are down. /// </summary> /// <param name="httpserver">blank string, we discover this in the process</param> /// <param name="id">Agent ID that we are making this request on behalf</param> /// <param name="flags">passed in from packet</param> /// <param name="EstateID">passed in from packet</param> /// <param name="godlike">passed in from packet</param> /// <param name="itemtype">passed in from packet</param> /// <param name="regionhandle">Region we're looking up</param> /// <returns></returns> private OSDMap RequestMapItemsAsync(string httpserver, UUID id, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { bool blacklisted = false; lock (m_blacklistedregions) { if (m_blacklistedregions.ContainsKey(regionhandle)) blacklisted = true; } if (blacklisted) return new OSDMap(); UUID requestID = UUID.Random(); lock (m_cachedRegionMapItemsAddress) { if (m_cachedRegionMapItemsAddress.ContainsKey(regionhandle)) httpserver = m_cachedRegionMapItemsAddress[regionhandle]; } if (httpserver.Length == 0) { uint x = 0, y = 0; Utils.LongToUInts(regionhandle, out x, out y); GridRegion mreg = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y); if (mreg != null) { httpserver = "http://" + mreg.ExternalEndPoint.Address.ToString() + ":" + mreg.HttpPort + "/MAP/MapItems/" + regionhandle.ToString(); lock (m_cachedRegionMapItemsAddress) { if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle)) m_cachedRegionMapItemsAddress.Add(regionhandle, httpserver); } } else { lock (m_blacklistedregions) { if (!m_blacklistedregions.ContainsKey(regionhandle)) m_blacklistedregions.Add(regionhandle, Environment.TickCount); } m_log.InfoFormat("[WORLD MAP]: Blacklisted region {0}", regionhandle.ToString()); } } blacklisted = false; lock (m_blacklistedurls) { if (m_blacklistedurls.ContainsKey(httpserver)) blacklisted = true; } // Can't find the http server if (httpserver.Length == 0 || blacklisted) return new OSDMap(); MapRequestState mrs = new MapRequestState(); mrs.agentID = id; mrs.EstateID = EstateID; mrs.flags = flags; mrs.godlike = godlike; mrs.itemtype=itemtype; mrs.regionhandle = regionhandle; lock (m_openRequests) m_openRequests.Add(requestID, mrs); WebRequest mapitemsrequest = WebRequest.Create(httpserver); mapitemsrequest.Method = "POST"; mapitemsrequest.ContentType = "application/xml+llsd"; OSDMap RAMap = new OSDMap(); // string RAMapString = RAMap.ToString(); OSD LLSDofRAMap = RAMap; // RENAME if this works byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap); OSDMap responseMap = new OSDMap(); responseMap["requestID"] = OSD.FromUUID(requestID); Stream os = null; try { // send the Post mapitemsrequest.ContentLength = buffer.Length; //Count bytes to send os = mapitemsrequest.GetRequestStream(); os.Write(buffer, 0, buffer.Length); //Send it os.Close(); //m_log.DebugFormat("[WORLD MAP]: Getting MapItems from Sim {0}", httpserver); } catch (WebException ex) { m_log.WarnFormat("[WORLD MAP]: Bad send on GetMapItems {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); lock (m_blacklistedurls) { if (!m_blacklistedurls.ContainsKey(httpserver)) m_blacklistedurls.Add(httpserver, Environment.TickCount); } m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver); return responseMap; } string response_mapItems_reply = null; { // get the response try { WebResponse webResponse = mapitemsrequest.GetResponse(); if (webResponse != null) { StreamReader sr = new StreamReader(webResponse.GetResponseStream()); response_mapItems_reply = sr.ReadToEnd().Trim(); } else { return new OSDMap(); } } catch (WebException) { responseMap["connect"] = OSD.FromBoolean(false); lock (m_blacklistedurls) { if (!m_blacklistedurls.ContainsKey(httpserver)) m_blacklistedurls.Add(httpserver, Environment.TickCount); } m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver); return responseMap; } OSD rezResponse = null; try { rezResponse = OSDParser.DeserializeLLSDXml(response_mapItems_reply); responseMap = (OSDMap)rezResponse; responseMap["requestID"] = OSD.FromUUID(requestID); } catch (Exception) { //m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } } return responseMap; } /// <summary> /// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates /// </summary> /// <param name="minX"></param> /// <param name="minY"></param> /// <param name="maxX"></param> /// <param name="maxY"></param> public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag) { if ((flag & 0x10000) != 0) // user clicked on the map a tile that isn't visible { List<MapBlockData> response = new List<MapBlockData>(); // this should return one mapblock at most. // (diva note: why?? in that case we should GetRegionByPosition) // But make sure: Look whether the one we requested is in there List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID, minX * (int)Constants.RegionSize, maxX * (int)Constants.RegionSize, minY * (int)Constants.RegionSize, maxY * (int)Constants.RegionSize); if (regions != null) { foreach (GridRegion r in regions) { if ((r.RegionLocX == minX * (int)Constants.RegionSize) && (r.RegionLocY == minY * (int)Constants.RegionSize)) { // found it => add it to response MapBlockData block = new MapBlockData(); MapBlockFromGridRegion(block, r); response.Add(block); break; } } } if (response.Count == 0) { // response still empty => couldn't find the map-tile the user clicked on => tell the client MapBlockData block = new MapBlockData(); block.X = (ushort)minX; block.Y = (ushort)minY; block.Access = 254; // == not there response.Add(block); } remoteClient.SendMapBlock(response, 0); } else { // normal mapblock request. Use the provided values GetAndSendBlocks(remoteClient, minX, minY, maxX, maxY, flag); } } protected virtual void GetAndSendBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag) { List<MapBlockData> mapBlocks = new List<MapBlockData>(); List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID, (minX - 4) * (int)Constants.RegionSize, (maxX + 4) * (int)Constants.RegionSize, (minY - 4) * (int)Constants.RegionSize, (maxY + 4) * (int)Constants.RegionSize); foreach (GridRegion r in regions) { MapBlockData block = new MapBlockData(); MapBlockFromGridRegion(block, r); mapBlocks.Add(block); } remoteClient.SendMapBlock(mapBlocks, flag); } protected void MapBlockFromGridRegion(MapBlockData block, GridRegion r) { block.Access = r.Access; block.MapImageId = r.TerrainImage; block.Name = r.RegionName; block.X = (ushort)(r.RegionLocX / Constants.RegionSize); block.Y = (ushort)(r.RegionLocY / Constants.RegionSize); } public Hashtable OnHTTPGetMapImage(Hashtable keysvals) { m_log.Debug("[WORLD MAP]: Sending map image jpeg"); Hashtable reply = new Hashtable(); int statuscode = 200; byte[] jpeg = new byte[0]; if (myMapImageJPEG.Length == 0) { MemoryStream imgstream = new MemoryStream(); Bitmap mapTexture = new Bitmap(1,1); ManagedImage managedImage; Image image = (Image)mapTexture; try { // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data imgstream = new MemoryStream(); // non-async because we know we have the asset immediately. AssetBase mapasset = m_scene.AssetService.Get(m_scene.RegionInfo.RegionSettings.TerrainImageID.ToString()); // Decode image to System.Drawing.Image if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image)) { // Save to bitmap mapTexture = new Bitmap(image); EncoderParameters myEncoderParameters = new EncoderParameters(); myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); // Save bitmap to stream mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters); // Write the stream to a byte array for output jpeg = imgstream.ToArray(); myMapImageJPEG = jpeg; } } catch (Exception) { // Dummy! m_log.Warn("[WORLD MAP]: Unable to generate Map image"); } finally { // Reclaim memory, these are unmanaged resources // If we encountered an exception, one or more of these will be null if (mapTexture != null) mapTexture.Dispose(); if (image != null) image.Dispose(); if (imgstream != null) { imgstream.Close(); imgstream.Dispose(); } } } else { // Use cached version so we don't have to loose our mind jpeg = myMapImageJPEG; } reply["str_response_string"] = Convert.ToBase64String(jpeg); reply["int_response_code"] = statuscode; reply["content_type"] = "image/jpeg"; return reply; } // From msdn private static ImageCodecInfo GetEncoderInfo(String mimeType) { ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } /// <summary> /// Export the world map /// </summary> /// <param name="fileName"></param> public void HandleExportWorldMapConsoleCommand(string module, string[] cmdparams) { if (m_scene.ConsoleScene() == null) { // FIXME: If console region is root then this will be printed by every module. Currently, there is no // way to prevent this, short of making the entire module shared (which is complete overkill). // One possibility is to return a bool to signal whether the module has completely handled the command m_log.InfoFormat("[WORLD MAP]: Please change to a specific region in order to export its world map"); return; } if (m_scene.ConsoleScene() != m_scene) return; string exportPath; if (cmdparams.Length > 1) exportPath = cmdparams[1]; else exportPath = DEFAULT_WORLD_MAP_EXPORT_PATH; m_log.InfoFormat( "[WORLD MAP]: Exporting world map for {0} to {1}", m_scene.RegionInfo.RegionName, exportPath); List<MapBlockData> mapBlocks = new List<MapBlockData>(); List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID, (int)(m_scene.RegionInfo.RegionLocX - 9) * (int)Constants.RegionSize, (int)(m_scene.RegionInfo.RegionLocX + 9) * (int)Constants.RegionSize, (int)(m_scene.RegionInfo.RegionLocY - 9) * (int)Constants.RegionSize, (int)(m_scene.RegionInfo.RegionLocY + 9) * (int)Constants.RegionSize); List<AssetBase> textures = new List<AssetBase>(); List<Image> bitImages = new List<Image>(); foreach (GridRegion r in regions) { MapBlockData mapBlock = new MapBlockData(); MapBlockFromGridRegion(mapBlock, r); AssetBase texAsset = m_scene.AssetService.Get(mapBlock.MapImageId.ToString()); if (texAsset != null) { textures.Add(texAsset); } //else //{ // // WHAT?!? This doesn't seem right. Commenting (diva) // texAsset = m_scene.AssetService.Get(mapBlock.MapImageId.ToString()); // if (texAsset != null) // { // textures.Add(texAsset); // } //} } foreach (AssetBase asset in textures) { ManagedImage managedImage; Image image; if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image)) bitImages.Add(image); } Bitmap mapTexture = new Bitmap(2560, 2560); Graphics g = Graphics.FromImage(mapTexture); SolidBrush sea = new SolidBrush(Color.DarkBlue); g.FillRectangle(sea, 0, 0, 2560, 2560); for (int i = 0; i < mapBlocks.Count; i++) { ushort x = (ushort)((mapBlocks[i].X - m_scene.RegionInfo.RegionLocX) + 10); ushort y = (ushort)((mapBlocks[i].Y - m_scene.RegionInfo.RegionLocY) + 10); g.DrawImage(bitImages[i], (x * 128), 2560 - (y * 128), 128, 128); // y origin is top } mapTexture.Save(exportPath, ImageFormat.Jpeg); m_log.InfoFormat( "[WORLD MAP]: Successfully exported world map for {0} to {1}", m_scene.RegionInfo.RegionName, exportPath); } public OSD HandleRemoteMapItemRequest(string path, OSD request, string endpoint) { uint xstart = 0; uint ystart = 0; Utils.LongToUInts(m_scene.RegionInfo.RegionHandle,out xstart,out ystart); OSDMap responsemap = new OSDMap(); int tc = Environment.TickCount; if (m_scene.GetRootAgentCount() == 0) { OSDMap responsemapdata = new OSDMap(); responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1)); responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1)); responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); responsemapdata["Extra"] = OSD.FromInteger(0); responsemapdata["Extra2"] = OSD.FromInteger(0); OSDArray responsearr = new OSDArray(); responsearr.Add(responsemapdata); responsemap["6"] = responsearr; } else { OSDArray responsearr = new OSDArray(m_scene.GetRootAgentCount()); m_scene.ForEachScenePresence(delegate(ScenePresence sp) { OSDMap responsemapdata = new OSDMap(); responsemapdata["X"] = OSD.FromInteger((int)(xstart + sp.AbsolutePosition.X)); responsemapdata["Y"] = OSD.FromInteger((int)(ystart + sp.AbsolutePosition.Y)); responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); responsemapdata["Extra"] = OSD.FromInteger(1); responsemapdata["Extra2"] = OSD.FromInteger(0); responsearr.Add(responsemapdata); }); responsemap["6"] = responsearr; } return responsemap; } public void GenerateMaptile() { // Cannot create a map for a nonexistant heightmap if (m_scene.Voxels == null) return; //create a texture asset of the terrain IMapImageGenerator terrain = m_scene.RequestModuleInterface<IMapImageGenerator>(); if (terrain == null) return; byte[] data = terrain.WriteJpeg2000Image(); if (data == null) return; UUID lastMapRegionUUID = m_scene.RegionInfo.RegionSettings.TerrainImageID; m_log.Debug("[WORLDMAP]: STORING MAPTILE IMAGE"); m_scene.RegionInfo.RegionSettings.TerrainImageID = UUID.Random(); AssetBase asset = new AssetBase( m_scene.RegionInfo.RegionSettings.TerrainImageID, "terrainImage_" + m_scene.RegionInfo.RegionID.ToString(), (sbyte)AssetType.Texture, m_scene.RegionInfo.RegionID.ToString()); asset.Data = data; asset.Description = m_scene.RegionInfo.RegionName; asset.Temporary = false; asset.Flags = AssetFlags.Maptile; // Store the new one m_log.DebugFormat("[WORLDMAP]: Storing map tile {0}", asset.ID); m_scene.AssetService.Store(asset); m_scene.RegionInfo.RegionSettings.Save(); // Delete the old one m_log.DebugFormat("[WORLDMAP]: Deleting old map tile {0}", lastMapRegionUUID); m_scene.AssetService.Delete(lastMapRegionUUID.ToString()); } private void MakeRootAgent(ScenePresence avatar) { // You may ask, why this is in a threadpool to start with.. // The reason is so we don't cause the thread to freeze waiting // for the 1 second it costs to start a thread manually. if (!threadrunning) Util.FireAndForget(this.StartThread); lock (m_rootAgents) { if (!m_rootAgents.Contains(avatar.UUID)) { m_rootAgents.Add(avatar.UUID); } } } private void MakeChildAgent(ScenePresence avatar) { lock (m_rootAgents) { m_rootAgents.Remove(avatar.UUID); if (m_rootAgents.Count == 0) StopThread(); } } } public struct MapRequestState { public UUID agentID; public uint flags; public uint EstateID; public bool godlike; public uint itemtype; public ulong regionhandle; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using Xunit; namespace System.Security.Cryptography.Encryption.Tests.Asymmetric { public static class CryptoStreamTests { [Fact] public static void Ctor() { var transform = new IdentityTransform(1, 1, true); Assert.Throws<ArgumentException>(() => new CryptoStream(new MemoryStream(), transform, (CryptoStreamMode)12345)); Assert.Throws<ArgumentException>(() => new CryptoStream(new MemoryStream(new byte[0], writable: false), transform, CryptoStreamMode.Write)); Assert.Throws<ArgumentException>(() => new CryptoStream(new CryptoStream(new MemoryStream(new byte[0]), transform, CryptoStreamMode.Write), transform, CryptoStreamMode.Read)); } [Theory] [InlineData(64, 64, true)] [InlineData(64, 128, true)] [InlineData(128, 64, true)] [InlineData(1, 1, true)] [InlineData(37, 24, true)] [InlineData(128, 3, true)] [InlineData(8192, 64, true)] [InlineData(64, 64, false)] public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks) { ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); var stream = new MemoryStream(); using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { Assert.True(encryptStream.CanWrite); Assert.False(encryptStream.CanRead); Assert.False(encryptStream.CanSeek); Assert.False(encryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => encryptStream.Length); Assert.Throws<NotSupportedException>(() => encryptStream.Position); Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); Assert.Throws<ArgumentException>(() => encryptStream.Write(new byte[3], 1, 4)); byte[] toWrite = Encoding.UTF8.GetBytes(LoremText); // Write it all at once encryptStream.Write(toWrite, 0, toWrite.Length); Assert.False(encryptStream.HasFlushedFinalBlock); // Write in chunks encryptStream.Write(toWrite, 0, toWrite.Length / 2); encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2)); Assert.False(encryptStream.HasFlushedFinalBlock); // Write one byte at a time for (int i = 0; i < toWrite.Length; i++) { encryptStream.WriteByte(toWrite[i]); } Assert.False(encryptStream.HasFlushedFinalBlock); // Write async encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult(); Assert.False(encryptStream.HasFlushedFinalBlock); // Flush (nops) encryptStream.Flush(); encryptStream.FlushAsync().GetAwaiter().GetResult(); encryptStream.FlushFinalBlock(); Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock()); Assert.True(encryptStream.HasFlushedFinalBlock); Assert.True(stream.Length > 0); } // Read/decrypt using Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { Assert.False(decryptStream.CanWrite); Assert.True(decryptStream.CanRead); Assert.False(decryptStream.CanSeek); Assert.False(decryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => decryptStream.Length); Assert.Throws<NotSupportedException>(() => decryptStream.Position); Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); Assert.Throws<ArgumentException>(() => decryptStream.Read(new byte[3], 1, 4)); using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEnd()); } } // Read/decrypt using ReadToEnd stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt using a small buffer to force multiple calls to Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt one byte at a time with ReadByte stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { string expectedStr = LoremText + LoremText + LoremText + LoremText; foreach (char c in expectedStr) { Assert.Equal(c, decryptStream.ReadByte()); // relies on LoremText being ASCII } Assert.Equal(-1, decryptStream.ReadByte()); } } [Fact] public static void NestedCryptoStreams() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (CryptoStream encryptStream1 = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) using (CryptoStream encryptStream2 = new CryptoStream(encryptStream1, encryptor, CryptoStreamMode.Write)) { encryptStream2.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); } } [Fact] public static void MultipleDispose() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.Dispose(); } } private const string LoremText = @"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem. In porttitor. Donec laoreet nonummy augue. Suspendisse dui purus, scelerisque at, vulputate vitae, pretium mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut nonummy."; private sealed class IdentityTransform : ICryptoTransform { private readonly int _inputBlockSize, _outputBlockSize; private readonly bool _canTransformMultipleBlocks; private long _writePos, _readPos; private MemoryStream _stream; internal IdentityTransform(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks) { _inputBlockSize = inputBlockSize; _outputBlockSize = outputBlockSize; _canTransformMultipleBlocks = canTransformMultipleBlocks; _stream = new MemoryStream(); } public bool CanReuseTransform { get { return true; } } public bool CanTransformMultipleBlocks { get { return _canTransformMultipleBlocks; } } public int InputBlockSize { get { return _inputBlockSize; } } public int OutputBlockSize { get { return _outputBlockSize; } } public void Dispose() { } public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { _stream.Position = _writePos; _stream.Write(inputBuffer, inputOffset, inputCount); _writePos = _stream.Position; _stream.Position = _readPos; int copied = _stream.Read(outputBuffer, outputOffset, outputBuffer.Length - outputOffset); _readPos = _stream.Position; return copied; } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { _stream.Position = _writePos; _stream.Write(inputBuffer, inputOffset, inputCount); _stream.Position = _readPos; long len = _stream.Length - _stream.Position; byte[] outputBuffer = new byte[len]; _stream.Read(outputBuffer, 0, outputBuffer.Length); _stream = new MemoryStream(); _writePos = 0; _readPos = 0; return outputBuffer; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Expressions.Cpp; using Microsoft.TemplateEngine.Core.Expressions.Cpp2; using Microsoft.TemplateEngine.Core.Operations; using Microsoft.TemplateEngine.Core.Util; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Config; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects { public class GlobalRunSpec : IGlobalRunSpec { private static IReadOnlyDictionary<string, IOperationConfig> _operationConfigLookup; private static void EnsureOperationConfigs(IComponentManager componentManager) { if (_operationConfigLookup == null) { List<IOperationConfig> operationConfigReaders = new List<IOperationConfig>(componentManager.OfType<IOperationConfig>()); Dictionary<string, IOperationConfig> operationConfigLookup = new Dictionary<string, IOperationConfig>(); foreach (IOperationConfig opConfig in operationConfigReaders) { operationConfigLookup[opConfig.Key] = opConfig; } _operationConfigLookup = operationConfigLookup; } } public IReadOnlyList<IPathMatcher> Include { get; private set; } public IReadOnlyList<IPathMatcher> Exclude { get; private set; } public IReadOnlyList<IPathMatcher> CopyOnly { get; private set; } public IReadOnlyDictionary<string, string> Rename { get; private set; } public IReadOnlyList<IOperationProvider> Operations { get; } public IVariableCollection RootVariableCollection { get; } public IReadOnlyList<KeyValuePair<IPathMatcher, IRunSpec>> Special { get; } public IReadOnlyDictionary<string, IReadOnlyList<IOperationProvider>> LocalizationOperations { get; } public IReadOnlyList<string> IgnoreFileNames { get; } public bool TryGetTargetRelPath(string sourceRelPath, out string targetRelPath) { return Rename.TryGetValue(sourceRelPath, out targetRelPath); } public GlobalRunSpec( IDirectory templateRoot, IComponentManager componentManager, IParameterSet parameters, IVariableCollection variables, IGlobalRunConfig globalConfig, IReadOnlyList<KeyValuePair<string, IGlobalRunConfig>> fileGlobConfigs, IReadOnlyDictionary<string, IReadOnlyList<IOperationProvider>> localizationOperations, IReadOnlyList<string> ignoreFileNames) { EnsureOperationConfigs(componentManager); RootVariableCollection = variables; LocalizationOperations = localizationOperations; IgnoreFileNames = ignoreFileNames; Operations = ResolveOperations(globalConfig, templateRoot, variables, parameters); List<KeyValuePair<IPathMatcher, IRunSpec>> specials = new List<KeyValuePair<IPathMatcher, IRunSpec>>(); if (fileGlobConfigs != null) { foreach (KeyValuePair<string, IGlobalRunConfig> specialEntry in fileGlobConfigs) { IReadOnlyList<IOperationProvider> specialOps = null; IVariableCollection specialVariables = variables; if (specialEntry.Value != null) { specialOps = ResolveOperations(specialEntry.Value, templateRoot, variables, parameters); specialVariables = VariableCollection.SetupVariables(templateRoot.MountPoint.EnvironmentSettings, parameters, specialEntry.Value.VariableSetup); } RunSpec spec = new RunSpec(specialOps, specialVariables ?? variables, specialEntry.Value.VariableSetup.FallbackFormat); specials.Add(new KeyValuePair<IPathMatcher, IRunSpec>(new GlobbingPatternMatcher(specialEntry.Key), spec)); } } Special = specials; } public void SetupFileSource(FileSourceMatchInfo source) { FileSourceHierarchicalPathMatcher matcher = new FileSourceHierarchicalPathMatcher(source); Include = new List<IPathMatcher>() { new FileSourceStateMatcher(FileDispositionStates.Include, matcher) }; Exclude = new List<IPathMatcher>() { new FileSourceStateMatcher(FileDispositionStates.Exclude, matcher) }; CopyOnly = new List<IPathMatcher>() { new FileSourceStateMatcher(FileDispositionStates.CopyOnly, matcher) }; Rename = source.Renames ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } // Returns a list of operations which contains the custom operations and the default operations. // If there are custom Conditional operations, don't include the default Conditionals. // // Note: we may need a more robust filtering mechanism in the future. private static IReadOnlyList<IOperationProvider> ResolveOperations(IGlobalRunConfig runConfig, IDirectory templateRoot, IVariableCollection variables, IParameterSet parameters) { IReadOnlyList<IOperationProvider> customOperations = SetupCustomOperations(runConfig.CustomOperations, templateRoot, variables); IReadOnlyList<IOperationProvider> defaultOperations = SetupOperations(templateRoot.MountPoint.EnvironmentSettings, parameters, runConfig); List<IOperationProvider> operations = new List<IOperationProvider>(customOperations); if (customOperations.Any(x => x is Conditional)) { operations.AddRange(defaultOperations.Where(op => !(op is Conditional))); } else { operations.AddRange(defaultOperations); } return operations; } private static IReadOnlyList<IOperationProvider> SetupOperations(IEngineEnvironmentSettings environmentSettings, IParameterSet parameters, IGlobalRunConfig runConfig) { // default operations List<IOperationProvider> operations = new List<IOperationProvider>(); operations.AddRange(runConfig.Operations); // replacements if (runConfig.Replacements != null) { foreach (IReplacementTokens replaceSetup in runConfig.Replacements) { IOperationProvider replacement = ReplacementConfig.Setup(environmentSettings, replaceSetup, parameters); if (replacement != null) { operations.Add(replacement); } } } if (runConfig.VariableSetup.Expand) { operations?.Add(new ExpandVariables(null, true)); } return operations; } private static IReadOnlyList<IOperationProvider> SetupCustomOperations(IReadOnlyList<ICustomOperationModel> customModel, IDirectory templateRoot, IVariableCollection variables) { ITemplateEngineHost host = templateRoot.MountPoint.EnvironmentSettings.Host; List<IOperationProvider> customOperations = new List<IOperationProvider>(); foreach (ICustomOperationModel opModelUntyped in customModel) { CustomOperationModel opModel = opModelUntyped as CustomOperationModel; if (opModel == null) { host.LogMessage($"Operation type = [{opModelUntyped.Type}] could not be cast as a CustomOperationModel"); continue; } string opType = opModel.Type; string condition = opModel.Condition; if (string.IsNullOrEmpty(condition) || Cpp2StyleEvaluatorDefinition.EvaluateFromString(templateRoot.MountPoint.EnvironmentSettings, condition, variables)) { IOperationConfig realConfigObject; if (_operationConfigLookup.TryGetValue(opType, out realConfigObject)) { customOperations.AddRange( realConfigObject.ConfigureFromJObject(opModel.Configuration, templateRoot)); } else { host.LogMessage($"Operation type = [{opType}] from configuration is unknown."); } } } return customOperations; } internal class ProcessorState : IProcessorState { public ProcessorState(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, byte[] buffer, Encoding encoding) { Config = new EngineConfig(environmentSettings, vars); CurrentBuffer = buffer; CurrentBufferPosition = 0; Encoding = encoding; EncodingConfig = new EncodingConfig(Config, encoding); } public IEngineConfig Config { get; } public byte[] CurrentBuffer { get; private set; } public int CurrentBufferLength => CurrentBuffer.Length; public int CurrentBufferPosition { get; } public Encoding Encoding { get; set; } public IEncodingConfig EncodingConfig { get; } public int CurrentSequenceNumber => throw new NotImplementedException(); public bool AdvanceBuffer(int bufferPosition) { byte[] tmp = new byte[CurrentBufferLength - bufferPosition]; Buffer.BlockCopy(CurrentBuffer, bufferPosition, tmp, 0, CurrentBufferLength - bufferPosition); CurrentBuffer = tmp; return true; } public void SeekBackUntil(ITokenTrie match) { throw new NotImplementedException(); } public void SeekBackUntil(ITokenTrie match, bool consume) { throw new NotImplementedException(); } public void SeekBackWhile(ITokenTrie match) { throw new NotImplementedException(); } public void SeekForwardUntil(ITokenTrie trie, ref int bufferLength, ref int currentBufferPosition) { throw new NotImplementedException(); } public void SeekForwardThrough(ITokenTrie trie, ref int bufferLength, ref int currentBufferPosition) { throw new NotImplementedException(); } public void SeekForwardWhile(ITokenTrie trie, ref int bufferLength, ref int currentBufferPosition) { throw new NotImplementedException(); } public void Inject(Stream staged) { throw new NotImplementedException(); } } } }
// 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! namespace Google.Cloud.Dialogflow.V2.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; using gcdv = Google.Cloud.Dialogflow.V2; /// <summary>Generated snippets.</summary> public sealed class GeneratedVersionsClientSnippets { /// <summary>Snippet for ListVersions</summary> public void ListVersionsRequestObject() { // Snippet: ListVersions(ListVersionsRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) ListVersionsRequest request = new ListVersionsRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), }; // Make the request PagedEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersions(request); // Iterate over all response items, lazily performing RPCs as required foreach (gcdv::Version item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListVersionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersionsAsync</summary> public async Task ListVersionsRequestObjectAsync() { // Snippet: ListVersionsAsync(ListVersionsRequest, CallSettings) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) ListVersionsRequest request = new ListVersionsRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((gcdv::Version item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListVersionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersions</summary> public void ListVersions() { // Snippet: ListVersions(string, string, int?, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent"; // Make the request PagedEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersions(parent); // Iterate over all response items, lazily performing RPCs as required foreach (gcdv::Version item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListVersionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersionsAsync</summary> public async Task ListVersionsAsync() { // Snippet: ListVersionsAsync(string, string, int?, CallSettings) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent"; // Make the request PagedAsyncEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((gcdv::Version item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListVersionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersions</summary> public void ListVersionsResourceNames() { // Snippet: ListVersions(AgentName, string, int?, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) AgentName parent = AgentName.FromProject("[PROJECT]"); // Make the request PagedEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersions(parent); // Iterate over all response items, lazily performing RPCs as required foreach (gcdv::Version item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListVersionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersionsAsync</summary> public async Task ListVersionsResourceNamesAsync() { // Snippet: ListVersionsAsync(AgentName, string, int?, CallSettings) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) AgentName parent = AgentName.FromProject("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((gcdv::Version item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListVersionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetVersion</summary> public void GetVersionRequestObject() { // Snippet: GetVersion(GetVersionRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) GetVersionRequest request = new GetVersionRequest { VersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), }; // Make the request gcdv::Version response = versionsClient.GetVersion(request); // End snippet } /// <summary>Snippet for GetVersionAsync</summary> public async Task GetVersionRequestObjectAsync() { // Snippet: GetVersionAsync(GetVersionRequest, CallSettings) // Additional: GetVersionAsync(GetVersionRequest, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) GetVersionRequest request = new GetVersionRequest { VersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), }; // Make the request gcdv::Version response = await versionsClient.GetVersionAsync(request); // End snippet } /// <summary>Snippet for GetVersion</summary> public void GetVersion() { // Snippet: GetVersion(string, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/versions/[VERSION]"; // Make the request gcdv::Version response = versionsClient.GetVersion(name); // End snippet } /// <summary>Snippet for GetVersionAsync</summary> public async Task GetVersionAsync() { // Snippet: GetVersionAsync(string, CallSettings) // Additional: GetVersionAsync(string, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/versions/[VERSION]"; // Make the request gcdv::Version response = await versionsClient.GetVersionAsync(name); // End snippet } /// <summary>Snippet for GetVersion</summary> public void GetVersionResourceNames() { // Snippet: GetVersion(VersionName, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) VersionName name = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"); // Make the request gcdv::Version response = versionsClient.GetVersion(name); // End snippet } /// <summary>Snippet for GetVersionAsync</summary> public async Task GetVersionResourceNamesAsync() { // Snippet: GetVersionAsync(VersionName, CallSettings) // Additional: GetVersionAsync(VersionName, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) VersionName name = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"); // Make the request gcdv::Version response = await versionsClient.GetVersionAsync(name); // End snippet } /// <summary>Snippet for CreateVersion</summary> public void CreateVersionRequestObject() { // Snippet: CreateVersion(CreateVersionRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) CreateVersionRequest request = new CreateVersionRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), Version = new gcdv::Version(), }; // Make the request gcdv::Version response = versionsClient.CreateVersion(request); // End snippet } /// <summary>Snippet for CreateVersionAsync</summary> public async Task CreateVersionRequestObjectAsync() { // Snippet: CreateVersionAsync(CreateVersionRequest, CallSettings) // Additional: CreateVersionAsync(CreateVersionRequest, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) CreateVersionRequest request = new CreateVersionRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), Version = new gcdv::Version(), }; // Make the request gcdv::Version response = await versionsClient.CreateVersionAsync(request); // End snippet } /// <summary>Snippet for CreateVersion</summary> public void CreateVersion() { // Snippet: CreateVersion(string, Version, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent"; gcdv::Version version = new gcdv::Version(); // Make the request gcdv::Version response = versionsClient.CreateVersion(parent, version); // End snippet } /// <summary>Snippet for CreateVersionAsync</summary> public async Task CreateVersionAsync() { // Snippet: CreateVersionAsync(string, Version, CallSettings) // Additional: CreateVersionAsync(string, Version, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent"; gcdv::Version version = new gcdv::Version(); // Make the request gcdv::Version response = await versionsClient.CreateVersionAsync(parent, version); // End snippet } /// <summary>Snippet for CreateVersion</summary> public void CreateVersionResourceNames() { // Snippet: CreateVersion(AgentName, Version, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) AgentName parent = AgentName.FromProject("[PROJECT]"); gcdv::Version version = new gcdv::Version(); // Make the request gcdv::Version response = versionsClient.CreateVersion(parent, version); // End snippet } /// <summary>Snippet for CreateVersionAsync</summary> public async Task CreateVersionResourceNamesAsync() { // Snippet: CreateVersionAsync(AgentName, Version, CallSettings) // Additional: CreateVersionAsync(AgentName, Version, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) AgentName parent = AgentName.FromProject("[PROJECT]"); gcdv::Version version = new gcdv::Version(); // Make the request gcdv::Version response = await versionsClient.CreateVersionAsync(parent, version); // End snippet } /// <summary>Snippet for UpdateVersion</summary> public void UpdateVersionRequestObject() { // Snippet: UpdateVersion(UpdateVersionRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) UpdateVersionRequest request = new UpdateVersionRequest { Version = new gcdv::Version(), UpdateMask = new FieldMask(), }; // Make the request gcdv::Version response = versionsClient.UpdateVersion(request); // End snippet } /// <summary>Snippet for UpdateVersionAsync</summary> public async Task UpdateVersionRequestObjectAsync() { // Snippet: UpdateVersionAsync(UpdateVersionRequest, CallSettings) // Additional: UpdateVersionAsync(UpdateVersionRequest, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) UpdateVersionRequest request = new UpdateVersionRequest { Version = new gcdv::Version(), UpdateMask = new FieldMask(), }; // Make the request gcdv::Version response = await versionsClient.UpdateVersionAsync(request); // End snippet } /// <summary>Snippet for UpdateVersion</summary> public void UpdateVersion() { // Snippet: UpdateVersion(Version, FieldMask, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) gcdv::Version version = new gcdv::Version(); FieldMask updateMask = new FieldMask(); // Make the request gcdv::Version response = versionsClient.UpdateVersion(version, updateMask); // End snippet } /// <summary>Snippet for UpdateVersionAsync</summary> public async Task UpdateVersionAsync() { // Snippet: UpdateVersionAsync(Version, FieldMask, CallSettings) // Additional: UpdateVersionAsync(Version, FieldMask, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) gcdv::Version version = new gcdv::Version(); FieldMask updateMask = new FieldMask(); // Make the request gcdv::Version response = await versionsClient.UpdateVersionAsync(version, updateMask); // End snippet } /// <summary>Snippet for DeleteVersion</summary> public void DeleteVersionRequestObject() { // Snippet: DeleteVersion(DeleteVersionRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) DeleteVersionRequest request = new DeleteVersionRequest { VersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), }; // Make the request versionsClient.DeleteVersion(request); // End snippet } /// <summary>Snippet for DeleteVersionAsync</summary> public async Task DeleteVersionRequestObjectAsync() { // Snippet: DeleteVersionAsync(DeleteVersionRequest, CallSettings) // Additional: DeleteVersionAsync(DeleteVersionRequest, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) DeleteVersionRequest request = new DeleteVersionRequest { VersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), }; // Make the request await versionsClient.DeleteVersionAsync(request); // End snippet } /// <summary>Snippet for DeleteVersion</summary> public void DeleteVersion() { // Snippet: DeleteVersion(string, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/versions/[VERSION]"; // Make the request versionsClient.DeleteVersion(name); // End snippet } /// <summary>Snippet for DeleteVersionAsync</summary> public async Task DeleteVersionAsync() { // Snippet: DeleteVersionAsync(string, CallSettings) // Additional: DeleteVersionAsync(string, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/versions/[VERSION]"; // Make the request await versionsClient.DeleteVersionAsync(name); // End snippet } /// <summary>Snippet for DeleteVersion</summary> public void DeleteVersionResourceNames() { // Snippet: DeleteVersion(VersionName, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) VersionName name = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"); // Make the request versionsClient.DeleteVersion(name); // End snippet } /// <summary>Snippet for DeleteVersionAsync</summary> public async Task DeleteVersionResourceNamesAsync() { // Snippet: DeleteVersionAsync(VersionName, CallSettings) // Additional: DeleteVersionAsync(VersionName, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) VersionName name = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"); // Make the request await versionsClient.DeleteVersionAsync(name); // End snippet } } }
// 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.Buffers.Text { public static partial class Utf8Parser { private static bool TryParseSByteN(ReadOnlySpan<byte> text, out sbyte value, out int bytesConsumed) { if (text.Length < 1) goto FalseExit; int sign = 1; int index = 0; int c = text[index]; if (c == '-') { sign = -1; index++; if ((uint)index >= (uint)text.Length) goto FalseExit; c = text[index]; } else if (c == '+') { index++; if ((uint)index >= (uint)text.Length) goto FalseExit; c = text[index]; } int answer; // Handle the first digit (or period) as a special case. This ensures some compatible edge-case behavior with the classic parse routines // (at least one digit must precede any commas, and a string without any digits prior to the decimal point must have at least // one digit after the decimal point.) if (c == Utf8Constants.Period) goto FractionalPartWithoutLeadingDigits; if (!ParserHelpers.IsDigit(c)) goto FalseExit; answer = c - '0'; for (; ; ) { index++; if ((uint)index >= (uint)text.Length) goto Done; c = text[index]; if (c == Utf8Constants.Comma) continue; if (c == Utf8Constants.Period) goto FractionalDigits; if (!ParserHelpers.IsDigit(c)) goto Done; answer = answer * 10 + c - '0'; // if sign < 0, (-1 * sign + 1) / 2 = 1 // else, (-1 * sign + 1) / 2 = 0 if (answer > sbyte.MaxValue + (-1 * sign + 1) / 2) goto FalseExit; // Overflow } FractionalPartWithoutLeadingDigits: // If we got here, we found a decimal point before we found any digits. This is legal as long as there's at least one zero after the decimal point. answer = 0; index++; if ((uint)index >= (uint)text.Length) goto FalseExit; if (text[index] != '0') goto FalseExit; FractionalDigits: // "N" format allows a fractional portion despite being an integer format but only if the post-fraction digits are all 0. do { index++; if ((uint)index >= (uint)text.Length) goto Done; c = text[index]; } while (c == '0'); if (ParserHelpers.IsDigit(c)) goto FalseExit; // The fractional portion contained a non-zero digit. Treat this as an error, not an early termination. goto Done; FalseExit: bytesConsumed = default; value = default; return false; Done: bytesConsumed = index; value = (sbyte)(answer * sign); return true; } private static bool TryParseInt16N(ReadOnlySpan<byte> text, out short value, out int bytesConsumed) { if (text.Length < 1) goto FalseExit; int sign = 1; int index = 0; int c = text[index]; if (c == '-') { sign = -1; index++; if ((uint)index >= (uint)text.Length) goto FalseExit; c = text[index]; } else if (c == '+') { index++; if ((uint)index >= (uint)text.Length) goto FalseExit; c = text[index]; } int answer; // Handle the first digit (or period) as a special case. This ensures some compatible edge-case behavior with the classic parse routines // (at least one digit must precede any commas, and a string without any digits prior to the decimal point must have at least // one digit after the decimal point.) if (c == Utf8Constants.Period) goto FractionalPartWithoutLeadingDigits; if (!ParserHelpers.IsDigit(c)) goto FalseExit; answer = c - '0'; for (; ; ) { index++; if ((uint)index >= (uint)text.Length) goto Done; c = text[index]; if (c == Utf8Constants.Comma) continue; if (c == Utf8Constants.Period) goto FractionalDigits; if (!ParserHelpers.IsDigit(c)) goto Done; answer = answer * 10 + c - '0'; // if sign < 0, (-1 * sign + 1) / 2 = 1 // else, (-1 * sign + 1) / 2 = 0 if (answer > short.MaxValue + (-1 * sign + 1) / 2) goto FalseExit; // Overflow } FractionalPartWithoutLeadingDigits: // If we got here, we found a decimal point before we found any digits. This is legal as long as there's at least one zero after the decimal point. answer = 0; index++; if ((uint)index >= (uint)text.Length) goto FalseExit; if (text[index] != '0') goto FalseExit; FractionalDigits: // "N" format allows a fractional portion despite being an integer format but only if the post-fraction digits are all 0. do { index++; if ((uint)index >= (uint)text.Length) goto Done; c = text[index]; } while (c == '0'); if (ParserHelpers.IsDigit(c)) goto FalseExit; // The fractional portion contained a non-zero digit. Treat this as an error, not an early termination. goto Done; FalseExit: bytesConsumed = default; value = default; return false; Done: bytesConsumed = index; value = (short)(answer * sign); return true; } private static bool TryParseInt32N(ReadOnlySpan<byte> text, out int value, out int bytesConsumed) { if (text.Length < 1) goto FalseExit; int sign = 1; int index = 0; int c = text[index]; if (c == '-') { sign = -1; index++; if ((uint)index >= (uint)text.Length) goto FalseExit; c = text[index]; } else if (c == '+') { index++; if ((uint)index >= (uint)text.Length) goto FalseExit; c = text[index]; } int answer; // Handle the first digit (or period) as a special case. This ensures some compatible edge-case behavior with the classic parse routines // (at least one digit must precede any commas, and a string without any digits prior to the decimal point must have at least // one digit after the decimal point.) if (c == Utf8Constants.Period) goto FractionalPartWithoutLeadingDigits; if (!ParserHelpers.IsDigit(c)) goto FalseExit; answer = c - '0'; for (; ; ) { index++; if ((uint)index >= (uint)text.Length) goto Done; c = text[index]; if (c == Utf8Constants.Comma) continue; if (c == Utf8Constants.Period) goto FractionalDigits; if (!ParserHelpers.IsDigit(c)) goto Done; if (((uint)answer) > int.MaxValue / 10) goto FalseExit; answer = answer * 10 + c - '0'; // if sign < 0, (-1 * sign + 1) / 2 = 1 // else, (-1 * sign + 1) / 2 = 0 if ((uint)answer > (uint)int.MaxValue + (-1 * sign + 1) / 2) goto FalseExit; // Overflow } FractionalPartWithoutLeadingDigits: // If we got here, we found a decimal point before we found any digits. This is legal as long as there's at least one zero after the decimal point. answer = 0; index++; if ((uint)index >= (uint)text.Length) goto FalseExit; if (text[index] != '0') goto FalseExit; FractionalDigits: // "N" format allows a fractional portion despite being an integer format but only if the post-fraction digits are all 0. do { index++; if ((uint)index >= (uint)text.Length) goto Done; c = text[index]; } while (c == '0'); if (ParserHelpers.IsDigit(c)) goto FalseExit; // The fractional portion contained a non-zero digit. Treat this as an error, not an early termination. goto Done; FalseExit: bytesConsumed = default; value = default; return false; Done: bytesConsumed = index; value = answer * sign; return true; } private static bool TryParseInt64N(ReadOnlySpan<byte> text, out long value, out int bytesConsumed) { if (text.Length < 1) goto FalseExit; int sign = 1; int index = 0; int c = text[index]; if (c == '-') { sign = -1; index++; if ((uint)index >= (uint)text.Length) goto FalseExit; c = text[index]; } else if (c == '+') { index++; if ((uint)index >= (uint)text.Length) goto FalseExit; c = text[index]; } long answer; // Handle the first digit (or period) as a special case. This ensures some compatible edge-case behavior with the classic parse routines // (at least one digit must precede any commas, and a string without any digits prior to the decimal point must have at least // one digit after the decimal point.) if (c == Utf8Constants.Period) goto FractionalPartWithoutLeadingDigits; if (!ParserHelpers.IsDigit(c)) goto FalseExit; answer = c - '0'; for (; ; ) { index++; if ((uint)index >= (uint)text.Length) goto Done; c = text[index]; if (c == Utf8Constants.Comma) continue; if (c == Utf8Constants.Period) goto FractionalDigits; if (!ParserHelpers.IsDigit(c)) goto Done; if (((ulong)answer) > long.MaxValue / 10) goto FalseExit; answer = answer * 10 + c - '0'; // if sign < 0, (-1 * sign + 1) / 2 = 1 // else, (-1 * sign + 1) / 2 = 0 if ((ulong)answer > (ulong)(long.MaxValue + (-1 * sign + 1) / 2)) goto FalseExit; // Overflow } FractionalPartWithoutLeadingDigits: // If we got here, we found a decimal point before we found any digits. This is legal as long as there's at least one zero after the decimal point. answer = 0; index++; if ((uint)index >= (uint)text.Length) goto FalseExit; if (text[index] != '0') goto FalseExit; FractionalDigits: // "N" format allows a fractional portion despite being an integer format but only if the post-fraction digits are all 0. do { index++; if ((uint)index >= (uint)text.Length) goto Done; c = text[index]; } while (c == '0'); if (ParserHelpers.IsDigit(c)) goto FalseExit; // The fractional portion contained a non-zero digit. Treat this as an error, not an early termination. goto Done; FalseExit: bytesConsumed = default; value = default; return false; Done: bytesConsumed = index; value = answer * sign; return true; } } }
namespace android.graphics.drawable { [global::MonoJavaBridge.JavaClass()] public partial class InsetDrawable : android.graphics.drawable.Drawable, android.graphics.drawable.Drawable.Callback { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static InsetDrawable() { InitJNI(); } protected InsetDrawable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _inflate4050; public override void inflate(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1, android.util.AttributeSet arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._inflate4050, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._inflate4050, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _draw4051; public override void draw(android.graphics.Canvas arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._draw4051, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._draw4051, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getChangingConfigurations4052; public override int getChangingConfigurations() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._getChangingConfigurations4052); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._getChangingConfigurations4052); } internal static global::MonoJavaBridge.MethodId _setAlpha4053; public override void setAlpha(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._setAlpha4053, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._setAlpha4053, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setColorFilter4054; public override void setColorFilter(android.graphics.ColorFilter arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._setColorFilter4054, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._setColorFilter4054, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isStateful4055; public override bool isStateful() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._isStateful4055); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._isStateful4055); } internal static global::MonoJavaBridge.MethodId _setVisible4056; public override bool setVisible(bool arg0, bool arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._setVisible4056, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._setVisible4056, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getOpacity4057; public override int getOpacity() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._getOpacity4057); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._getOpacity4057); } internal static global::MonoJavaBridge.MethodId _onStateChange4058; protected override bool onStateChange(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._onStateChange4058, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._onStateChange4058, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onBoundsChange4059; protected override void onBoundsChange(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._onBoundsChange4059, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._onBoundsChange4059, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getIntrinsicWidth4060; public override int getIntrinsicWidth() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._getIntrinsicWidth4060); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._getIntrinsicWidth4060); } internal static global::MonoJavaBridge.MethodId _getIntrinsicHeight4061; public override int getIntrinsicHeight() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._getIntrinsicHeight4061); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._getIntrinsicHeight4061); } internal static global::MonoJavaBridge.MethodId _getPadding4062; public override bool getPadding(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._getPadding4062, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._getPadding4062, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _mutate4063; public override global::android.graphics.drawable.Drawable mutate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._mutate4063)) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._mutate4063)) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _getConstantState4064; public override global::android.graphics.drawable.Drawable.ConstantState getConstantState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._getConstantState4064)) as android.graphics.drawable.Drawable.ConstantState; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._getConstantState4064)) as android.graphics.drawable.Drawable.ConstantState; } internal static global::MonoJavaBridge.MethodId _invalidateDrawable4065; public virtual void invalidateDrawable(android.graphics.drawable.Drawable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._invalidateDrawable4065, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._invalidateDrawable4065, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _scheduleDrawable4066; public virtual void scheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1, long arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._scheduleDrawable4066, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._scheduleDrawable4066, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _unscheduleDrawable4067; public virtual void unscheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable._unscheduleDrawable4067, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._unscheduleDrawable4067, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _InsetDrawable4068; public InsetDrawable(android.graphics.drawable.Drawable arg0, int arg1, int arg2, int arg3, int arg4) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._InsetDrawable4068, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _InsetDrawable4069; public InsetDrawable(android.graphics.drawable.Drawable arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.InsetDrawable.staticClass, global::android.graphics.drawable.InsetDrawable._InsetDrawable4069, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.drawable.InsetDrawable.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/InsetDrawable")); global::android.graphics.drawable.InsetDrawable._inflate4050 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "inflate", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)V"); global::android.graphics.drawable.InsetDrawable._draw4051 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "draw", "(Landroid/graphics/Canvas;)V"); global::android.graphics.drawable.InsetDrawable._getChangingConfigurations4052 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "getChangingConfigurations", "()I"); global::android.graphics.drawable.InsetDrawable._setAlpha4053 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "setAlpha", "(I)V"); global::android.graphics.drawable.InsetDrawable._setColorFilter4054 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "setColorFilter", "(Landroid/graphics/ColorFilter;)V"); global::android.graphics.drawable.InsetDrawable._isStateful4055 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "isStateful", "()Z"); global::android.graphics.drawable.InsetDrawable._setVisible4056 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "setVisible", "(ZZ)Z"); global::android.graphics.drawable.InsetDrawable._getOpacity4057 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "getOpacity", "()I"); global::android.graphics.drawable.InsetDrawable._onStateChange4058 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "onStateChange", "([I)Z"); global::android.graphics.drawable.InsetDrawable._onBoundsChange4059 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "onBoundsChange", "(Landroid/graphics/Rect;)V"); global::android.graphics.drawable.InsetDrawable._getIntrinsicWidth4060 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "getIntrinsicWidth", "()I"); global::android.graphics.drawable.InsetDrawable._getIntrinsicHeight4061 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "getIntrinsicHeight", "()I"); global::android.graphics.drawable.InsetDrawable._getPadding4062 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "getPadding", "(Landroid/graphics/Rect;)Z"); global::android.graphics.drawable.InsetDrawable._mutate4063 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "mutate", "()Landroid/graphics/drawable/Drawable;"); global::android.graphics.drawable.InsetDrawable._getConstantState4064 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "getConstantState", "()Landroid/graphics/drawable/Drawable$ConstantState;"); global::android.graphics.drawable.InsetDrawable._invalidateDrawable4065 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "invalidateDrawable", "(Landroid/graphics/drawable/Drawable;)V"); global::android.graphics.drawable.InsetDrawable._scheduleDrawable4066 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "scheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;J)V"); global::android.graphics.drawable.InsetDrawable._unscheduleDrawable4067 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "unscheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;)V"); global::android.graphics.drawable.InsetDrawable._InsetDrawable4068 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "<init>", "(Landroid/graphics/drawable/Drawable;IIII)V"); global::android.graphics.drawable.InsetDrawable._InsetDrawable4069 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.InsetDrawable.staticClass, "<init>", "(Landroid/graphics/drawable/Drawable;I)V"); } } }
// 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 Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal abstract class EditAndContinueTestHelpers { public abstract AbstractEditAndContinueAnalyzer Analyzer { get; } public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span); public abstract SyntaxTree ParseText(string source); public abstract Compilation CreateLibraryCompilation(string name, IEnumerable<SyntaxTree> trees); public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method); internal void VerifyUnchangedDocument( string source, ActiveStatementSpan[] oldActiveStatements, TextSpan?[] trackingSpansOpt, TextSpan[] expectedNewActiveStatements, ImmutableArray<TextSpan>[] expectedOldExceptionRegions, ImmutableArray<TextSpan>[] expectedNewExceptionRegions) { var text = SourceText.From(source); var tree = ParseText(source); var root = tree.GetRoot(); tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument"); TestActiveStatementTrackingService trackingService; if (trackingSpansOpt != null) { trackingService = new TestActiveStatementTrackingService(documentId, trackingSpansOpt); } else { trackingService = null; } var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length]; var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length]; Analyzer.AnalyzeUnchangedDocument( oldActiveStatements.AsImmutable(), text, root, documentId, trackingService, actualNewActiveStatements, actualNewExceptionRegions); // check active statements: AssertSpansEqual(expectedNewActiveStatements, actualNewActiveStatements, source, text); // check new exception regions: Assert.Equal(expectedNewExceptionRegions.Length, actualNewExceptionRegions.Length); for (int i = 0; i < expectedNewExceptionRegions.Length; i++) { AssertSpansEqual(expectedNewExceptionRegions[i], actualNewExceptionRegions[i], source, text); } } internal void VerifyRudeDiagnostics( EditScript<SyntaxNode> editScript, ActiveStatementsDescription description, RudeEditDiagnosticDescription[] expectedDiagnostics) { var oldActiveStatements = description.OldSpans; if (description.OldTrackingSpans != null) { Assert.Equal(oldActiveStatements.Length, description.OldTrackingSpans.Length); } string newSource = editScript.Match.NewRoot.SyntaxTree.ToString(); string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString(); var oldText = SourceText.From(oldSource); var newText = SourceText.From(newSource); var diagnostics = new List<RudeEditDiagnostic>(); var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length]; var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length]; var updatedActiveMethodMatches = new List<AbstractEditAndContinueAnalyzer.UpdatedMemberInfo>(); var editMap = Analyzer.BuildEditMap(editScript); DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument"); TestActiveStatementTrackingService trackingService; if (description.OldTrackingSpans != null) { trackingService = new TestActiveStatementTrackingService(documentId, description.OldTrackingSpans); } else { trackingService = null; } Analyzer.AnalyzeSyntax( editScript, editMap, oldText, newText, documentId, trackingService, oldActiveStatements.AsImmutable(), actualNewActiveStatements, actualNewExceptionRegions, updatedActiveMethodMatches, diagnostics); diagnostics.Verify(newSource, expectedDiagnostics); // check active statements: AssertSpansEqual(description.NewSpans, actualNewActiveStatements, newSource, newText); if (diagnostics.Count == 0) { // check old exception regions: for (int i = 0; i < oldActiveStatements.Length; i++) { var actualOldExceptionRegions = Analyzer.GetExceptionRegions( oldText, editScript.Match.OldRoot, oldActiveStatements[i].Span, isLeaf: (oldActiveStatements[i].Flags & ActiveStatementFlags.LeafFrame) != 0); AssertSpansEqual(description.OldRegions[i], actualOldExceptionRegions, oldSource, oldText); } // check new exception regions: Assert.Equal(description.NewRegions.Length, actualNewExceptionRegions.Length); for (int i = 0; i < description.NewRegions.Length; i++) { AssertSpansEqual(description.NewRegions[i], actualNewExceptionRegions[i], newSource, newText); } } else { for (int i = 0; i < oldActiveStatements.Length; i++) { Assert.Equal(0, description.NewRegions[i].Length); } } if (description.OldTrackingSpans != null) { // Verify that the new tracking spans are equal to the new active statements. AssertEx.Equal(trackingService.TrackingSpans, description.NewSpans.Select(s => (TextSpan?)s)); } } internal void VerifyLineEdits( EditScript<SyntaxNode> editScript, IEnumerable<LineChange> expectedLineEdits, IEnumerable<string> expectedNodeUpdates, RudeEditDiagnosticDescription[] expectedDiagnostics) { string newSource = editScript.Match.NewRoot.SyntaxTree.ToString(); string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString(); var oldText = SourceText.From(oldSource); var newText = SourceText.From(newSource); var diagnostics = new List<RudeEditDiagnostic>(); var editMap = Analyzer.BuildEditMap(editScript); var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); var actualLineEdits = new List<LineChange>(); Analyzer.AnalyzeTrivia( oldText, newText, editScript.Match, editMap, triviaEdits, actualLineEdits, diagnostics, default(CancellationToken)); diagnostics.Verify(newSource, expectedDiagnostics); AssertEx.Equal(expectedLineEdits, actualLineEdits, itemSeparator: ",\r\n"); var actualNodeUpdates = triviaEdits.Select(e => e.Value.ToString().ToLines().First()); AssertEx.Equal(expectedNodeUpdates, actualNodeUpdates, itemSeparator: ",\r\n"); } internal void VerifySemantics( EditScript<SyntaxNode> editScript, ActiveStatementsDescription activeStatements, IEnumerable<string> additionalOldSources = null, IEnumerable<string> additionalNewSources = null, SemanticEditDescription[] expectedSemanticEdits = null, RudeEditDiagnosticDescription[] expectedDiagnostics = null) { var editMap = Analyzer.BuildEditMap(editScript); var oldRoot = editScript.Match.OldRoot; var newRoot = editScript.Match.NewRoot; var oldSource = oldRoot.SyntaxTree.ToString(); var newSource = newRoot.SyntaxTree.ToString(); var oldText = SourceText.From(oldSource); var newText = SourceText.From(newSource); IEnumerable<SyntaxTree> oldTrees = new[] { oldRoot.SyntaxTree }; IEnumerable<SyntaxTree> newTrees = new[] { newRoot.SyntaxTree }; if (additionalOldSources != null) { oldTrees = oldTrees.Concat(additionalOldSources.Select(s => ParseText(s))); } if (additionalOldSources != null) { newTrees = newTrees.Concat(additionalNewSources.Select(s => ParseText(s))); } var oldCompilation = CreateLibraryCompilation("Old", oldTrees); var newCompilation = CreateLibraryCompilation("New", newTrees); if (oldCompilation is CSharpCompilation) { oldCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); newCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); } else { // TODO: verify all compilation diagnostics like C# does (tests need to be updated) oldTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); newTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); } var oldModel = oldCompilation.GetSemanticModel(oldRoot.SyntaxTree); var newModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree); var oldActiveStatements = activeStatements.OldSpans.AsImmutable(); var updatedActiveMethodMatches = new List<AbstractEditAndContinueAnalyzer.UpdatedMemberInfo>(); var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); var actualLineEdits = new List<LineChange>(); var actualSemanticEdits = new List<SemanticEdit>(); var diagnostics = new List<RudeEditDiagnostic>(); var actualNewActiveStatements = new LinePositionSpan[activeStatements.OldSpans.Length]; var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[activeStatements.OldSpans.Length]; Analyzer.AnalyzeSyntax( editScript, editMap, oldText, newText, null, null, oldActiveStatements, actualNewActiveStatements, actualNewExceptionRegions, updatedActiveMethodMatches, diagnostics); diagnostics.Verify(newSource); Analyzer.AnalyzeTrivia( oldText, newText, editScript.Match, editMap, triviaEdits, actualLineEdits, diagnostics, default(CancellationToken)); diagnostics.Verify(newSource); Analyzer.AnalyzeSemantics( editScript, editMap, oldText, oldActiveStatements, triviaEdits, updatedActiveMethodMatches, oldModel, newModel, actualSemanticEdits, diagnostics, default(CancellationToken)); diagnostics.Verify(newSource, expectedDiagnostics); if (expectedSemanticEdits == null) { return; } Assert.Equal(expectedSemanticEdits.Length, actualSemanticEdits.Count); for (int i = 0; i < actualSemanticEdits.Count; i++) { var editKind = expectedSemanticEdits[i].Kind; Assert.Equal(editKind, actualSemanticEdits[i].Kind); var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdits[i].SymbolProvider(oldCompilation) : null; var expectedNewSymbol = expectedSemanticEdits[i].SymbolProvider(newCompilation); var actualOldSymbol = actualSemanticEdits[i].OldSymbol; var actualNewSymbol = actualSemanticEdits[i].NewSymbol; Assert.Equal(expectedOldSymbol, actualOldSymbol); Assert.Equal(expectedNewSymbol, actualNewSymbol); var expectedSyntaxMap = expectedSemanticEdits[i].SyntaxMap; var actualSyntaxMap = actualSemanticEdits[i].SyntaxMap; Assert.Equal(expectedSemanticEdits[i].PreserveLocalVariables, actualSemanticEdits[i].PreserveLocalVariables); if (expectedSyntaxMap != null) { Assert.NotNull(actualSyntaxMap); Assert.True(expectedSemanticEdits[i].PreserveLocalVariables); var newNodes = new List<SyntaxNode>(); foreach (var expectedSpanMapping in expectedSyntaxMap) { var newNode = FindNode(newRoot, expectedSpanMapping.Value); var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key); var actualOldNode = actualSyntaxMap(newNode); Assert.Equal(expectedOldNode, actualOldNode); newNodes.Add(newNode); } } else if (!expectedSemanticEdits[i].PreserveLocalVariables) { Assert.Null(actualSyntaxMap); } } } private static void AssertSpansEqual(IList<TextSpan> expected, IList<LinePositionSpan> actual, string newSource, SourceText newText) { AssertEx.Equal( expected, actual.Select(span => newText.Lines.GetTextSpan(span)), itemSeparator: "\r\n", itemInspector: s => DisplaySpan(newSource, s)); } private static string DisplaySpan(string source, TextSpan span) { return span + ": [" + source.Substring(span.Start, span.Length).Replace("\r\n", " ") + "]"; } internal static IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> GetMethodMatches(AbstractEditAndContinueAnalyzer analyzer, Match<SyntaxNode> bodyMatch) { Dictionary<SyntaxNode, AbstractEditAndContinueAnalyzer.LambdaInfo> lazyActiveOrMatchedLambdas = null; var map = analyzer.ComputeMap(bodyMatch, Array.Empty<AbstractEditAndContinueAnalyzer.ActiveNode>(), ref lazyActiveOrMatchedLambdas, new List<RudeEditDiagnostic>()); var result = new Dictionary<SyntaxNode, SyntaxNode>(); foreach (var pair in map.Forward) { if (pair.Value == bodyMatch.NewRoot) { Assert.Same(pair.Key, bodyMatch.OldRoot); continue; } result.Add(pair.Key, pair.Value); } return result; } public static MatchingPairs ToMatchingPairs(Match<SyntaxNode> match) { return ToMatchingPairs(match.Matches.Where(partners => partners.Key != match.OldRoot)); } public static MatchingPairs ToMatchingPairs(IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> matches) { return new MatchingPairs(matches .OrderBy(partners => partners.Key.GetLocation().SourceSpan.Start) .ThenByDescending(partners => partners.Key.Span.Length) .Select(partners => new MatchingPair { Old = partners.Key.ToString().Replace("\r\n", " ").Replace("\n", " "), New = partners.Value.ToString().Replace("\r\n", " ").Replace("\n", " ") })); } private static IEnumerable<KeyValuePair<K, V>> ReverseMapping<K, V>(IEnumerable<KeyValuePair<V, K>> mapping) { foreach (var pair in mapping) { yield return KeyValuePair.Create(pair.Value, pair.Key); } } } internal static class EditScriptTestUtils { public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected) { AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n"); } } }
// // TextLayoutBackendHandler.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin 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 System.Linq; using AppKit; using CoreGraphics; using CoreText; using Foundation; using Xwt.Backends; using Xwt.Drawing; namespace Xwt.Mac { public class MacTextLayoutBackendHandler: TextLayoutBackendHandler { class LayoutInfo : IDisposable { string text = String.Empty; NSFont font; float? width, height; TextTrimming textTrimming; Alignment textAlignment; readonly public List<TextAttribute> Attributes; readonly ApplicationContext ApplicationContext; readonly NSTextStorage TextStorage; readonly NSTextContainer TextContainer; public string Text { get { return text; } set { text = value; Attributes.Clear (); ResetAttributes (); } } public NSFont Font { get { return font; } set { font = value; ResetAttributes (); } } public TextTrimming TextTrimming { get { return textTrimming; } set { textTrimming = value; ResetAttributes (); } } public Alignment TextAlignment { get { return textAlignment; } set { textAlignment = value; ResetAttributes (); } } public float? Width { get { return width; } set { width = value; TextContainer.Size = new CGSize (value ?? double.MaxValue, TextContainer.Size.Height); } } public float? Height { get { return height; } set { height = value; TextContainer.Size = new CGSize (TextContainer.Size.Width, value ?? double.MaxValue); } } public LayoutInfo (ApplicationContext actx) { ApplicationContext = actx; Attributes = new List<TextAttribute> (); TextStorage = new NSTextStorage (); TextContainer = new NSTextContainer { LineFragmentPadding = 0.0f }; } public void AddAttribute (TextAttribute attribute) { Attributes.Add (attribute); AddAttributeInternal (attribute); } public void ClearAttributes () { Attributes.Clear (); ResetAttributes (); } void ResetAttributes (NSColor foregroundColorOverride = null) { // clear user attributes TextStorage.SetAttributes (new NSDictionary (), new NSRange (0, TextStorage.Length)); var r = new NSRange (0, Text.Length); TextStorage.SetString (new NSAttributedString (Text)); TextStorage.SetAlignment (TextAlignment.ToNSTextAlignment (), r); if (Font != null) // set a global font TextStorage.AddAttribute (NSStringAttributeKey.Font, Font, r); // paragraph style TextContainer.LineBreakMode = TextTrimming == TextTrimming.WordElipsis ? NSLineBreakMode.TruncatingTail : NSLineBreakMode.ByWordWrapping; var pstyle = NSParagraphStyle.DefaultParagraphStyle.MutableCopy () as NSMutableParagraphStyle; pstyle.Alignment = TextAlignment.ToNSTextAlignment (); if (TextTrimming == TextTrimming.WordElipsis) pstyle.LineBreakMode = NSLineBreakMode.TruncatingTail; TextStorage.AddAttribute (NSStringAttributeKey.ParagraphStyle, pstyle, r); // set foreground color override if (foregroundColorOverride != null) TextStorage.AddAttribute(NSStringAttributeKey.ForegroundColor, foregroundColorOverride, r); // restore user attributes foreach (var att in Attributes) AddAttributeInternal (att); } void AddAttributeInternal (TextAttribute attribute) { var r = new NSRange (attribute.StartIndex, attribute.Count); if (attribute is BackgroundTextAttribute) { var xa = (BackgroundTextAttribute)attribute; TextStorage.AddAttribute (NSStringAttributeKey.BackgroundColor, xa.Color.ToNSColor (), r); } else if (attribute is ColorTextAttribute) { var xa = (ColorTextAttribute)attribute; TextStorage.AddAttribute (NSStringAttributeKey.ForegroundColor, xa.Color.ToNSColor (), r); } else if (attribute is UnderlineTextAttribute) { var xa = (UnderlineTextAttribute)attribute; var style = xa.Underline ? NSUnderlineStyle.Single : NSUnderlineStyle.None; TextStorage.AddAttribute(NSStringAttributeKey.UnderlineStyle, NSNumber.FromInt32 ((int)style), r); } else if (attribute is FontStyleTextAttribute) { var xa = (FontStyleTextAttribute)attribute; if (xa.Style == FontStyle.Italic) { TextStorage.ApplyFontTraits (NSFontTraitMask.Italic, r); } else if (xa.Style == FontStyle.Oblique) { // copy Pango.Style.Oblique behaviour (25% skew) TextStorage.AddAttribute (NSStringAttributeKey.Obliqueness, NSNumber.FromFloat ((float)0.25), r); } else { TextStorage.RemoveAttribute (NSStringAttributeKey.Obliqueness, r); TextStorage.ApplyFontTraits (NSFontTraitMask.Unitalic, r); } } else if (attribute is FontWeightTextAttribute) { var xa = (FontWeightTextAttribute)attribute; NSRange er; // get the effective font to modify for the given range var ft = TextStorage.GetAttribute (NSStringAttributeKey.Font, attribute.StartIndex, out er, r) as NSFont; ft = ft.WithWeight (xa.Weight); TextStorage.AddAttribute (NSStringAttributeKey.Font, ft, r); } else if (attribute is LinkTextAttribute) { TextStorage.AddAttribute (NSStringAttributeKey.ForegroundColor, Toolkit.CurrentEngine.Defaults.FallbackLinkColor.ToNSColor (), r); TextStorage.AddAttribute (NSStringAttributeKey.UnderlineStyle, NSNumber.FromInt32 ((int)NSUnderlineStyle.Single), r); } else if (attribute is StrikethroughTextAttribute) { var xa = (StrikethroughTextAttribute)attribute; var style = xa.Strikethrough ? NSUnderlineStyle.Single : NSUnderlineStyle.None; TextStorage.AddAttribute (NSStringAttributeKey.StrikethroughStyle, NSNumber.FromInt32 ((int)style), r); } else if (attribute is FontTextAttribute) { var xa = (FontTextAttribute)attribute; var nf = ((FontData)ApplicationContext.Toolkit.GetSafeBackend (xa.Font)).Font; TextStorage.AddAttribute (NSStringAttributeKey.Font, nf, r); } } public void Draw (CGContext ctx, CGColor foregroundColor, double x, double y) { bool tempForegroundSet = false; // if no color attribute is set for the whole string, // NSLayoutManager will use the default control foreground color. // To override the default color we need to apply the current CGContext stroke color // before all other attributes are set, otherwise it will remove all other foreground colors. if (foregroundColor != null && !Attributes.Any (a => a is ColorTextAttribute && a.StartIndex == 0 && a.Count == Text.Length)) { // FIXME: we need to find a better way to accomplish this without the need to reset all attributes. ResetAttributes(NSColor.FromCGColor(foregroundColor)); tempForegroundSet = true; } ctx.SaveState (); NSGraphicsContext.GlobalSaveGraphicsState (); var nsContext = NSGraphicsContext.FromCGContext (ctx, true); NSGraphicsContext.CurrentContext = nsContext; using (var TextLayout = new NSLayoutManager ()) { TextLayout.AddTextContainer (TextContainer); TextStorage.AddLayoutManager (TextLayout); TextLayout.DrawBackgroundForGlyphRange (new NSRange(0, Text.Length), new CGPoint (x, y)); TextLayout.DrawGlyphsForGlyphRange (new NSRange(0, Text.Length), new CGPoint (x, y)); TextStorage.RemoveLayoutManager (TextLayout); TextLayout.RemoveTextContainer (0); } // reset foreground color change if (tempForegroundSet) ResetAttributes(); NSGraphicsContext.GlobalRestoreGraphicsState (); ctx.RestoreState (); } public CGSize GetSize () { using (var TextLayout = new NSLayoutManager ()) { TextLayout.AddTextContainer (TextContainer); TextStorage.AddLayoutManager (TextLayout); TextLayout.GlyphRangeForBoundingRect (new CGRect (CGPoint.Empty, TextContainer.Size), TextContainer); var s = TextLayout.GetUsedRectForTextContainer (TextContainer); TextStorage.RemoveLayoutManager (TextLayout); TextLayout.RemoveTextContainer (0); return s.Size; } } public double GetBaseLine () { using (var line = new CTLine (TextStorage)) { nfloat ascent, descent, leading; line.GetTypographicBounds (out ascent, out descent, out leading); return ascent; } } public nuint GetIndexFromCoordinates (double x, double y) { using (var TextLayout = new NSLayoutManager ()) { TextLayout.AddTextContainer (TextContainer); TextStorage.AddLayoutManager (TextLayout); TextLayout.GlyphRangeForBoundingRect (new CGRect (CGPoint.Empty, TextContainer.Size), TextContainer); nfloat fraction = 0; var index = TextLayout.CharacterIndexForPoint (new CGPoint (x, y), TextContainer, ref fraction); TextStorage.RemoveLayoutManager (TextLayout); TextLayout.RemoveTextContainer (0); return index; } } public CGPoint GetCoordinateFromIndex(int index) { using (var TextLayout = new NSLayoutManager ()) { TextLayout.AddTextContainer (TextContainer); TextStorage.AddLayoutManager (TextLayout); TextLayout.GlyphRangeForBoundingRect (new CGRect (CGPoint.Empty, TextContainer.Size), TextContainer); var glyphIndex = TextLayout.GlyphIndexForCharacterAtIndex (index); var p = TextLayout.LocationForGlyphAtIndex ((nint)glyphIndex); TextStorage.RemoveLayoutManager (TextLayout); TextLayout.RemoveTextContainer (0); return p; } } public void Dispose () { TextStorage.Dispose (); TextContainer.Dispose (); } } public override object Create () { return new LayoutInfo (ApplicationContext); } public override void SetText (object backend, string text) { LayoutInfo li = (LayoutInfo)backend; li.Text = text == null ? String.Empty : text.Replace ("\r\n", "\n"); } public override void SetFont (object backend, Font font) { LayoutInfo li = (LayoutInfo)backend; li.Font = ((FontData)ApplicationContext.Toolkit.GetSafeBackend (font)).Font; } public override void SetWidth (object backend, double value) { LayoutInfo li = (LayoutInfo)backend; li.Width = value < 0 ? null : (float?)value; } public override void SetHeight (object backend, double value) { LayoutInfo li = (LayoutInfo)backend; li.Height = value < 0 ? null : (float?)value; } public override void SetTrimming (object backend, TextTrimming textTrimming) { LayoutInfo li = (LayoutInfo)backend; li.TextTrimming = textTrimming; } public override void SetAlignment (object backend, Alignment alignment) { LayoutInfo li = (LayoutInfo)backend; li.TextAlignment = alignment; } public override Size GetSize (object backend) { LayoutInfo li = (LayoutInfo)backend; return li.GetSize().ToXwtSize(); } public override double GetBaseline (object backend) { LayoutInfo li = (LayoutInfo)backend; return li.GetBaseLine(); } public override double GetMeanline (object backend) { LayoutInfo li = (LayoutInfo)backend; return GetBaseline (backend) - li.Font.XHeight / 2; } internal static void Draw (CGContextBackend ctx, object layout, double x, double y) { LayoutInfo li = (LayoutInfo)layout; li.Draw (ctx.Context, ctx.CurrentStatus.GlobalColor, x, y); } public override void AddAttribute (object backend, TextAttribute attribute) { LayoutInfo li = (LayoutInfo)backend; li.AddAttribute (attribute); } public override void ClearAttributes (object backend) { LayoutInfo li = (LayoutInfo)backend; li.ClearAttributes (); } public override int GetIndexFromCoordinates (object backend, double x, double y) { LayoutInfo li = (LayoutInfo)backend; return (int)li.GetIndexFromCoordinates (x, y); } public override Point GetCoordinateFromIndex (object backend, int index) { LayoutInfo li = (LayoutInfo)backend; return li.GetCoordinateFromIndex (index).ToXwtPoint (); } public override void Dispose (object backend) { ((LayoutInfo)backend).Dispose (); } } }
// <copyright file="GPGSUtil.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.Editor { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using UnityEditor; using UnityEngine; /// <summary> /// Utility class to perform various tasks in the editor. /// </summary> public static class GPGSUtil { /// <summary>Property key for project requiring G+ access public const string REQUIREGOOGLEPLUSKEY = "proj.requireGPlus"; /// <summary>Property key for project settings.</summary> public const string SERVICEIDKEY = "App.NearbdServiceId"; /// <summary>Property key for project settings.</summary> public const string APPIDKEY = "proj.AppId"; /// <summary>Property key for project settings.</summary> public const string CLASSDIRECTORYKEY = "proj.classDir"; /// <summary>Property key for project settings.</summary> public const string CLASSNAMEKEY = "proj.ConstantsClassName"; /// <summary>Property key for project settings.</summary> public const string WEBCLIENTIDKEY = "and.ClientId"; /// <summary>Property key for project settings.</summary> public const string IOSCLIENTIDKEY = "ios.ClientId"; /// <summary>Property key for project settings.</summary> public const string IOSBUNDLEIDKEY = "ios.BundleId"; /// <summary>Property key for project settings.</summary> public const string ANDROIDRESOURCEKEY = "and.ResourceData"; /// <summary>Property key for project settings.</summary> public const string ANDROIDSETUPDONEKEY = "android.SetupDone"; /// <summary>Property key for project settings.</summary> public const string ANDROIDBUNDLEIDKEY = "and.BundleId"; /// <summary>Property key for project settings.</summary> public const string IOSRESOURCEKEY = "ios.ResourceData"; /// <summary>Property key for project settings.</summary> public const string IOSSETUPDONEKEY = "ios.SetupDone"; /// <summary>Property key for nearby settings done.</summary> public const string NEARBYSETUPDONEKEY = "android.NearbySetupDone"; /// <summary>Property key for project settings.</summary> public const string LASTUPGRADEKEY = "lastUpgrade"; /// <summary>Constant for token replacement</summary> private const string SERVICEIDPLACEHOLDER = "__NEARBY_SERVICE_ID__"; /// <summary>Constant for token replacement</summary> private const string APPIDPLACEHOLDER = "__APP_ID__"; /// <summary>Constant for token replacement</summary> private const string CLASSNAMEPLACEHOLDER = "__Class__"; /// <summary>Constant for token replacement</summary> private const string WEBCLIENTIDPLACEHOLDER = "__WEB_CLIENTID__"; /// <summary>Constant for token replacement</summary> private const string IOSCLIENTIDPLACEHOLDER = "__IOS_CLIENTID__"; /// <summary>Constant for token replacement</summary> private const string IOSBUNDLEIDPLACEHOLDER = "__BUNDLEID__"; /// <summary>Constant for token replacement</summary> private const string TOKENPERMISSIONSHOLDER = "__TOKEN_PERMISSIONS__"; /// <summary>Constant for require google plus token replacement</summary> private const string REQUIREGOOGLEPLUSPLACEHOLDER = "__REQUIRE_GOOGLE_PLUS__"; /// <summary>Property key for project settings.</summary> private const string TOKENPERMISSIONKEY = "proj.tokenPermissions"; /// <summary>Constant for token replacement</summary> private const string NAMESPACESTARTPLACEHOLDER = "__NameSpaceStart__"; /// <summary>Constant for token replacement</summary> private const string NAMESPACEENDPLACEHOLDER = "__NameSpaceEnd__"; /// <summary>Constant for token replacement</summary> private const string CONSTANTSPLACEHOLDER = "__Constant_Properties__"; /// <summary> /// The game info file path. This is a generated file. /// </summary> private const string GameInfoPath = "Assets/GooglePlayGames/GameInfo.cs"; /// <summary> /// The token permissions to add if needed. /// </summary> private const string TokenPermissions = "<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>\n" + "<uses-permission android:name=\"android.permission.USE_CREDENTIALS\"/>"; /// <summary> /// The map of replacements for filling in code templates. The /// key is the string that appears in the template as a placeholder, /// the value is the key into the GPGSProjectSettings. /// </summary> private static Dictionary<string, string> replacements = new Dictionary<string, string>() { { SERVICEIDPLACEHOLDER, SERVICEIDKEY }, { APPIDPLACEHOLDER, APPIDKEY }, { CLASSNAMEPLACEHOLDER, CLASSNAMEKEY }, { WEBCLIENTIDPLACEHOLDER, WEBCLIENTIDKEY }, { IOSCLIENTIDPLACEHOLDER, IOSCLIENTIDKEY }, { IOSBUNDLEIDPLACEHOLDER, IOSBUNDLEIDKEY }, { TOKENPERMISSIONSHOLDER, TOKENPERMISSIONKEY }, { REQUIREGOOGLEPLUSPLACEHOLDER, REQUIREGOOGLEPLUSKEY } }; /// <summary> /// Replaces / in file path to be the os specific separator. /// </summary> /// <returns>The path.</returns> /// <param name="path">Path with correct separators.</param> public static string SlashesToPlatformSeparator(string path) { return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString()); } /// <summary> /// Reads the file. /// </summary> /// <returns>The file contents. The slashes are corrected.</returns> /// <param name="filePath">File path.</param> public static string ReadFile(string filePath) { filePath = SlashesToPlatformSeparator(filePath); if (!File.Exists(filePath)) { Alert("Plugin error: file not found: " + filePath); return null; } StreamReader sr = new StreamReader(filePath); string body = sr.ReadToEnd(); sr.Close(); return body; } /// <summary> /// Reads the editor template. /// </summary> /// <returns>The editor template contents.</returns> /// <param name="name">Name of the template in the editor directory.</param> public static string ReadEditorTemplate(string name) { return ReadFile(SlashesToPlatformSeparator("Assets/GooglePlayGames/Editor/" + name + ".txt")); } /// <summary> /// Writes the file. /// </summary> /// <param name="file">File path - the slashes will be corrected.</param> /// <param name="body">Body of the file to write.</param> public static void WriteFile(string file, string body) { file = SlashesToPlatformSeparator(file); using (var wr = new StreamWriter(file, false)) { wr.Write(body); } } /// <summary> /// Validates the string to be a valid nearby service id. /// </summary> /// <returns><c>true</c>, if like valid service identifier was looksed, <c>false</c> otherwise.</returns> /// <param name="s">string to test.</param> public static bool LooksLikeValidServiceId(string s) { if (s.Length < 3) { return false; } foreach (char c in s) { if (!char.IsLetterOrDigit(c) && c != '.') { return false; } } return true; } /// <summary> /// Looks the like valid app identifier. /// </summary> /// <returns><c>true</c>, if valid app identifier, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidAppId(string s) { if (s.Length < 5) { return false; } foreach (char c in s) { if (c < '0' || c > '9') { return false; } } return true; } /// <summary> /// Looks the like valid client identifier. /// </summary> /// <returns><c>true</c>, if valid client identifier, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidClientId(string s) { return s.EndsWith(".googleusercontent.com"); } /// <summary> /// Looks the like a valid bundle identifier. /// </summary> /// <returns><c>true</c>, if valid bundle identifier, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidBundleId(string s) { return s.Length > 3; } /// <summary> /// Looks like a valid package. /// </summary> /// <returns><c>true</c>, if valid package name, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidPackageName(string s) { if (string.IsNullOrEmpty(s)) { throw new Exception("cannot be empty"); } string[] parts = s.Split(new char[] { '.' }); foreach (string p in parts) { char[] bytes = p.ToCharArray(); for (int i = 0; i < bytes.Length; i++) { if (i == 0 && !char.IsLetter(bytes[i])) { throw new Exception("each part must start with a letter"); } else if (char.IsWhiteSpace(bytes[i])) { throw new Exception("cannot contain spaces"); } else if (!char.IsLetterOrDigit(bytes[i]) && bytes[i] != '_') { throw new Exception("must be alphanumeric or _"); } } } return parts.Length >= 1; } /// <summary> /// Determines if is setup done. /// </summary> /// <returns><c>true</c> if is setup done; otherwise, <c>false</c>.</returns> public static bool IsSetupDone() { bool doneSetup = true; #if UNITY_ANDROID doneSetup = GPGSProjectSettings.Instance.GetBool(ANDROIDSETUPDONEKEY, false); // check gameinfo if (File.Exists(GameInfoPath)) { string contents = ReadFile(GameInfoPath); if (contents.Contains(APPIDPLACEHOLDER)) { Debug.Log("GameInfo not initialized with AppId. " + "Run Window > Google Play Games > Setup > Android Setup..."); return false; } } else { Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > Android Setup..."); return false; } #elif (UNITY_IPHONE && !NO_GPGS) doneSetup = GPGSProjectSettings.Instance.GetBool(IOSSETUPDONEKEY, false); // check gameinfo if (File.Exists(GameInfoPath)) { string contents = ReadFile(GameInfoPath); if (contents.Contains(IOSCLIENTIDPLACEHOLDER)) { Debug.Log("GameInfo not initialized with Client Id. " + "Run Window > Google Play Games > Setup > iOS Setup..."); return false; } } else { Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > iOS Setup..."); return false; } #endif return doneSetup; } /// <summary> /// Makes legal identifier from string. /// Returns a legal C# identifier from the given string. The transformations are: /// - spaces => underscore _ /// - punctuation => empty string /// - leading numbers are prefixed with underscore. /// </summary> /// <returns>the id</returns> /// <param name="key">Key to convert to an identifier.</param> public static string MakeIdentifier(string key) { string s; string retval = string.Empty; if (string.IsNullOrEmpty(key)) { return "_"; } s = key.Trim().Replace(' ', '_'); foreach (char c in s) { if (char.IsLetterOrDigit(c) || c == '_') { retval += c; } } return retval; } /// <summary> /// Displays an error dialog. /// </summary> /// <param name="s">the message</param> public static void Alert(string s) { Alert(GPGSStrings.Error, s); } /// <summary> /// Displays a dialog with the given title and message. /// </summary> /// <param name="title">the title.</param> /// <param name="message">the message.</param> public static void Alert(string title, string message) { EditorUtility.DisplayDialog(title, message, GPGSStrings.Ok); } /// <summary> /// Gets the android sdk path. /// </summary> /// <returns>The android sdk path.</returns> public static string GetAndroidSdkPath() { string sdkPath = EditorPrefs.GetString("AndroidSdkRoot"); if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\"))) { sdkPath = sdkPath.Substring(0, sdkPath.Length - 1); } return sdkPath; } /// <summary> /// Determines if the android sdk exists. /// </summary> /// <returns><c>true</c> if android sdk exists; otherwise, <c>false</c>.</returns> public static bool HasAndroidSdk() { string sdkPath = GetAndroidSdkPath(); return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath); } /// <summary> /// Gets the unity major version. /// </summary> /// <returns>The unity major version.</returns> public static int GetUnityMajorVersion() { #if UNITY_5 string majorVersion = Application.unityVersion.Split('.')[0]; int ver; if (!int.TryParse(majorVersion, out ver)) { ver = 0; } return ver; #elif UNITY_4_6 return 4; #else return 0; #endif } /// <summary> /// Checks for the android manifest file exsistance. /// </summary> /// <returns><c>true</c>, if the file exists <c>false</c> otherwise.</returns> public static bool AndroidManifestExists() { string destFilename = GPGSUtil.SlashesToPlatformSeparator( "Assets/Plugins/Android/MainLibProj/AndroidManifest.xml"); return File.Exists(destFilename); } /// <summary> /// Generates the android manifest. /// </summary> /// <param name="needTokenPermissions">If set to <c>true</c> need token permissions.</param> public static void GenerateAndroidManifest(bool needTokenPermissions) { string destFilename = GPGSUtil.SlashesToPlatformSeparator( "Assets/Plugins/Android/MainLibProj/AndroidManifest.xml"); // Generate AndroidManifest.xml string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest"); Dictionary<string, string> overrideValues = new Dictionary<string, string>(); if (!needTokenPermissions) { overrideValues[TOKENPERMISSIONKEY] = string.Empty; overrideValues[WEBCLIENTIDPLACEHOLDER] = string.Empty; } else { overrideValues[TOKENPERMISSIONKEY] = TokenPermissions; } foreach (KeyValuePair<string, string> ent in replacements) { string value = GPGSProjectSettings.Instance.Get(ent.Value, overrideValues); manifestBody = manifestBody.Replace(ent.Key, value); } GPGSUtil.WriteFile(destFilename, manifestBody); GPGSUtil.UpdateGameInfo(); } /// <summary> /// Writes the resource identifiers file. This file contains the /// resource ids copied (downloaded?) from the play game app console. /// </summary> /// <param name="classDirectory">Class directory.</param> /// <param name="className">Class name.</param> /// <param name="resourceKeys">Resource keys.</param> public static void WriteResourceIds(string classDirectory, string className, Hashtable resourceKeys) { string constantsValues = string.Empty; string[] parts = className.Split('.'); string dirName = classDirectory; if (string.IsNullOrEmpty(dirName)) { dirName = "Assets"; } string nameSpace = string.Empty; for (int i = 0; i < parts.Length - 1; i++) { dirName += "/" + parts[i]; if (nameSpace != string.Empty) { nameSpace += "."; } nameSpace += parts[i]; } EnsureDirExists(dirName); foreach (DictionaryEntry ent in resourceKeys) { string key = MakeIdentifier((string)ent.Key); constantsValues += " public const string " + key + " = \"" + ent.Value + "\"; // <GPGSID>\n"; } string fileBody = GPGSUtil.ReadEditorTemplate("template-Constants"); if (nameSpace != string.Empty) { fileBody = fileBody.Replace( NAMESPACESTARTPLACEHOLDER, "namespace " + nameSpace + "\n{"); } else { fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, string.Empty); } fileBody = fileBody.Replace(CLASSNAMEPLACEHOLDER, parts[parts.Length - 1]); fileBody = fileBody.Replace(CONSTANTSPLACEHOLDER, constantsValues); if (nameSpace != string.Empty) { fileBody = fileBody.Replace( NAMESPACEENDPLACEHOLDER, "}"); } else { fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, string.Empty); } WriteFile(Path.Combine(dirName, parts[parts.Length - 1] + ".cs"), fileBody); } /// <summary> /// Updates the game info file. This is a generated file containing the /// app and client ids. /// </summary> public static void UpdateGameInfo() { string fileBody = GPGSUtil.ReadEditorTemplate("template-GameInfo"); foreach (KeyValuePair<string, string> ent in replacements) { string value = GPGSProjectSettings.Instance.Get(ent.Value); fileBody = fileBody.Replace(ent.Key, value); } GPGSUtil.WriteFile(GameInfoPath, fileBody); } /// <summary> /// Ensures the dir exists. /// </summary> /// <param name="dir">Directory to check.</param> public static void EnsureDirExists(string dir) { dir = SlashesToPlatformSeparator(dir); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } } /// <summary> /// Deletes the dir if exists. /// </summary> /// <param name="dir">Directory to delete.</param> public static void DeleteDirIfExists(string dir) { dir = SlashesToPlatformSeparator(dir); if (Directory.Exists(dir)) { Directory.Delete(dir, true); } } /// <summary> /// Gets the Google Play Services library version. This is only /// needed for Unity versions less than 5. /// </summary> /// <returns>The GPS version.</returns> /// <param name="libProjPath">Lib proj path.</param> private static int GetGPSVersion(string libProjPath) { string versionFile = libProjPath + "/res/values/version.xml"; XmlTextReader reader = new XmlTextReader(new StreamReader(versionFile)); bool inResource = false; int version = -1; while (reader.Read()) { if (reader.Name == "resources") { inResource = true; } if (inResource && reader.Name == "integer") { if ("google_play_services_version".Equals( reader.GetAttribute("name"))) { reader.Read(); Debug.Log("Read version string: " + reader.Value); version = Convert.ToInt32(reader.Value); } } } reader.Close(); return version; } } } #endif
using System; using System.Threading.Tasks; using System.IO; using System.Threading; using System.Reflection; using System.IO.IsolatedStorage; using System.Collections.Generic; using Xamarin.Forms; using System.Security.Cryptography; using System.Text; namespace UnitTests { class MockPlatformServices : IPlatformServices { Action<Action> invokeOnMainThread; Action<Uri> openUriAction; Func<Uri, CancellationToken, Task<Stream>> getStreamAsync; public MockPlatformServices (Action<Action> invokeOnMainThread = null, Action<Uri> openUriAction = null, Func<Uri, CancellationToken, Task<Stream>> getStreamAsync = null) { this.invokeOnMainThread = invokeOnMainThread; this.openUriAction = openUriAction; this.getStreamAsync = getStreamAsync; } static MD5CryptoServiceProvider checksum = new MD5CryptoServiceProvider (); public string GetMD5Hash (string input) { var bytes = checksum.ComputeHash (Encoding.UTF8.GetBytes (input)); var ret = new char [32]; for (int i = 0; i < 16; i++){ ret [i*2] = (char)hex (bytes [i] >> 4); ret [i*2+1] = (char)hex (bytes [i] & 0xf); } return new string (ret); } static int hex (int v) { if (v < 10) return '0' + v; return 'a' + v-10; } public double GetNamedSize (NamedSize size, Type targetElement, bool useOldSizes) { switch (size) { case NamedSize.Default: return 10; case NamedSize.Micro: return 4; case NamedSize.Small: return 8; case NamedSize.Medium: return 12; case NamedSize.Large: return 16; default: throw new ArgumentOutOfRangeException ("size"); } } public void OpenUriAction (Uri uri) { if (openUriAction != null) openUriAction (uri); else throw new NotImplementedException (); } public bool IsInvokeRequired { get { return false; } } public void BeginInvokeOnMainThread (Action action) { if (invokeOnMainThread == null) action (); else invokeOnMainThread (action); } public void StartTimer (TimeSpan interval, Func<bool> callback) { Timer timer = null; TimerCallback onTimeout = o => BeginInvokeOnMainThread (() => { if (callback ()) return; timer.Dispose (); }); timer = new Timer (onTimeout, null, interval, interval); } public Task<Stream> GetStreamAsync (Uri uri, CancellationToken cancellationToken) { if (getStreamAsync == null) throw new NotImplementedException (); return getStreamAsync (uri, cancellationToken); } public Assembly[] GetAssemblies () { return AppDomain.CurrentDomain.GetAssemblies (); } public ITimer CreateTimer (Action<object> callback) { return new MockTimer (new Timer (o => callback(o))); } public ITimer CreateTimer (Action<object> callback, object state, int dueTime, int period) { return new MockTimer (new Timer (o => callback(o), state, dueTime, period)); } public ITimer CreateTimer (Action<object> callback, object state, long dueTime, long period) { return new MockTimer (new Timer (o => callback(o), state, dueTime, period)); } public ITimer CreateTimer (Action<object> callback, object state, TimeSpan dueTime, TimeSpan period) { return new MockTimer (new Timer (o => callback(o), state, dueTime, period)); } public ITimer CreateTimer (Action<object> callback, object state, uint dueTime, uint period) { return new MockTimer (new Timer (o => callback(o), state, dueTime, period)); } public class MockTimer : ITimer { readonly Timer timer; public MockTimer (Timer timer) { this.timer = timer; } public void Change (int dueTime, int period) { timer.Change (dueTime, period); } public void Change (long dueTime, long period) { timer.Change (dueTime, period); } public void Change (TimeSpan dueTime, TimeSpan period) { timer.Change (dueTime, period); } public void Change (uint dueTime, uint period) { timer.Change (dueTime, period); } } public IIsolatedStorageFile GetUserStoreForApplication () { #if WINDOWS_PHONE return new MockIsolatedStorageFile (IsolatedStorageFile.GetUserStoreForApplication ()); #else return new MockIsolatedStorageFile (IsolatedStorageFile.GetUserStoreForAssembly ()); #endif } public class MockIsolatedStorageFile : IIsolatedStorageFile { readonly IsolatedStorageFile isolatedStorageFile; public MockIsolatedStorageFile (IsolatedStorageFile isolatedStorageFile) { this.isolatedStorageFile = isolatedStorageFile; } public Task<bool> GetDirectoryExistsAsync (string path) { return Task.FromResult (isolatedStorageFile.DirectoryExists (path)); } public Task CreateDirectoryAsync (string path) { isolatedStorageFile.CreateDirectory (path); return Task.FromResult (true); } public Task<Stream> OpenFileAsync(string path, Xamarin.Forms.FileMode mode, Xamarin.Forms.FileAccess access) { Stream stream = isolatedStorageFile.OpenFile (path, (System.IO.FileMode)mode, (System.IO.FileAccess)access); return Task.FromResult (stream); } public Task<Stream> OpenFileAsync(string path, Xamarin.Forms.FileMode mode, Xamarin.Forms.FileAccess access, Xamarin.Forms.FileShare share) { Stream stream = isolatedStorageFile.OpenFile (path, (System.IO.FileMode)mode, (System.IO.FileAccess)access, (System.IO.FileShare)share); return Task.FromResult (stream); } public Task<bool> GetFileExistsAsync (string path) { return Task.FromResult (isolatedStorageFile.FileExists (path)); } public Task<DateTimeOffset> GetLastWriteTimeAsync (string path) { return Task.FromResult (isolatedStorageFile.GetLastWriteTime (path)); } } } class MockDeserializer : IDeserializer { public Task<IDictionary<string, object>> DeserializePropertiesAsync () { return Task.FromResult<IDictionary<string, object>> (new Dictionary<string,object> ()); } public Task SerializePropertiesAsync (System.Collections.Generic.IDictionary<string, object> properties) { return Task.FromResult (false); } } class MockResourcesProvider : ISystemResourcesProvider { public IResourceDictionary GetSystemResources () { var dictionary = new ResourceDictionary (); Style style; style = new Style (typeof(Label)); dictionary [Device.Styles.BodyStyleKey] = style; style = new Style (typeof(Label)); style.Setters.Add (Label.FontSizeProperty, 50); dictionary [Device.Styles.TitleStyleKey] = style; style = new Style (typeof(Label)); style.Setters.Add (Label.FontSizeProperty, 40); dictionary [Device.Styles.SubtitleStyleKey] = style; style = new Style (typeof(Label)); style.Setters.Add (Label.FontSizeProperty, 30); dictionary [Device.Styles.CaptionStyleKey] = style; style = new Style (typeof(Label)); style.Setters.Add (Label.FontSizeProperty, 20); dictionary [Device.Styles.ListItemTextStyleKey] = style; style = new Style (typeof(Label)); style.Setters.Add (Label.FontSizeProperty, 10); dictionary [Device.Styles.ListItemDetailTextStyleKey] = style; return dictionary; } } public class MockApplication : Application { public MockApplication () { } } }
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using HtmlAgilityPack; namespace Umbraco.Core.Macros { /// <summary> /// Parses the macro syntax in a string and renders out it's contents /// </summary> internal class MacroTagParser { private static readonly Regex MacroRteContent = new Regex(@"(<!--\s*?)(<\?UMBRACO_MACRO.*?/>)(\s*?-->)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline); private static readonly Regex MacroPersistedFormat = new Regex(@"(<\?UMBRACO_MACRO (?:.+?)??macroAlias=[""']([^""\'\n\r]+?)[""'].+?)(?:/>|>.*?</\?UMBRACO_MACRO>)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline); /// <summary> /// This formats the persisted string to something useful for the rte so that the macro renders properly since we /// persist all macro formats like {?UMBRACO_MACRO macroAlias=\"myMacro\" /} /// </summary> /// <param name="persistedContent"></param> /// <param name="htmlAttributes">The html attributes to be added to the div</param> /// <returns></returns> /// <remarks> /// This converts the persisted macro format to this: /// /// {div class='umb-macro-holder'} /// <!-- <?UMBRACO_MACRO macroAlias=\"myMacro\" /> --> /// {ins}Macro alias: {strong}My Macro{/strong}{/ins} /// {/div} /// /// </remarks> internal static string FormatRichTextPersistedDataForEditor(string persistedContent, IDictionary<string ,string> htmlAttributes) { return MacroPersistedFormat.Replace(persistedContent, match => { if (match.Groups.Count >= 3) { //<div class="umb-macro-holder myMacro mceNonEditable"> var alias = match.Groups[2].Value; var sb = new StringBuilder("<div class=\"umb-macro-holder "); //sb.Append(alias.ToSafeAlias()); sb.Append("mceNonEditable\""); foreach (var htmlAttribute in htmlAttributes) { sb.Append(" "); sb.Append(htmlAttribute.Key); sb.Append("=\""); sb.Append(htmlAttribute.Value); sb.Append("\""); } sb.AppendLine(">"); sb.Append("<!-- "); sb.Append(match.Groups[1].Value.Trim()); sb.Append(" />"); sb.AppendLine(" -->"); sb.Append("<ins>"); sb.Append("Macro alias: "); sb.Append("<strong>"); sb.Append(alias); sb.Append("</strong></ins></div>"); return sb.ToString(); } //replace with nothing if we couldn't find the syntax for whatever reason return ""; }); } /// <summary> /// This formats the string content posted from a rich text editor that contains macro contents to be persisted. /// </summary> /// <returns></returns> /// <remarks> /// /// This is required because when editors are using the rte, the html that is contained in the editor might actually be displaying /// the entire macro content, when the data is submitted the editor will clear most of this data out but we'll still need to parse it properly /// and ensure the correct sytnax is persisted to the db. /// /// When a macro is inserted into the rte editor, the html will be: /// /// {div class='umb-macro-holder'} /// <!-- <?UMBRACO_MACRO macroAlias=\"myMacro\" /> --> /// This could be some macro content /// {/div} /// /// What this method will do is remove the {div} and parse out the commented special macro syntax: {?UMBRACO_MACRO macroAlias=\"myMacro\" /} /// since this is exactly how we need to persist it to the db. /// /// </remarks> internal static string FormatRichTextContentForPersistence(string rteContent) { if (string.IsNullOrEmpty(rteContent)) { return string.Empty; } var html = new HtmlDocument(); html.LoadHtml(rteContent); //get all the comment nodes we want var commentNodes = html.DocumentNode.SelectNodes("//comment()[contains(., '<?UMBRACO_MACRO')]"); if (commentNodes == null) { //There are no macros found, just return the normal content return rteContent; } //replace each containing parent <div> with the comment node itself. foreach (var c in commentNodes) { var div = c.ParentNode; var divContainer = div.ParentNode; divContainer.ReplaceChild(c, div); } var parsed = html.DocumentNode.OuterHtml; //now replace all the <!-- and --> with nothing return MacroRteContent.Replace(parsed, match => { if (match.Groups.Count >= 3) { //get the 3rd group which is the macro syntax return match.Groups[2].Value; } //replace with nothing if we couldn't find the syntax for whatever reason return string.Empty; }); } /// <summary> /// This will accept a text block and seach/parse it for macro markup. /// When either a text block or a a macro is found, it will call the callback method. /// </summary> /// <param name="text"> </param> /// <param name="textFoundCallback"></param> /// <param name="macroFoundCallback"></param> /// <returns></returns> /// <remarks> /// This method simply parses the macro contents, it does not create a string or result, /// this is up to the developer calling this method to implement this with the callbacks. /// </remarks> internal static void ParseMacros( string text, Action<string> textFoundCallback, Action<string, Dictionary<string, string>> macroFoundCallback ) { if (textFoundCallback == null) throw new ArgumentNullException("textFoundCallback"); if (macroFoundCallback == null) throw new ArgumentNullException("macroFoundCallback"); string elementText = text; var fieldResult = new StringBuilder(elementText); //NOTE: This is legacy code, this is definitely not the correct way to do a while loop! :) var stop = false; while (!stop) { var tagIndex = fieldResult.ToString().ToLower().IndexOf("<?umbraco"); if (tagIndex < 0) tagIndex = fieldResult.ToString().ToLower().IndexOf("<umbraco:macro"); if (tagIndex > -1) { var tempElementContent = ""; //text block found, call the call back method textFoundCallback(fieldResult.ToString().Substring(0, tagIndex)); fieldResult.Remove(0, tagIndex); var tag = fieldResult.ToString().Substring(0, fieldResult.ToString().IndexOf(">") + 1); var attributes = XmlHelper.GetAttributesFromElement(tag); // Check whether it's a single tag (<?.../>) or a tag with children (<?..>...</?...>) if (tag.Substring(tag.Length - 2, 1) != "/" && tag.IndexOf(" ") > -1) { String closingTag = "</" + (tag.Substring(1, tag.IndexOf(" ") - 1)) + ">"; // Tag with children are only used when a macro is inserted by the umbraco-editor, in the // following format: "<?UMBRACO_MACRO ...><IMG SRC="..."..></?UMBRACO_MACRO>", so we // need to delete extra information inserted which is the image-tag and the closing // umbraco_macro tag if (fieldResult.ToString().IndexOf(closingTag) > -1) { fieldResult.Remove(0, fieldResult.ToString().IndexOf(closingTag)); } } var macroAlias = attributes.ContainsKey("macroalias") ? attributes["macroalias"] : attributes["alias"]; //call the callback now that we have the macro parsed macroFoundCallback(macroAlias, attributes); fieldResult.Remove(0, fieldResult.ToString().IndexOf(">") + 1); fieldResult.Insert(0, tempElementContent); } else { //text block found, call the call back method textFoundCallback(fieldResult.ToString()); stop = true; //break; } } } } }
using System; using NUnit.Framework; using CS_threescale; using System.Collections; namespace CS_threescale_Test { [TestFixture] public class ApiTest { private IApi m_api; private readonly string backend = "http://su1.3scale.net:80"; private readonly string default_backend = "https://su1.3scale.net:443"; private readonly string provider_key = Environment.GetEnvironmentVariable ("DOTNET_PLUGIN_NUNIT_PROVIDER_KEY"); private readonly string app_key = Environment.GetEnvironmentVariable ("DOTNET_PLUGIN_NUNIT_APP_KEY"); private readonly string app_id = Environment.GetEnvironmentVariable ("DOTNET_PLUGIN_NUNIT_APP_ID"); private readonly string service_id = Environment.GetEnvironmentVariable ("DOTNET_PLUGIN_NUNIT_SERVICE_ID"); private readonly string service_token = Environment.GetEnvironmentVariable ("DOTNET_PLUGIN_NUNIT_SERVICE_TOKEN"); private readonly string invalid_provider_key = "InvalidProviderKey"; private readonly string invalid_app_id = "InvalidAppId"; private readonly string invalid_app_key = "InvalidAppKey"; private readonly string invalid_service_id = "InvalidServiceId"; [Test] public void TestDefaultHost () { m_api = new Api (); Assert.AreEqual (default_backend, m_api.HostURI); } [Test] public void TestCustomHost () { m_api = new Api ("example.com", provider_key); Assert.AreEqual ("example.com", m_api.HostURI); } #region Authrep tests [Test] public void TestAuthrepWithValidCredentials () { m_api = new Api (backend, provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); var response = m_api.authrep (parameters); Assert.IsTrue (response.authorized); } [Test] public void TestAuthRepWithServiceToken () { m_api = new Api (); //Hack to get around tls errors with Mono m_api.HostURI = backend; Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); parameters.Add ("service_token", service_token); var response = m_api.authrep (parameters); Assert.IsTrue (response.authorized); } [Test] public void TestAuthrepWithInvalidProviderKey () { m_api = new Api (backend, invalid_provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); var ex = Assert.Throws<ApiException> (() => m_api.authrep (parameters)); Assert.That (ex.Message, Is.EqualTo ("provider_key_invalid : provider key \"" + invalid_provider_key + "\" is invalid")); } [Test] public void TestAuthrepWithInvalidServiceId () { m_api = new Api (backend, provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", invalid_service_id); var ex = Assert.Throws<ApiException> (() => m_api.authrep (parameters)); Assert.That (ex.Message, Is.EqualTo ("service_id_invalid : service id \"" + invalid_service_id + "\" is invalid")); } [Test] public void TestAuthrepWithInvalidAppId () { m_api = new Api (backend, provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", "1a2b3c4d5e6f7a8b9c"); parameters.Add ("app_id", invalid_app_id); parameters.Add ("service_id", service_id); var ex = Assert.Throws<ApiException> (() => m_api.authrep (parameters)); Assert.That (ex.Message, Is.EqualTo ("application_not_found : application with id=\"" + invalid_app_id + "\" was not found")); } [Test] public void TestAuthrepWithInvalidAppKey () { m_api = new Api (backend, provider_key); var parameters = new Hashtable (); parameters.Add ("app_id", app_id); parameters.Add ("app_key", invalid_app_key); parameters.Add ("service_id", service_id); var resp = m_api.authrep (parameters); Assert.IsFalse (resp.authorized); Assert.AreEqual (resp.reason, "application key \"InvalidAppKey\" is invalid"); } [Test] public void TestAuthrepWithMissingAppKey () { m_api = new Api (backend, provider_key); var parameters = new Hashtable (); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); var resp = m_api.authrep (parameters); Assert.IsFalse (resp.authorized); Assert.AreEqual (resp.reason, "application key is missing"); } [Test] public void TestAuthRepWithInvalidMetric () { m_api = new Api (backend, provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); Hashtable metrics = new Hashtable (); metrics.Add ("invalid_metric", "1"); parameters.Add ("usage", metrics); var ex = Assert.Throws<ApiException> (() => m_api.authrep (parameters)); Assert.That (ex.Message, Is.EqualTo ("metric_invalid : metric \"invalid_metric\" is invalid")); } #endregion #region Authorize tests [Test] public void TestAuthorizeWithValidCredentials () { m_api = new Api (backend, provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); var response = m_api.authorize (parameters); Assert.IsTrue (response.authorized); } public void TestAuthorizeWithServiceToken () { m_api = new Api (); //Hack to get around tls errors with Mono m_api.HostURI = backend; Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); parameters.Add ("service_token", service_token); var response = m_api.authorize (parameters); Assert.IsTrue (response.authorized); } [Test] public void TestAuthorizeWithInvalidProviderKey () { m_api = new Api (backend, invalid_provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); var ex = Assert.Throws<ApiException> (() => m_api.authorize (parameters)); Assert.That (ex.Message, Is.EqualTo ("provider_key_invalid : provider key \"" + invalid_provider_key + "\" is invalid")); } [Test] public void TestAuthorizeWithInvalidServiceId () { m_api = new Api (backend, provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", invalid_service_id); var ex = Assert.Throws<ApiException> (() => m_api.authorize (parameters)); Assert.That (ex.Message, Is.EqualTo ("service_id_invalid : service id \"" + invalid_service_id + "\" is invalid")); } [Test] public void TestAuthorizeWithInvalidAppId () { m_api = new Api (backend, provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", "1a2b3c4d5e6f7a8b9c"); parameters.Add ("app_id", invalid_app_id); parameters.Add ("service_id", service_id); var ex = Assert.Throws<ApiException> (() => m_api.authorize (parameters)); Assert.That (ex.Message, Is.EqualTo ("application_not_found : application with id=\"" + invalid_app_id + "\" was not found")); } [Test] public void TestAuthorizeResponsePlan () { m_api = new Api (backend, provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); var resp = m_api.authorize (parameters); Assert.AreEqual ("Default", resp.plan); } [Test] public void TestAuthorizeResponseUsageReport () { m_api = new Api (backend, provider_key); Hashtable parameters = new Hashtable (); parameters.Add ("app_key", app_key); parameters.Add ("app_id", app_id); parameters.Add ("service_id", service_id); var response = m_api.authorize (parameters); var metric = ((UsageItem)response.usages [0]).metric; Assert.AreEqual ("hits", metric); } #endregion #region Report Test public void TestReportWithServiceToken () { m_api = new Api (); bool exception = false; //Hack to get around tls errors with Mono m_api.HostURI = backend; Hashtable transactions = new Hashtable (); Hashtable transaction = null; transaction = new Hashtable (); transaction.Add ("app_id", app_id); transaction.Add ("app_key", app_key); transaction.Add ("service_id", service_id); transaction.Add ("service_token", service_token); Hashtable usage = new Hashtable (); usage.Add ("hits", "1"); transaction.Add ("usage", usage); transactions.Add ("0", transaction); try { m_api.report (transactions); } catch (Exception) { exception = true; } Assert.False (exception); } [Test] public void TestReportWithInvalidProviderKey () { m_api = new Api (backend, invalid_provider_key); Hashtable transactions = new Hashtable (); Hashtable transaction = null; transaction = new Hashtable (); transaction.Add ("app_id", app_id); transaction.Add ("app_key", app_key); transaction.Add ("service_id", service_id); Hashtable usage = new Hashtable (); usage.Add ("hits", "1"); transaction.Add ("usage", usage); transactions.Add ("0", transaction); var ex = Assert.Throws<ApiException> (() => m_api.report (transactions)); Assert.That (ex.Message, Is.EqualTo ("provider_key_invalid : provider key \"" + invalid_provider_key + "\" is invalid")); } [Test] public void TestReportWithNoTransactions () { m_api = new Api (backend, provider_key); Hashtable transactions = new Hashtable (); var ex = Assert.Throws<ApiException> (() => m_api.report (transactions)); Assert.That (ex.Message, Is.EqualTo ("argument error: undefined transactions, must be at least one")); } [Test] public void TestReportWithEmptyTransaction () { m_api = new Api (backend, provider_key); Hashtable transactions = new Hashtable (); Hashtable transaction = new Hashtable (); transactions.Add ("0", transaction); var ex = Assert.Throws<ApiException> (() => m_api.report (transactions)); Assert.That (ex.Message, Is.EqualTo ("Bad request")); } [Test] public void TestReportWithNoUsage () { m_api = new Api (backend, provider_key); Hashtable transactions = new Hashtable (); Hashtable transaction = new Hashtable (); transaction.Add ("app_id", app_id); transaction.Add ("app_key", app_key); transaction.Add ("service_id", service_id); Hashtable usage = new Hashtable (); transaction.Add ("usage", usage); transactions.Add ("0", transaction); var ex = Assert.Throws<ApiException> (() => m_api.report (transactions)); Assert.That (ex.Message, Is.EqualTo ("argument error: undefined transaction, usage is missing in one record")); } #endregion } }
/* Copyright 2015 Arsene Tochemey GANDOTE 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; namespace BasicRestClient.RestClient { public class FileExtensionMimeTypeMapping { private static readonly Dictionary<string, string> MimeTypes = new Dictionary<string, string> { {".323", "text/h323"}, {".3g2", "video/3gpp2"}, {".3gp", "video/3gpp"}, {".3gp2", "video/3gpp2"}, {".3gpp", "video/3gpp"}, {".7z", "application/x-7z-compressed"}, {".aa", "audio/audible"}, {".AAC", "audio/aac"}, {".aaf", "application/octet-stream"}, {".aax", "audio/vnd.audible.aax"}, {".ac3", "audio/ac3"}, {".aca", "application/octet-stream"}, {".accda", "application/msaccess.addin"}, {".accdb", "application/msaccess"}, {".accdc", "application/msaccess.cab"}, {".accde", "application/msaccess"}, {".accdr", "application/msaccess.runtime"}, {".accdt", "application/msaccess"}, {".accdw", "application/msaccess.webapplication"}, {".accft", "application/msaccess.ftemplate"}, {".acx", "application/internet-property-stream"}, {".AddIn", "text/xml"}, {".ade", "application/msaccess"}, {".adobebridge", "application/x-bridge-url"}, {".adp", "application/msaccess"}, {".ADT", "audio/vnd.dlna.adts"}, {".ADTS", "audio/aac"}, {".afm", "application/octet-stream"}, {".ai", "application/postscript"}, {".aif", "audio/x-aiff"}, {".aifc", "audio/aiff"}, {".aiff", "audio/aiff"}, {".air", "application/vnd.adobe.air-application-installer-package+zip"}, {".amc", "application/x-mpeg"}, {".application", "application/x-ms-application"}, {".art", "image/x-jg"}, {".asa", "application/xml"}, {".asax", "application/xml"}, {".ascx", "application/xml"}, {".asd", "application/octet-stream"}, {".asf", "video/x-ms-asf"}, {".ashx", "application/xml"}, {".asi", "application/octet-stream"}, {".asm", "text/plain"}, {".asmx", "application/xml"}, {".aspx", "application/xml"}, {".asr", "video/x-ms-asf"}, {".asx", "video/x-ms-asf"}, {".atom", "application/atom+xml"}, {".au", "audio/basic"}, {".avi", "video/x-msvideo"}, {".axs", "application/olescript"}, {".bas", "text/plain"}, {".bcpio", "application/x-bcpio"}, {".bin", "application/octet-stream"}, {".bmp", "image/bmp"}, {".c", "text/plain"}, {".cab", "application/octet-stream"}, {".caf", "audio/x-caf"}, {".calx", "application/vnd.ms-office.calx"}, {".cat", "application/vnd.ms-pki.seccat"}, {".cc", "text/plain"}, {".cd", "text/plain"}, {".cdda", "audio/aiff"}, {".cdf", "application/x-cdf"}, {".cer", "application/x-x509-ca-cert"}, {".chm", "application/octet-stream"}, {".class", "application/x-java-applet"}, {".clp", "application/x-msclip"}, {".cmx", "image/x-cmx"}, {".cnf", "text/plain"}, {".cod", "image/cis-cod"}, {".config", "application/xml"}, {".contact", "text/x-ms-contact"}, {".coverage", "application/xml"}, {".cpio", "application/x-cpio"}, {".cpp", "text/plain"}, {".crd", "application/x-mscardfile"}, {".crl", "application/pkix-crl"}, {".crt", "application/x-x509-ca-cert"}, {".cs", "text/plain"}, {".csdproj", "text/plain"}, {".csh", "application/x-csh"}, {".csproj", "text/plain"}, {".css", "text/css"}, {".csv", "text/csv"}, {".cur", "application/octet-stream"}, {".cxx", "text/plain"}, {".dat", "application/octet-stream"}, {".datasource", "application/xml"}, {".dbproj", "text/plain"}, {".dcr", "application/x-director"}, {".def", "text/plain"}, {".deploy", "application/octet-stream"}, {".der", "application/x-x509-ca-cert"}, {".dgml", "application/xml"}, {".dib", "image/bmp"}, {".dif", "video/x-dv"}, {".dir", "application/x-director"}, {".disco", "text/xml"}, {".dll", "application/x-msdownload"}, {".dll.config", "text/xml"}, {".dlm", "text/dlm"}, {".doc", "application/msword"}, {".docm", "application/vnd.ms-word.document.macroEnabled.12"}, {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {".dot", "application/msword"}, {".dotm", "application/vnd.ms-word.template.macroEnabled.12"}, {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"}, {".dsp", "application/octet-stream"}, {".dsw", "text/plain"}, {".dtd", "text/xml"}, {".dtsConfig", "text/xml"}, {".dv", "video/x-dv"}, {".dvi", "application/x-dvi"}, {".dwf", "drawing/x-dwf"}, {".dwp", "application/octet-stream"}, {".dxr", "application/x-director"}, {".eml", "message/rfc822"}, {".emz", "application/octet-stream"}, {".eot", "application/octet-stream"}, {".eps", "application/postscript"}, {".etl", "application/etl"}, {".etx", "text/x-setext"}, {".evy", "application/envoy"}, {".exe", "application/octet-stream"}, {".exe.config", "text/xml"}, {".fdf", "application/vnd.fdf"}, {".fif", "application/fractals"}, {".filters", "Application/xml"}, {".fla", "application/octet-stream"}, {".flr", "x-world/x-vrml"}, {".flv", "video/x-flv"}, {".fsscript", "application/fsharp-script"}, {".fsx", "application/fsharp-script"}, {".generictest", "application/xml"}, {".gif", "image/gif"}, {".group", "text/x-ms-group"}, {".gsm", "audio/x-gsm"}, {".gtar", "application/x-gtar"}, {".gz", "application/x-gzip"}, {".h", "text/plain"}, {".hdf", "application/x-hdf"}, {".hdml", "text/x-hdml"}, {".hhc", "application/x-oleobject"}, {".hhk", "application/octet-stream"}, {".hhp", "application/octet-stream"}, {".hlp", "application/winhlp"}, {".hpp", "text/plain"}, {".hqx", "application/mac-binhex40"}, {".hta", "application/hta"}, {".htc", "text/x-component"}, {".htm", "text/html"}, {".html", "text/html"}, {".htt", "text/webviewhtml"}, {".hxa", "application/xml"}, {".hxc", "application/xml"}, {".hxd", "application/octet-stream"}, {".hxe", "application/xml"}, {".hxf", "application/xml"}, {".hxh", "application/octet-stream"}, {".hxi", "application/octet-stream"}, {".hxk", "application/xml"}, {".hxq", "application/octet-stream"}, {".hxr", "application/octet-stream"}, {".hxs", "application/octet-stream"}, {".hxt", "text/html"}, {".hxv", "application/xml"}, {".hxw", "application/octet-stream"}, {".hxx", "text/plain"}, {".i", "text/plain"}, {".ico", "image/x-icon"}, {".ics", "application/octet-stream"}, {".idl", "text/plain"}, {".ief", "image/ief"}, {".iii", "application/x-iphone"}, {".inc", "text/plain"}, {".inf", "application/octet-stream"}, {".inl", "text/plain"}, {".ins", "application/x-internet-signup"}, {".ipa", "application/x-itunes-ipa"}, {".ipg", "application/x-itunes-ipg"}, {".ipproj", "text/plain"}, {".ipsw", "application/x-itunes-ipsw"}, {".iqy", "text/x-ms-iqy"}, {".isp", "application/x-internet-signup"}, {".ite", "application/x-itunes-ite"}, {".itlp", "application/x-itunes-itlp"}, {".itms", "application/x-itunes-itms"}, {".itpc", "application/x-itunes-itpc"}, {".IVF", "video/x-ivf"}, {".jar", "application/java-archive"}, {".java", "application/octet-stream"}, {".jck", "application/liquidmotion"}, {".jcz", "application/liquidmotion"}, {".jfif", "image/pjpeg"}, {".jnlp", "application/x-java-jnlp-file"}, {".jpb", "application/octet-stream"}, {".jpe", "image/jpeg"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".js", "application/x-javascript"}, {".jsx", "text/jscript"}, {".jsxbin", "text/plain"}, {".latex", "application/x-latex"}, {".library-ms", "application/windows-library+xml"}, {".lit", "application/x-ms-reader"}, {".loadtest", "application/xml"}, {".lpk", "application/octet-stream"}, {".lsf", "video/x-la-asf"}, {".lst", "text/plain"}, {".lsx", "video/x-la-asf"}, {".lzh", "application/octet-stream"}, {".m13", "application/x-msmediaview"}, {".m14", "application/x-msmediaview"}, {".m1v", "video/mpeg"}, {".m2t", "video/vnd.dlna.mpeg-tts"}, {".m2ts", "video/vnd.dlna.mpeg-tts"}, {".m2v", "video/mpeg"}, {".m3u", "audio/x-mpegurl"}, {".m3u8", "audio/x-mpegurl"}, {".m4a", "audio/m4a"}, {".m4b", "audio/m4b"}, {".m4p", "audio/m4p"}, {".m4r", "audio/x-m4r"}, {".m4v", "video/x-m4v"}, {".mac", "image/x-macpaint"}, {".mak", "text/plain"}, {".man", "application/x-troff-man"}, {".manifest", "application/x-ms-manifest"}, {".map", "text/plain"}, {".master", "application/xml"}, {".mda", "application/msaccess"}, {".mdb", "application/x-msaccess"}, {".mde", "application/msaccess"}, {".mdp", "application/octet-stream"}, {".me", "application/x-troff-me"}, {".mfp", "application/x-shockwave-flash"}, {".mht", "message/rfc822"}, {".mhtml", "message/rfc822"}, {".mid", "audio/mid"}, {".midi", "audio/mid"}, {".mix", "application/octet-stream"}, {".mk", "text/plain"}, {".mmf", "application/x-smaf"}, {".mno", "text/xml"}, {".mny", "application/x-msmoney"}, {".mod", "video/mpeg"}, {".mov", "video/quicktime"}, {".movie", "video/x-sgi-movie"}, {".mp2", "video/mpeg"}, {".mp2v", "video/mpeg"}, {".mp3", "audio/mpeg"}, {".mp4", "video/mp4"}, {".mp4v", "video/mp4"}, {".mpa", "video/mpeg"}, {".mpe", "video/mpeg"}, {".mpeg", "video/mpeg"}, {".mpf", "application/vnd.ms-mediapackage"}, {".mpg", "video/mpeg"}, {".mpp", "application/vnd.ms-project"}, {".mpv2", "video/mpeg"}, {".mqv", "video/quicktime"}, {".ms", "application/x-troff-ms"}, {".msi", "application/octet-stream"}, {".mso", "application/octet-stream"}, {".mts", "video/vnd.dlna.mpeg-tts"}, {".mtx", "application/xml"}, {".mvb", "application/x-msmediaview"}, {".mvc", "application/x-miva-compiled"}, {".mxp", "application/x-mmxp"}, {".nc", "application/x-netcdf"}, {".nsc", "video/x-ms-asf"}, {".nws", "message/rfc822"}, {".ocx", "application/octet-stream"}, {".oda", "application/oda"}, {".odc", "text/x-ms-odc"}, {".odh", "text/plain"}, {".odl", "text/plain"}, {".odp", "application/vnd.oasis.opendocument.presentation"}, {".ods", "application/oleobject"}, {".odt", "application/vnd.oasis.opendocument.text"}, {".one", "application/onenote"}, {".onea", "application/onenote"}, {".onepkg", "application/onenote"}, {".onetmp", "application/onenote"}, {".onetoc", "application/onenote"}, {".onetoc2", "application/onenote"}, {".orderedtest", "application/xml"}, {".osdx", "application/opensearchdescription+xml"}, {".p10", "application/pkcs10"}, {".p12", "application/x-pkcs12"}, {".p7b", "application/x-pkcs7-certificates"}, {".p7c", "application/pkcs7-mime"}, {".p7m", "application/pkcs7-mime"}, {".p7r", "application/x-pkcs7-certreqresp"}, {".p7s", "application/pkcs7-signature"}, {".pbm", "image/x-portable-bitmap"}, {".pcast", "application/x-podcast"}, {".pct", "image/pict"}, {".pcx", "application/octet-stream"}, {".pcz", "application/octet-stream"}, {".pdf", "application/pdf"}, {".pfb", "application/octet-stream"}, {".pfm", "application/octet-stream"}, {".pfx", "application/x-pkcs12"}, {".pgm", "image/x-portable-graymap"}, {".pic", "image/pict"}, {".pict", "image/pict"}, {".pkgdef", "text/plain"}, {".pkgundef", "text/plain"}, {".pko", "application/vnd.ms-pki.pko"}, {".pls", "audio/scpls"}, {".pma", "application/x-perfmon"}, {".pmc", "application/x-perfmon"}, {".pml", "application/x-perfmon"}, {".pmr", "application/x-perfmon"}, {".pmw", "application/x-perfmon"}, {".png", "image/png"}, {".pnm", "image/x-portable-anymap"}, {".pnt", "image/x-macpaint"}, {".pntg", "image/x-macpaint"}, {".pnz", "image/png"}, {".pot", "application/vnd.ms-powerpoint"}, {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"}, {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"}, {".ppa", "application/vnd.ms-powerpoint"}, {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"}, {".ppm", "image/x-portable-pixmap"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"}, {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"}, {".ppt", "application/vnd.ms-powerpoint"}, {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"}, {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, {".prf", "application/pics-rules"}, {".prm", "application/octet-stream"}, {".prx", "application/octet-stream"}, {".ps", "application/postscript"}, {".psc1", "application/PowerShell"}, {".psd", "application/octet-stream"}, {".psess", "application/xml"}, {".psm", "application/octet-stream"}, {".psp", "application/octet-stream"}, {".pub", "application/x-mspublisher"}, {".pwz", "application/vnd.ms-powerpoint"}, {".qht", "text/x-html-insertion"}, {".qhtm", "text/x-html-insertion"}, {".qt", "video/quicktime"}, {".qti", "image/x-quicktime"}, {".qtif", "image/x-quicktime"}, {".qtl", "application/x-quicktimeplayer"}, {".qxd", "application/octet-stream"}, {".ra", "audio/x-pn-realaudio"}, {".ram", "audio/x-pn-realaudio"}, {".rar", "application/octet-stream"}, {".ras", "image/x-cmu-raster"}, {".rat", "application/rat-file"}, {".rc", "text/plain"}, {".rc2", "text/plain"}, {".rct", "text/plain"}, {".rdlc", "application/xml"}, {".resx", "application/xml"}, {".rf", "image/vnd.rn-realflash"}, {".rgb", "image/x-rgb"}, {".rgs", "text/plain"}, {".rm", "application/vnd.rn-realmedia"}, {".rmi", "audio/mid"}, {".rmp", "application/vnd.rn-rn_music_package"}, {".roff", "application/x-troff"}, {".rpm", "audio/x-pn-realaudio-plugin"}, {".rqy", "text/x-ms-rqy"}, {".rtf", "application/rtf"}, {".rtx", "text/richtext"}, {".ruleset", "application/xml"}, {".s", "text/plain"}, {".safariextz", "application/x-safari-safariextz"}, {".scd", "application/x-msschedule"}, {".sct", "text/scriptlet"}, {".sd2", "audio/x-sd2"}, {".sdp", "application/sdp"}, {".sea", "application/octet-stream"}, {".searchConnector-ms", "application/windows-search-connector+xml"}, {".setpay", "application/set-payment-initiation"}, {".setreg", "application/set-registration-initiation"}, {".settings", "application/xml"}, {".sgimb", "application/x-sgimb"}, {".sgml", "text/sgml"}, {".sh", "application/x-sh"}, {".shar", "application/x-shar"}, {".shtml", "text/html"}, {".sit", "application/x-stuffit"}, {".sitemap", "application/xml"}, {".skin", "application/xml"}, {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"}, {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"}, {".slk", "application/vnd.ms-excel"}, {".sln", "text/plain"}, {".slupkg-ms", "application/x-ms-license"}, {".smd", "audio/x-smd"}, {".smi", "application/octet-stream"}, {".smx", "audio/x-smd"}, {".smz", "audio/x-smd"}, {".snd", "audio/basic"}, {".snippet", "application/xml"}, {".snp", "application/octet-stream"}, {".sol", "text/plain"}, {".sor", "text/plain"}, {".spc", "application/x-pkcs7-certificates"}, {".spl", "application/futuresplash"}, {".src", "application/x-wais-source"}, {".srf", "text/plain"}, {".SSISDeploymentManifest", "text/xml"}, {".ssm", "application/streamingmedia"}, {".sst", "application/vnd.ms-pki.certstore"}, {".stl", "application/vnd.ms-pki.stl"}, {".sv4cpio", "application/x-sv4cpio"}, {".sv4crc", "application/x-sv4crc"}, {".svc", "application/xml"}, {".swf", "application/x-shockwave-flash"}, {".t", "application/x-troff"}, {".tar", "application/x-tar"}, {".tcl", "application/x-tcl"}, {".testrunconfig", "application/xml"}, {".testsettings", "application/xml"}, {".tex", "application/x-tex"}, {".texi", "application/x-texinfo"}, {".texinfo", "application/x-texinfo"}, {".tgz", "application/x-compressed"}, {".thmx", "application/vnd.ms-officetheme"}, {".thn", "application/octet-stream"}, {".tif", "image/tiff"}, {".tiff", "image/tiff"}, {".tlh", "text/plain"}, {".tli", "text/plain"}, {".toc", "application/octet-stream"}, {".tr", "application/x-troff"}, {".trm", "application/x-msterminal"}, {".trx", "application/xml"}, {".ts", "video/vnd.dlna.mpeg-tts"}, {".tsv", "text/tab-separated-values"}, {".ttf", "application/octet-stream"}, {".tts", "video/vnd.dlna.mpeg-tts"}, {".txt", "text/plain"}, {".u32", "application/octet-stream"}, {".uls", "text/iuls"}, {".user", "text/plain"}, {".ustar", "application/x-ustar"}, {".vb", "text/plain"}, {".vbdproj", "text/plain"}, {".vbk", "video/mpeg"}, {".vbproj", "text/plain"}, {".vbs", "text/vbscript"}, {".vcf", "text/x-vcard"}, {".vcproj", "Application/xml"}, {".vcs", "text/plain"}, {".vcxproj", "Application/xml"}, {".vddproj", "text/plain"}, {".vdp", "text/plain"}, {".vdproj", "text/plain"}, {".vdx", "application/vnd.ms-visio.viewer"}, {".vml", "text/xml"}, {".vscontent", "application/xml"}, {".vsct", "text/xml"}, {".vsd", "application/vnd.visio"}, {".vsi", "application/ms-vsi"}, {".vsix", "application/vsix"}, {".vsixlangpack", "text/xml"}, {".vsixmanifest", "text/xml"}, {".vsmdi", "application/xml"}, {".vspscc", "text/plain"}, {".vss", "application/vnd.visio"}, {".vsscc", "text/plain"}, {".vssettings", "text/xml"}, {".vssscc", "text/plain"}, {".vst", "application/vnd.visio"}, {".vstemplate", "text/xml"}, {".vsto", "application/x-ms-vsto"}, {".vsw", "application/vnd.visio"}, {".vsx", "application/vnd.visio"}, {".vtx", "application/vnd.visio"}, {".wav", "audio/wav"}, {".wave", "audio/wav"}, {".wax", "audio/x-ms-wax"}, {".wbk", "application/msword"}, {".wbmp", "image/vnd.wap.wbmp"}, {".wcm", "application/vnd.ms-works"}, {".wdb", "application/vnd.ms-works"}, {".wdp", "image/vnd.ms-photo"}, {".webarchive", "application/x-safari-webarchive"}, {".webtest", "application/xml"}, {".wiq", "application/xml"}, {".wiz", "application/msword"}, {".wks", "application/vnd.ms-works"}, {".WLMP", "application/wlmoviemaker"}, {".wlpginstall", "application/x-wlpg-detect"}, {".wlpginstall3", "application/x-wlpg3-detect"}, {".wm", "video/x-ms-wm"}, {".wma", "audio/x-ms-wma"}, {".wmd", "application/x-ms-wmd"}, {".wmf", "application/x-msmetafile"}, {".wml", "text/vnd.wap.wml"}, {".wmlc", "application/vnd.wap.wmlc"}, {".wmls", "text/vnd.wap.wmlscript"}, {".wmlsc", "application/vnd.wap.wmlscriptc"}, {".wmp", "video/x-ms-wmp"}, {".wmv", "video/x-ms-wmv"}, {".wmx", "video/x-ms-wmx"}, {".wmz", "application/x-ms-wmz"}, {".wpl", "application/vnd.ms-wpl"}, {".wps", "application/vnd.ms-works"}, {".wri", "application/x-mswrite"}, {".wrl", "x-world/x-vrml"}, {".wrz", "x-world/x-vrml"}, {".wsc", "text/scriptlet"}, {".wsdl", "text/xml"}, {".wvx", "video/x-ms-wvx"}, {".x", "application/directx"}, {".xaf", "x-world/x-vrml"}, {".xaml", "application/xaml+xml"}, {".xap", "application/x-silverlight-app"}, {".xbap", "application/x-ms-xbap"}, {".xbm", "image/x-xbitmap"}, {".xdr", "text/plain"}, {".xht", "application/xhtml+xml"}, {".xhtml", "application/xhtml+xml"}, {".xla", "application/vnd.ms-excel"}, {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"}, {".xlc", "application/vnd.ms-excel"}, {".xld", "application/vnd.ms-excel"}, {".xlk", "application/vnd.ms-excel"}, {".xll", "application/vnd.ms-excel"}, {".xlm", "application/vnd.ms-excel"}, {".xls", "application/vnd.ms-excel"}, {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"}, {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"}, {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {".xlt", "application/vnd.ms-excel"}, {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"}, {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"}, {".xlw", "application/vnd.ms-excel"}, {".xml", "text/xml"}, {".xmta", "application/xml"}, {".xof", "x-world/x-vrml"}, {".XOML", "text/plain"}, {".xpm", "image/x-xpixmap"}, {".xps", "application/vnd.ms-xpsdocument"}, {".xrm-ms", "text/xml"}, {".xsc", "application/xml"}, {".xsd", "text/xml"}, {".xsf", "text/xml"}, {".xsl", "text/xml"}, {".xslt", "text/xml"}, {".xsn", "application/octet-stream"}, {".xss", "application/xml"}, {".xtp", "application/octet-stream"}, {".xwd", "image/x-xwindowdump"}, {".z", "application/x-compress"}, {".zip", "application/x-zip-compressed"} }; public static string GetMimeType(string extension) { if (extension == null) throw new ArgumentNullException("extension"); if (!extension.StartsWith(".")) extension = "." + extension; string mime; return MimeTypes.TryGetValue(extension, out mime) ? mime : "application/octet-stream"; } } }
using System.Drawing; using System.Web.UI.WebControls; namespace Rainbow.Framework.Web.UI.WebControls { /// <summary> /// Power Grid /// </summary> public class PowerGrid : DataGrid { /// <summary> /// /// </summary> protected Label lblFooter; private string m_PagerCurrentPageCssClass = string.Empty; private string m_PagerOtherPageCssClass = string.Empty; #region Public Properties /// <summary> /// Gets or sets the sort expression. /// </summary> /// <value>The sort expression.</value> public string SortExpression { get { return base.Attributes["SortExpression"]; } set { base.Attributes["SortExpression"] = value; } } /// <summary> /// Gets or sets a value indicating whether this instance is sorted ascending. /// </summary> /// <value> /// <c>true</c> if this instance is sorted ascending; otherwise, <c>false</c>. /// </value> public bool IsSortedAscending { get { return base.Attributes["SortedAscending"].Equals("yes"); } set { if (!value) { base.Attributes["SortedAscending"] = "no"; return; } base.Attributes["SortedAscending"] = "yes"; } } /// <summary> /// Gets or sets the pager current page CSS class. /// </summary> /// <value>The pager current page CSS class.</value> public string PagerCurrentPageCssClass { get { return m_PagerCurrentPageCssClass; } set { m_PagerCurrentPageCssClass = value; } } /// <summary> /// Gets or sets the pager other page CSS class. /// </summary> /// <value>The pager other page CSS class.</value> public string PagerOtherPageCssClass { get { return m_PagerOtherPageCssClass; } set { m_PagerOtherPageCssClass = value; } } /// <summary> /// Gets or sets the footer text. /// </summary> /// <value>The footer text.</value> public string FooterText { get { return lblFooter.Text; } set { lblFooter.Text = value; } } #endregion /// <summary> /// Initializes a new instance of the <see cref="PowerGrid"/> class. /// </summary> public PowerGrid() { lblFooter = new Label(); PagerStyle.Mode = PagerMode.NumericPages; PagerStyle.BackColor = Color.Gainsboro; PagerStyle.PageButtonCount = 10; PagerStyle.HorizontalAlign = HorizontalAlign.Center; FooterStyle.BackColor = Color.Gainsboro; FooterStyle.HorizontalAlign = HorizontalAlign.Center; ShowFooter = true; AutoGenerateColumns = false; AllowPaging = true; PageSize = 7; CellSpacing = 2; CellPadding = 2; GridLines = GridLines.None; BorderColor = Color.Black; BorderStyle = BorderStyle.Solid; BorderWidth = 1; ForeColor = Color.Black; Font.Size = FontUnit.XXSmall; Font.Name = "Verdana"; ItemStyle.BackColor = Color.Beige; AlternatingItemStyle.BackColor = Color.PaleGoldenrod; HeaderStyle.Font.Bold = true; HeaderStyle.BackColor = Color.Brown; HeaderStyle.ForeColor = Color.White; HeaderStyle.HorizontalAlign = HorizontalAlign.Center; AllowSorting = true; Attributes["SortedAscending"] = "yes"; ItemCreated += new DataGridItemEventHandler(OnItemCreated); SortCommand += new DataGridSortCommandEventHandler(OnSortCommand); PageIndexChanged += new DataGridPageChangedEventHandler(OnPageIndexChanged); } /// <summary> /// Called when [item created]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.DataGridItemEventArgs"/> instance containing the event data.</param> public void OnItemCreated(object sender, DataGridItemEventArgs e) { ListItemType listItemType = e.Item.ItemType; if (listItemType == ListItemType.Footer) { int i1 = e.Item.Cells.Count; for (int j = i1 - 1; j > 0; j--) { e.Item.Cells.RemoveAt(j); } e.Item.Cells[0].ColumnSpan = i1; e.Item.Cells[0].Controls.Add(lblFooter); } if (listItemType == ListItemType.Pager) { TableCell tableCell1 = (TableCell) e.Item.Controls[0]; for (int k = 0; k < tableCell1.Controls.Count; k += 2) { try { LinkButton linkButton = (LinkButton) tableCell1.Controls[k]; linkButton.Text = string.Concat("[ ", linkButton.Text, " ]"); linkButton.CssClass = m_PagerOtherPageCssClass; } catch { Label label1 = (Label) tableCell1.Controls[k]; label1.Text = string.Concat("Page ", label1.Text); if (m_PagerCurrentPageCssClass.Equals(string.Empty)) { label1.ForeColor = Color.Blue; label1.Font.Bold = true; } else { label1.CssClass = m_PagerCurrentPageCssClass; } } } } //if (listItemType == ListItemType.Item) if (listItemType == ListItemType.Header) { string str1 = base.Attributes["SortExpression"]; string str2 = !base.Attributes["SortedAscending"].Equals("yes") ? " 6" : " 5"; for (int i2 = 0; i2 < base.Columns.Count; i2++) { if (str1 == base.Columns[i2].SortExpression) { TableCell tableCell2 = e.Item.Cells[i2]; Label label2 = new Label(); label2.Font.Name = "webdings"; label2.Font.Size = FontUnit.XXSmall; label2.Text = str2; tableCell2.Controls.Add(label2); } } } } /// <summary> /// Called when [sort command]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.DataGridSortCommandEventArgs"/> instance containing the event data.</param> public void OnSortCommand(object sender, DataGridSortCommandEventArgs e) { string _SortExpression; string _SortedAscending; _SortExpression = Attributes["SortExpression"]; _SortedAscending = Attributes["SortedAscending"]; Attributes["SortExpression"] = e.SortExpression; Attributes["SortedAscending"] = "yes"; if (e.SortExpression == _SortExpression) { if (_SortedAscending == "yes") Attributes["SortedAscending"] = "no"; } } /// <summary> /// Called when [page index changed]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.DataGridPageChangedEventArgs"/> instance containing the event data.</param> public void OnPageIndexChanged(object sender, DataGridPageChangedEventArgs e) { CurrentPageIndex = e.NewPageIndex; } /// <summary> /// Sets the GFW styles. /// </summary> public void SetGfwStyles() { CellPadding = 3; CellSpacing = 0; BorderColor = Color.Black; BackColor = Color.WhiteSmoke; ForeColor = Color.Black; GridLines = GridLines.Both; ItemStyle.BackColor = Color.WhiteSmoke; ItemStyle.VerticalAlign = VerticalAlign.Top; AlternatingItemStyle.BackColor = Color.LightGray; AlternatingItemStyle.VerticalAlign = VerticalAlign.Top; HeaderStyle.ForeColor = Color.Black; HeaderStyle.Font.Bold = true; HeaderStyle.BackColor = Color.LightGray; } } }
// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. using System; using System.Collections; using System.Net; using System.Text; using System.Web; using System.IO; namespace com.CastRoller.AmazonS3DA { /// An interface into the S3 system. It is initially configured with /// authentication and connection parameters and exposes methods to access and /// manipulate S3 data. public class AWSAuthConnection { private string awsAccessKeyId; private string awsSecretAccessKey; private bool isSecure; private string server; private int port; public AWSAuthConnection( string awsAccessKeyId, string awsSecretAccessKey ): this( awsAccessKeyId, awsSecretAccessKey, true ) { } public AWSAuthConnection( string awsAccessKeyId, string awsSecretAccessKey, bool isSecure ): this( awsAccessKeyId, awsSecretAccessKey, isSecure, Utils.Host ) { } public AWSAuthConnection( string awsAccessKeyId, string awsSecretAccessKey, bool isSecure, string server ) : this( awsAccessKeyId, awsSecretAccessKey, isSecure, server, isSecure ? Utils.SecurePort : Utils.InsecurePort ) { } public AWSAuthConnection( string awsAccessKeyId, string awsSecretAccessKey, bool isSecure, string server, int port ) { this.awsAccessKeyId = awsAccessKeyId; this.awsSecretAccessKey = awsSecretAccessKey; this.isSecure = isSecure; this.server = server; this.port = port; } /// <summary> /// Creates a new bucket. /// </summary> /// <param name="bucket">The name of the bucket to create</param> /// <param name="headers">A Map of string to string representing the headers to pass (can be null)</param> public Response createBucket( string bucket, SortedList headers ) { S3Object obj = new S3Object("", null); WebRequest request = makeRequest("PUT", bucket, headers, obj); request.ContentLength = 0; request.GetRequestStream().Close(); return new Response(request); } /// <summary> /// Lists the contents of a bucket. /// </summary> /// <param name="bucket">The name of the bucket to list</param> /// <param name="prefix">All returned keys will start with this string (can be null)</param> /// <param name="marker">All returned keys will be lexographically greater than this string (can be null)</param> /// <param name="maxKeys">The maximum number of keys to return (can be 0)</param> /// <param name="headers">A Map of string to string representing HTTP headers to pass.</param> public ListBucketResponse listBucket( string bucket, string prefix, string marker, int maxKeys, SortedList headers ) { return listBucket( bucket, prefix, marker, maxKeys, null, headers ); } /// <summary> /// Lists the contents of a bucket. /// </summary> /// <param name="bucket">The name of the bucket to list</param> /// <param name="prefix">All returned keys will start with this string (can be null)</param> /// <param name="marker">All returned keys will be lexographically greater than this string (can be null)</param> /// <param name="maxKeys">The maximum number of keys to return (can be 0)</param> /// <param name="headers">A Map of string to string representing HTTP headers to pass.</param> /// <param name="delimiter">Keys that contain a string between the prefix and the first /// occurrence of the delimiter will be rolled up into a single element.</param> public ListBucketResponse listBucket( string bucket, string prefix, string marker, int maxKeys, string delimiter, SortedList headers ) { StringBuilder path = new StringBuilder( bucket ); path.Append( "?" ); if (prefix != null) path.Append("prefix=").Append(HttpUtility.UrlEncode(prefix)).Append("&"); if ( marker != null ) path.Append( "marker=" ).Append(HttpUtility.UrlEncode(marker)).Append( "&" ); if ( maxKeys != 0 ) path.Append( "max-keys=" ).Append(maxKeys).Append( "&" ); if (delimiter != null) path.Append("delimiter=").Append(HttpUtility.UrlEncode(delimiter)).Append("&"); // we've always added exactly one too many chars. path.Remove( path.Length - 1, 1 ); return new ListBucketResponse( makeRequest( "GET", path.ToString(), headers ) ); } /// <summary> /// Deletes an empty Bucket. /// </summary> /// <param name="bucket">The name of the bucket to delete</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> /// <returns></returns> public Response deleteBucket( string bucket, SortedList headers ) { return new Response( makeRequest( "DELETE", bucket, headers ) ); } /// <summary> /// Writes an object to S3. /// </summary> /// <param name="bucket">The name of the bucket to which the object will be added.</param> /// <param name="key">The name of the key to use</param> /// <param name="obj">An S3Object containing the data to write.</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> public Response put( string bucket, string key, S3Object obj, SortedList headers ) { WebRequest request = makeRequest("PUT", bucket + "/" + encodeKeyForSignature(key), headers, obj); request.ContentLength = obj.Bytes.Length; request.GetRequestStream().Write(obj.Bytes, 0, obj.Bytes.Length); request.GetRequestStream().Close(); return new Response( request ); } /// <summary> /// Writes an object to S3 using streaming. /// </summary> /// <param name="bucket">The name of the bucket to which the object will be added.</param> /// <param name="key">The name of the key to use</param> /// <param name="obj">An S3Object containing the data to write.</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> public Response putStream(string bucket, string key, S3StreamObject obj, SortedList headers) { Boolean isEmptyKey = (key == null) || (key.Length == 0) || (key.Trim().Length == 0); string pathSep = isEmptyKey ? "" : "/"; if (key == null) key = ""; /*WebRequest request = makeStreamRequest("PUT", bucket + pathSep + HttpUtility.UrlEncode(key), headers, obj); */ WebRequest request = makeStreamRequest("PUT", bucket + pathSep + key, headers, obj); // cast WebRequest to a HttpWebRequest to allow for direct streaming of data HttpWebRequest hwr = (HttpWebRequest) request; hwr.AllowWriteStreamBuffering = false; hwr.SendChunked = false; hwr.ContentLength = obj.Stream.Length; ASCIIEncoding encoding = new ASCIIEncoding(); byte[] buf = new byte[1024]; BufferedStream bufferedInput = new BufferedStream(obj.Stream); int contentLength = 0; int bytesRead = 0; while ((bytesRead = bufferedInput.Read(buf, 0, 1024)) > 0) { contentLength += bytesRead; hwr.GetRequestStream().Write( buf, 0, bytesRead ); } hwr.GetRequestStream().Close(); return new Response( request ); } /// <summary> /// Make a new WebRequest /// </summary> /// <param name="method">The HTTP method to use (GET, PUT, DELETE)</param> /// <param name="resource">The resource name (bucket + "/" + key)</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> /// <param name="obj">S3StreamObject that is to be written (can be null).</param> private WebRequest makeStreamRequest( string method, string resource, SortedList headers, S3StreamObject obj ) { string url = makeURL( resource ); WebRequest req = WebRequest.Create( url ); req.Timeout = 3600000; // 1 hr req.Method = method; addHeaders( req, headers ); if ( obj != null ) addMetadataHeaders( req, obj.Metadata ); addAuthHeader( req, resource ); return req; } // NOTE: The Syste.Net.Uri class does modifications to the URL. // For example, if you have two consecutive slashes, it will // convert these to a single slash. This could lead to invalid // signatures as best and at worst keys with names you do not // care for. private static string encodeKeyForSignature(string key) { string output = HttpUtility.UrlEncode(key).Replace("%2f", "/"); return key; } /// <summary> /// Reads an object from S3 /// </summary> /// <param name="bucket">The name of the bucket where the object lives</param> /// <param name="key">The name of the key to use</param> /// <param name="headers">A Map of string to string representing the HTTP headers to pass (can be null)</param> public GetResponse get( string bucket, string key, SortedList headers ) { return new GetResponse(makeRequest("GET", bucket + "/" + encodeKeyForSignature(key), headers)); } /// <summary> /// Delete an object from S3. /// </summary> /// <param name="bucket">The name of the bucket where the object lives.</param> /// <param name="key">The name of the key to use.</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> /// <returns></returns> public Response delete( string bucket, string key, SortedList headers ) { return new Response(makeRequest("DELETE", bucket + "/" + encodeKeyForSignature(key), headers)); } /// <summary> /// Get the logging xml document for a given bucket /// </summary> /// <param name="bucket">The name of the bucket</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> public GetResponse getBucketLogging(string bucket, SortedList headers) { return new GetResponse(makeRequest("GET", bucket + "?logging", headers)); } /// <summary> /// Write a new logging xml document for a given bucket /// </summary> /// <param name="bucket">The name of the bucket to enable/disable logging on</param> /// <param name="loggingXMLDoc">The xml representation of the logging configuration as a String.</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> public Response putBucketLogging(string bucket, string loggingXMLDoc, SortedList headers) { S3Object obj = new S3Object(loggingXMLDoc, null); WebRequest request = makeRequest("PUT", bucket + "?logging", headers, obj); request.ContentLength = loggingXMLDoc.Length; request.GetRequestStream().Write(obj.Bytes, 0, obj.Bytes.Length); request.GetRequestStream().Close(); return new Response(request); } /// <summary> /// Get the ACL for a given bucket. /// </summary> /// <param name="bucket">The the bucket to get the ACL from.</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> public GetResponse getBucketACL(string bucket, SortedList headers) { return getACL(bucket, null, headers); } /// <summary> /// Get the ACL for a given object /// </summary> /// <param name="bucket">The name of the bucket where the object lives</param> /// <param name="key">The name of the key to use.</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> public GetResponse getACL( string bucket, string key, SortedList headers ) { if ( key == null ) key = ""; return new GetResponse(makeRequest("GET", bucket + "/" + encodeKeyForSignature(key) + "?acl", headers)); } /// <summary> /// Write a new ACL for a given bucket /// </summary> /// <param name="bucket">The name of the bucket to change the ACL.</param> /// <param name="aclXMLDoc">An XML representation of the ACL as a string.</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> public Response putBucketACL(string bucket, string aclXMLDoc, SortedList headers) { return putACL(bucket, null, aclXMLDoc, headers); } /// <summary> /// Write a new ACL for a given object /// </summary> /// <param name="bucket">The name of the bucket where the object lives or the /// name of the bucket to change the ACL if key is null.</param> /// <param name="key">The name of the key to use; can be null.</param> /// <param name="aclXMLDoc">An XML representation of the ACL as a string.</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> public Response putACL(string bucket, string key, string aclXMLDoc, SortedList headers) { S3Object obj = new S3Object( aclXMLDoc, null ); if ( key == null ) key = ""; WebRequest request = makeRequest("PUT", bucket + "/" + encodeKeyForSignature(key) + "?acl", headers, obj); request.ContentLength = aclXMLDoc.Length; request.GetRequestStream().Write(obj.Bytes, 0, obj.Bytes.Length); request.GetRequestStream().Close(); return new Response(request); } /// <summary> /// List all the buckets created by this account. /// </summary> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> public ListAllMyBucketsResponse listAllMyBuckets( SortedList headers ) { return new ListAllMyBucketsResponse(makeRequest("GET", "", headers)); } /// <summary> /// Make a new WebRequest without an S3Object. /// </summary> private WebRequest makeRequest( string method, string resource, SortedList headers ) { return makeRequest( method, resource, headers, null ); } /// <summary> /// Make a new WebRequest /// </summary> /// <param name="method">The HTTP method to use (GET, PUT, DELETE)</param> /// <param name="resource">The resource name (bucket + "/" + key)</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> /// <param name="obj">S3Object that is to be written (can be null).</param> private WebRequest makeRequest( string method, string resource, SortedList headers, S3Object obj ) { string url = makeURL( resource ); WebRequest req = WebRequest.Create( url ); if (req is HttpWebRequest) { HttpWebRequest httpReq = req as HttpWebRequest; httpReq.AllowWriteStreamBuffering = false; } req.Method = method; addHeaders( req, headers ); if ( obj != null ) addMetadataHeaders( req, obj.Metadata ); addAuthHeader( req, resource ); return req; } /// <summary> /// Add the given headers to the WebRequest /// </summary> /// <param name="req">Web request to add the headers to.</param> /// <param name="headers">A map of string to string representing the HTTP headers to pass (can be null)</param> private void addHeaders( WebRequest req, SortedList headers ) { addHeaders( req, headers, "" ); } /// <summary> /// Add the given metadata fields to the WebRequest. /// </summary> /// <param name="req">Web request to add the headers to.</param> /// <param name="metadata">A map of string to string representing the S3 metadata for this resource.</param> private void addMetadataHeaders( WebRequest req, SortedList metadata ) { addHeaders( req, metadata, Utils.METADATA_PREFIX ); } /// <summary> /// Add the given headers to the WebRequest with a prefix before the keys. /// </summary> /// <param name="req">WebRequest to add the headers to.</param> /// <param name="headers">Headers to add.</param> /// <param name="prefix">String to prepend to each before ebfore adding it to the WebRequest</param> private void addHeaders( WebRequest req, SortedList headers, string prefix ) { if ( headers != null ) { foreach ( string key in headers.Keys ) { if (prefix.Length == 0 && key.Equals("Content-Type")) { req.ContentType = headers[key] as string; } else { req.Headers.Add(prefix + key, headers[key] as string); } } } } /// <summary> /// Add the appropriate Authorization header to the WebRequest /// </summary> /// <param name="request">Request to add the header to</param> /// <param name="resource">The resource name (bucketName + "/" + key)</param> private void addAuthHeader( WebRequest request, string resource ) { if ( request.Headers[Utils.ALTERNATIVE_DATE_HEADER] == null ) { request.Headers.Add(Utils.ALTERNATIVE_DATE_HEADER, Utils.getHttpDate()); } string canonicalString = Utils.makeCanonicalString( resource, request ); string encodedCanonical = Utils.encode( awsSecretAccessKey, canonicalString, false ); request.Headers.Add( "Authorization", "AWS " + awsAccessKeyId + ":" + encodedCanonical ); } /// <summary> /// Create a new URL object for the given resource. /// </summary> /// <param name="resource">The resource name (bucketName + "/" + key)</param> private string makeURL( string resource ) { StringBuilder url = new StringBuilder(); url.Append( isSecure ? "https" : "http" ).Append( "://" ); url.Append( server ).Append( ":" ).Append( port ).Append( "/" ); url.Append( resource ); return url.ToString(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.WindowsAzure.Management.Automation; using Microsoft.WindowsAzure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.Management.Automation { /// <summary> /// Service operation for automation activities. (see /// http://aka.ms/azureautomationsdk/activityoperations for more /// information) /// </summary> internal partial class ActivityOperations : IServiceOperations<AutomationManagementClient>, IActivityOperations { /// <summary> /// Initializes a new instance of the ActivityOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ActivityOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve the activity in the module identified by module name and /// activity name. (see /// http://aka.ms/azureautomationsdk/activityoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The name of module. /// </param> /// <param name='activityName'> /// Required. The name of activity. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get activity operation. /// </returns> public async Task<ActivityGetResponse> GetAsync(string automationAccount, string moduleName, string activityName, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } if (activityName == null) { throw new ArgumentNullException("activityName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("moduleName", moduleName); tracingParameters.Add("activityName", activityName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/modules/"; url = url + Uri.EscapeDataString(moduleName); url = url + "/activities/"; url = url + Uri.EscapeDataString(activityName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ActivityGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Activity activityInstance = new Activity(); result.Activity = activityInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityProperties propertiesInstance = new ActivityProperties(); activityInstance.Properties = propertiesInstance; JToken definitionValue = propertiesValue["definition"]; if (definitionValue != null && definitionValue.Type != JTokenType.Null) { string definitionInstance = ((string)definitionValue); propertiesInstance.Definition = definitionInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken parameterSetsArray = propertiesValue["parameterSets"]; if (parameterSetsArray != null && parameterSetsArray.Type != JTokenType.Null) { foreach (JToken parameterSetsValue in ((JArray)parameterSetsArray)) { ActivityParameterSet activityParameterSetInstance = new ActivityParameterSet(); propertiesInstance.ParameterSets.Add(activityParameterSetInstance); JToken nameValue2 = parameterSetsValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); activityParameterSetInstance.Name = nameInstance2; } JToken parametersArray = parameterSetsValue["parameters"]; if (parametersArray != null && parametersArray.Type != JTokenType.Null) { foreach (JToken parametersValue in ((JArray)parametersArray)) { ActivityParameter activityParameterInstance = new ActivityParameter(); activityParameterSetInstance.Parameters.Add(activityParameterInstance); JToken nameValue3 = parametersValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); activityParameterInstance.Name = nameInstance3; } JToken typeValue = parametersValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); activityParameterInstance.Type = typeInstance; } JToken isMandatoryValue = parametersValue["isMandatory"]; if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null) { bool isMandatoryInstance = ((bool)isMandatoryValue); activityParameterInstance.IsMandatory = isMandatoryInstance; } JToken isDynamicValue = parametersValue["isDynamic"]; if (isDynamicValue != null && isDynamicValue.Type != JTokenType.Null) { bool isDynamicInstance = ((bool)isDynamicValue); activityParameterInstance.IsDynamic = isDynamicInstance; } JToken positionValue = parametersValue["position"]; if (positionValue != null && positionValue.Type != JTokenType.Null) { bool positionInstance = ((bool)positionValue); activityParameterInstance.Position = positionInstance; } JToken valueFromPipelineValue = parametersValue["valueFromPipeline"]; if (valueFromPipelineValue != null && valueFromPipelineValue.Type != JTokenType.Null) { bool valueFromPipelineInstance = ((bool)valueFromPipelineValue); activityParameterInstance.ValueFromPipeline = valueFromPipelineInstance; } JToken valueFromPipelineByPropertyNameValue = parametersValue["valueFromPipelineByPropertyName"]; if (valueFromPipelineByPropertyNameValue != null && valueFromPipelineByPropertyNameValue.Type != JTokenType.Null) { bool valueFromPipelineByPropertyNameInstance = ((bool)valueFromPipelineByPropertyNameValue); activityParameterInstance.ValueFromPipelineByPropertyName = valueFromPipelineByPropertyNameInstance; } JToken valueFromRemainingArgumentsValue = parametersValue["valueFromRemainingArguments"]; if (valueFromRemainingArgumentsValue != null && valueFromRemainingArgumentsValue.Type != JTokenType.Null) { bool valueFromRemainingArgumentsInstance = ((bool)valueFromRemainingArgumentsValue); activityParameterInstance.ValueFromRemainingArguments = valueFromRemainingArgumentsInstance; } } } } } JToken outputTypesArray = propertiesValue["outputTypes"]; if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null) { foreach (JToken outputTypesValue in ((JArray)outputTypesArray)) { ActivityOutputType activityOutputTypeInstance = new ActivityOutputType(); propertiesInstance.OutputTypes.Add(activityOutputTypeInstance); JToken nameValue4 = outputTypesValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); activityOutputTypeInstance.Name = nameInstance4; } JToken typeValue2 = outputTypesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); activityOutputTypeInstance.Type = typeInstance2; } } } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve a list of activities in the module identified by module /// name. (see http://aka.ms/azureautomationsdk/activityoperations /// for more information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The name of module. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list activity operation. /// </returns> public async Task<ActivityListResponse> ListAsync(string automationAccount, string moduleName, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("moduleName", moduleName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/modules/"; url = url + Uri.EscapeDataString(moduleName); url = url + "/activities"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ActivityListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Activity activityInstance = new Activity(); result.Activities.Add(activityInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityProperties propertiesInstance = new ActivityProperties(); activityInstance.Properties = propertiesInstance; JToken definitionValue = propertiesValue["definition"]; if (definitionValue != null && definitionValue.Type != JTokenType.Null) { string definitionInstance = ((string)definitionValue); propertiesInstance.Definition = definitionInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken parameterSetsArray = propertiesValue["parameterSets"]; if (parameterSetsArray != null && parameterSetsArray.Type != JTokenType.Null) { foreach (JToken parameterSetsValue in ((JArray)parameterSetsArray)) { ActivityParameterSet activityParameterSetInstance = new ActivityParameterSet(); propertiesInstance.ParameterSets.Add(activityParameterSetInstance); JToken nameValue2 = parameterSetsValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); activityParameterSetInstance.Name = nameInstance2; } JToken parametersArray = parameterSetsValue["parameters"]; if (parametersArray != null && parametersArray.Type != JTokenType.Null) { foreach (JToken parametersValue in ((JArray)parametersArray)) { ActivityParameter activityParameterInstance = new ActivityParameter(); activityParameterSetInstance.Parameters.Add(activityParameterInstance); JToken nameValue3 = parametersValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); activityParameterInstance.Name = nameInstance3; } JToken typeValue = parametersValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); activityParameterInstance.Type = typeInstance; } JToken isMandatoryValue = parametersValue["isMandatory"]; if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null) { bool isMandatoryInstance = ((bool)isMandatoryValue); activityParameterInstance.IsMandatory = isMandatoryInstance; } JToken isDynamicValue = parametersValue["isDynamic"]; if (isDynamicValue != null && isDynamicValue.Type != JTokenType.Null) { bool isDynamicInstance = ((bool)isDynamicValue); activityParameterInstance.IsDynamic = isDynamicInstance; } JToken positionValue = parametersValue["position"]; if (positionValue != null && positionValue.Type != JTokenType.Null) { bool positionInstance = ((bool)positionValue); activityParameterInstance.Position = positionInstance; } JToken valueFromPipelineValue = parametersValue["valueFromPipeline"]; if (valueFromPipelineValue != null && valueFromPipelineValue.Type != JTokenType.Null) { bool valueFromPipelineInstance = ((bool)valueFromPipelineValue); activityParameterInstance.ValueFromPipeline = valueFromPipelineInstance; } JToken valueFromPipelineByPropertyNameValue = parametersValue["valueFromPipelineByPropertyName"]; if (valueFromPipelineByPropertyNameValue != null && valueFromPipelineByPropertyNameValue.Type != JTokenType.Null) { bool valueFromPipelineByPropertyNameInstance = ((bool)valueFromPipelineByPropertyNameValue); activityParameterInstance.ValueFromPipelineByPropertyName = valueFromPipelineByPropertyNameInstance; } JToken valueFromRemainingArgumentsValue = parametersValue["valueFromRemainingArguments"]; if (valueFromRemainingArgumentsValue != null && valueFromRemainingArgumentsValue.Type != JTokenType.Null) { bool valueFromRemainingArgumentsInstance = ((bool)valueFromRemainingArgumentsValue); activityParameterInstance.ValueFromRemainingArguments = valueFromRemainingArgumentsInstance; } } } } } JToken outputTypesArray = propertiesValue["outputTypes"]; if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null) { foreach (JToken outputTypesValue in ((JArray)outputTypesArray)) { ActivityOutputType activityOutputTypeInstance = new ActivityOutputType(); propertiesInstance.OutputTypes.Add(activityOutputTypeInstance); JToken nameValue4 = outputTypesValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); activityOutputTypeInstance.Name = nameInstance4; } JToken typeValue2 = outputTypesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); activityOutputTypeInstance.Type = typeInstance2; } } } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve next list of activities in the module identified by module /// name. (see http://aka.ms/azureautomationsdk/activityoperations /// for more information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list activity operation. /// </returns> public async Task<ActivityListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ActivityListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Activity activityInstance = new Activity(); result.Activities.Add(activityInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityProperties propertiesInstance = new ActivityProperties(); activityInstance.Properties = propertiesInstance; JToken definitionValue = propertiesValue["definition"]; if (definitionValue != null && definitionValue.Type != JTokenType.Null) { string definitionInstance = ((string)definitionValue); propertiesInstance.Definition = definitionInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken parameterSetsArray = propertiesValue["parameterSets"]; if (parameterSetsArray != null && parameterSetsArray.Type != JTokenType.Null) { foreach (JToken parameterSetsValue in ((JArray)parameterSetsArray)) { ActivityParameterSet activityParameterSetInstance = new ActivityParameterSet(); propertiesInstance.ParameterSets.Add(activityParameterSetInstance); JToken nameValue2 = parameterSetsValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); activityParameterSetInstance.Name = nameInstance2; } JToken parametersArray = parameterSetsValue["parameters"]; if (parametersArray != null && parametersArray.Type != JTokenType.Null) { foreach (JToken parametersValue in ((JArray)parametersArray)) { ActivityParameter activityParameterInstance = new ActivityParameter(); activityParameterSetInstance.Parameters.Add(activityParameterInstance); JToken nameValue3 = parametersValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); activityParameterInstance.Name = nameInstance3; } JToken typeValue = parametersValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); activityParameterInstance.Type = typeInstance; } JToken isMandatoryValue = parametersValue["isMandatory"]; if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null) { bool isMandatoryInstance = ((bool)isMandatoryValue); activityParameterInstance.IsMandatory = isMandatoryInstance; } JToken isDynamicValue = parametersValue["isDynamic"]; if (isDynamicValue != null && isDynamicValue.Type != JTokenType.Null) { bool isDynamicInstance = ((bool)isDynamicValue); activityParameterInstance.IsDynamic = isDynamicInstance; } JToken positionValue = parametersValue["position"]; if (positionValue != null && positionValue.Type != JTokenType.Null) { bool positionInstance = ((bool)positionValue); activityParameterInstance.Position = positionInstance; } JToken valueFromPipelineValue = parametersValue["valueFromPipeline"]; if (valueFromPipelineValue != null && valueFromPipelineValue.Type != JTokenType.Null) { bool valueFromPipelineInstance = ((bool)valueFromPipelineValue); activityParameterInstance.ValueFromPipeline = valueFromPipelineInstance; } JToken valueFromPipelineByPropertyNameValue = parametersValue["valueFromPipelineByPropertyName"]; if (valueFromPipelineByPropertyNameValue != null && valueFromPipelineByPropertyNameValue.Type != JTokenType.Null) { bool valueFromPipelineByPropertyNameInstance = ((bool)valueFromPipelineByPropertyNameValue); activityParameterInstance.ValueFromPipelineByPropertyName = valueFromPipelineByPropertyNameInstance; } JToken valueFromRemainingArgumentsValue = parametersValue["valueFromRemainingArguments"]; if (valueFromRemainingArgumentsValue != null && valueFromRemainingArgumentsValue.Type != JTokenType.Null) { bool valueFromRemainingArgumentsInstance = ((bool)valueFromRemainingArgumentsValue); activityParameterInstance.ValueFromRemainingArguments = valueFromRemainingArgumentsInstance; } } } } } JToken outputTypesArray = propertiesValue["outputTypes"]; if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null) { foreach (JToken outputTypesValue in ((JArray)outputTypesArray)) { ActivityOutputType activityOutputTypeInstance = new ActivityOutputType(); propertiesInstance.OutputTypes.Add(activityOutputTypeInstance); JToken nameValue4 = outputTypesValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); activityOutputTypeInstance.Name = nameInstance4; } JToken typeValue2 = outputTypesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); activityOutputTypeInstance.Type = typeInstance2; } } } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using NLog; using ProtoBuf.Meta; using Sandbox; using Sandbox.Engine.Multiplayer; using Sandbox.Engine.Networking; using Sandbox.Engine.Platform.VideoMode; using Sandbox.Engine.Utils; using Sandbox.Game; using Sandbox.Game.Multiplayer; using Sandbox.Game.Screens.Helpers; using Sandbox.Game.World; using Sandbox.Graphics.GUI; using Sandbox.ModAPI; using SpaceEngineers.Game; using SpaceEngineers.Game.GUI; using Torch.API; using Torch.API.Managers; using Torch.API.ModAPI; using Torch.API.Session; using Torch.Commands; using Torch.Event; using Torch.Managers; using Torch.Managers.ChatManager; using Torch.Managers.PatchManager; using Torch.Patches; using Torch.Utils; using Torch.Session; using VRage; using VRage.Collections; using VRage.FileSystem; using VRage.Game; using VRage.Game.Common; using VRage.Game.Components; using VRage.Game.ObjectBuilder; using VRage.Game.SessionComponents; using VRage.GameServices; using VRage.Library; using VRage.ObjectBuilders; using VRage.Platform.Windows; using VRage.Plugins; using VRage.Scripting; using VRage.Steam; using VRage.Utils; using VRageRender; namespace Torch { /// <summary> /// Base class for code shared between the Torch client and server. /// </summary> public abstract class TorchBase : ViewModel, ITorchBase, IPlugin { static TorchBase() { MyVRageWindows.Init("SpaceEngineersDedicated", MySandboxGame.Log, null, false); ReflectedManager.Process(typeof(TorchBase).Assembly); ReflectedManager.Process(typeof(ITorchBase).Assembly); PatchManager.AddPatchShim(typeof(GameStatePatchShim)); PatchManager.AddPatchShim(typeof(GameAnalyticsPatch)); PatchManager.AddPatchShim(typeof(KeenLogPatch)); PatchManager.CommitInternal(); RegisterCoreAssembly(typeof(ITorchBase).Assembly); RegisterCoreAssembly(typeof(TorchBase).Assembly); RegisterCoreAssembly(Assembly.GetEntryAssembly()); //exceptions in English, please Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } /// <summary> /// Hack because *keen*. /// Use only if necessary, prefer dependency injection. /// </summary> [Obsolete("This is a hack, don't use it.")] public static ITorchBase Instance { get; private set; } /// <inheritdoc /> public ITorchConfig Config { get; protected set; } /// <inheritdoc /> public InformationalVersion TorchVersion { get; } /// <inheritdoc /> public Version GameVersion { get; private set; } /// <inheritdoc /> public string[] RunArgs { get; set; } /// <inheritdoc /> [Obsolete("Use GetManager<T>() or the [Dependency] attribute.")] public IPluginManager Plugins { get; protected set; } /// <inheritdoc /> public ITorchSession CurrentSession => Managers?.GetManager<ITorchSessionManager>()?.CurrentSession; /// <inheritdoc /> public event Action SessionLoading; /// <inheritdoc /> public event Action SessionLoaded; /// <inheritdoc /> public event Action SessionUnloading; /// <inheritdoc /> public event Action SessionUnloaded; /// <summary> /// Common log for the Torch instance. /// </summary> protected static Logger Log { get; } = LogManager.GetLogger("Torch"); /// <inheritdoc/> public IDependencyManager Managers { get; } private bool _init; /// <summary> /// /// </summary> /// <exception cref="InvalidOperationException">Thrown if a TorchBase instance already exists.</exception> protected TorchBase(ITorchConfig config) { RegisterCoreAssembly(GetType().Assembly); if (Instance != null) throw new InvalidOperationException("A TorchBase instance already exists."); Instance = this; Config = config; var versionString = Assembly.GetEntryAssembly() .GetCustomAttribute<AssemblyInformationalVersionAttribute>() .InformationalVersion; if (!InformationalVersion.TryParse(versionString, out InformationalVersion version)) throw new TypeLoadException("Unable to parse the Torch version from the assembly."); TorchVersion = version; RunArgs = new string[0]; Managers = new DependencyManager(); Plugins = new PluginManager(this); var sessionManager = new TorchSessionManager(this); sessionManager.AddFactory((x) => Sync.IsServer ? new ChatManagerServer(this) : new ChatManagerClient(this)); sessionManager.AddFactory((x) => Sync.IsServer ? new CommandManager(this) : null); sessionManager.AddFactory((x) => new EntityManager(this)); Managers.AddManager(sessionManager); Managers.AddManager(new PatchManager(this)); Managers.AddManager(new FilesystemManager(this)); Managers.AddManager(new UpdateManager(this)); Managers.AddManager(new EventManager(this)); Managers.AddManager(Plugins); TorchAPI.Instance = this; GameStateChanged += (game, state) => { if (state == TorchGameState.Created) { // If the attached assemblies change (MySandboxGame.ctor => MySandboxGame.ParseArgs => MyPlugins.RegisterFromArgs) // attach assemblies to object factories again. ObjectFactoryInitPatch.ForceRegisterAssemblies(); // safe to commit here; all important static ctors have run PatchManager.CommitInternal(); } }; sessionManager.SessionStateChanged += (session, state) => { switch (state) { case TorchSessionState.Loading: SessionLoading?.Invoke(); break; case TorchSessionState.Loaded: SessionLoaded?.Invoke(); break; case TorchSessionState.Unloading: SessionUnloading?.Invoke(); break; case TorchSessionState.Unloaded: SessionUnloaded?.Invoke(); break; default: throw new ArgumentOutOfRangeException(nameof(state), state, null); } }; } [Obsolete("Prefer using Managers.GetManager for global managers")] public T GetManager<T>() where T : class, IManager { return Managers.GetManager<T>(); } [Obsolete("Prefer using Managers.AddManager for global managers")] public bool AddManager<T>(T manager) where T : class, IManager { return Managers.AddManager(manager); } public bool IsOnGameThread() { return Thread.CurrentThread.ManagedThreadId == MySandboxGame.Static.UpdateThread.ManagedThreadId; } #region Game Actions /// <summary> /// Invokes an action on the game thread. /// </summary> /// <param name="action"></param> [MethodImpl(MethodImplOptions.NoInlining)] public void Invoke(Action action, [CallerMemberName] string caller = "") { MySandboxGame.Static.Invoke(action, caller); } /// <inheritdoc/> [MethodImpl(MethodImplOptions.NoInlining)] public void InvokeBlocking(Action action, int timeoutMs = -1, [CallerMemberName] string caller = "") { if (Thread.CurrentThread == MySandboxGame.Static.UpdateThread) { Debug.Assert(false, $"{nameof(InvokeBlocking)} should not be called on the game thread."); // ReSharper disable once HeuristicUnreachableCode action.Invoke(); return; } // ReSharper disable once ExplicitCallerInfoArgument Task task = InvokeAsync(action, caller); if (!task.Wait(timeoutMs)) throw new TimeoutException("The game action timed out"); if (task.IsFaulted && task.Exception != null) throw task.Exception; } /// <inheritdoc/> [MethodImpl(MethodImplOptions.NoInlining)] public Task<T> InvokeAsync<T>(Func<T> action, [CallerMemberName] string caller = "") { var ctx = new TaskCompletionSource<T>(); MySandboxGame.Static.Invoke(() => { try { ctx.SetResult(action.Invoke()); } catch (Exception e) { ctx.SetException(e); } finally { Debug.Assert(ctx.Task.IsCompleted); } }, caller); return ctx.Task; } /// <inheritdoc/> [MethodImpl(MethodImplOptions.NoInlining)] public Task InvokeAsync(Action action, [CallerMemberName] string caller = "") { var ctx = new TaskCompletionSource<bool>(); MySandboxGame.Static.Invoke(() => { try { action.Invoke(); ctx.SetResult(true); } catch (Exception e) { ctx.SetException(e); } finally { Debug.Assert(ctx.Task.IsCompleted); } }, caller); return ctx.Task; } #endregion #region Torch Init/Destroy protected abstract uint SteamAppId { get; } protected abstract string SteamAppName { get; } /// <inheritdoc /> public virtual void Init() { Debug.Assert(!_init, "Torch instance is already initialized."); SpaceEngineersGame.SetupBasicGameInfo(); SpaceEngineersGame.SetupPerGameSettings(); ObjectFactoryInitPatch.ForceRegisterAssemblies(); Debug.Assert(MyPerGameSettings.BasicGameInfo.GameVersion != null, "MyPerGameSettings.BasicGameInfo.GameVersion != null"); GameVersion = new MyVersion(MyPerGameSettings.BasicGameInfo.GameVersion.Value); try { Console.Title = $"{Config.InstanceName} - Torch {TorchVersion}, SE {GameVersion}"; } catch { // Running without a console } #if DEBUG Log.Info("DEBUG"); #else Log.Info("RELEASE"); #endif Log.Info($"Torch Version: {TorchVersion}"); Log.Info($"Game Version: {GameVersion}"); Log.Info($"Executing assembly: {Assembly.GetEntryAssembly().FullName}"); Log.Info($"Executing directory: {AppDomain.CurrentDomain.BaseDirectory}"); Managers.GetManager<PluginManager>().LoadPlugins(); Game = new VRageGame(this, TweakGameSettings, SteamAppName, SteamAppId, Config.InstancePath, RunArgs); if (!Game.WaitFor(VRageGame.GameState.Stopped)) Log.Warn("Failed to wait for game to be initialized"); Managers.Attach(); _init = true; if (GameState >= TorchGameState.Created && GameState < TorchGameState.Unloading) // safe to commit here; all important static ctors have run PatchManager.CommitInternal(); } /// <summary> /// Dispose callback for VRage plugin. Do not use. /// </summary> [Obsolete("Do not use; only there for VRage capability")] public void Dispose() { } /// <inheritdoc /> public virtual void Destroy() { Managers.Detach(); Game.SignalDestroy(); if (!Game.WaitFor(VRageGame.GameState.Destroyed)) Log.Warn("Failed to wait for the game to be destroyed"); Game = null; } #endregion protected VRageGame Game { get; private set; } /// <summary> /// Called after the basic game information is filled, but before the game is created. /// </summary> protected virtual void TweakGameSettings() { } private int _inProgressSaves = 0; /// <inheritdoc/> public virtual Task<GameSaveResult> Save(int timeoutMs = -1, bool exclusive = false) { if (exclusive) { if (MyAsyncSaving.InProgress || _inProgressSaves > 0) { Log.Error("Failed to save game, game is already saving"); return null; } } Interlocked.Increment(ref _inProgressSaves); return TorchAsyncSaving.Save(this, timeoutMs).ContinueWith((task, torchO) => { var torch = (TorchBase) torchO; Interlocked.Decrement(ref torch._inProgressSaves); if (task.IsFaulted) { Log.Error(task.Exception, "Failed to save game"); return GameSaveResult.UnknownError; } if (task.Result != GameSaveResult.Success) Log.Error($"Failed to save game: {task.Result}"); else Log.Info("Saved game"); return task.Result; }, this, TaskContinuationOptions.RunContinuationsAsynchronously); } /// <inheritdoc/> public virtual void Start() { Game.SignalStart(); if (!Game.WaitFor(VRageGame.GameState.Running)) Log.Warn("Failed to wait for the game to be started"); Invoke(() => Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US")); } /// <inheritdoc /> public virtual void Stop() { LogManager.Flush(); Game.SignalStop(); if (!Game.WaitFor(VRageGame.GameState.Stopped)) Log.Warn("Failed to wait for the game to be stopped"); } /// <inheritdoc /> public abstract void Restart(bool save = true); /// <inheritdoc /> public virtual void Init(object gameInstance) { } /// <inheritdoc /> public virtual void Update() { Managers.GetManager<IPluginManager>().UpdatePlugins(); } private TorchGameState _gameState = TorchGameState.Unloaded; /// <inheritdoc/> public TorchGameState GameState { get => _gameState; internal set { _gameState = value; GameStateChanged?.Invoke(MySandboxGame.Static, _gameState); } } /// <inheritdoc/> public event TorchGameStateChangedDel GameStateChanged; private static readonly HashSet<Assembly> _registeredCoreAssemblies = new HashSet<Assembly>(); /// <summary> /// Registers a core (Torch) assembly with the system, including its /// <see cref="EventManager"/> shims, <see cref="PatchManager"/> shims, and <see cref="ReflectedManager"/> components. /// </summary> /// <param name="asm">Assembly to register</param> internal static void RegisterCoreAssembly(Assembly asm) { lock (_registeredCoreAssemblies) if (_registeredCoreAssemblies.Add(asm)) { ReflectedManager.Process(asm); EventManager.AddDispatchShims(asm); PatchManager.AddPatchShims(asm); } } private static readonly HashSet<Assembly> _registeredAuxAssemblies = new HashSet<Assembly>(); private static readonly TimeSpan _gameStateChangeTimeout = TimeSpan.FromMinutes(1); /// <summary> /// Registers an auxillary (plugin) assembly with the system, including its /// <see cref="ReflectedManager"/> related components. /// </summary> /// <param name="asm">Assembly to register</param> internal static void RegisterAuxAssembly(Assembly asm) { lock (_registeredAuxAssemblies) if (_registeredAuxAssemblies.Add(asm)) { ReflectedManager.Process(asm); PatchManager.AddPatchShims(asm); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace System.Linq.Expressions { /// <summary> /// Strongly-typed and parameterized string resources. /// </summary> internal static class Strings { /// <summary> /// A string like "reducible nodes must override Expression.Reduce()" /// </summary> internal static string ReducibleMustOverrideReduce { get { return SR.ReducibleMustOverrideReduce; } } /// <summary> /// A string like "node cannot reduce to itself or null" /// </summary> internal static string MustReduceToDifferent { get { return SR.MustReduceToDifferent; } } /// <summary> /// A string like "cannot assign from the reduced node type to the original node type" /// </summary> internal static string ReducedNotCompatible { get { return SR.ReducedNotCompatible; } } /// <summary> /// A string like "Setter must have parameters." /// </summary> internal static string SetterHasNoParams { get { return SR.SetterHasNoParams; } } /// <summary> /// A string like "Property cannot have a managed pointer type." /// </summary> internal static string PropertyCannotHaveRefType { get { return SR.PropertyCannotHaveRefType; } } /// <summary> /// A string like "Indexing parameters of getter and setter must match." /// </summary> internal static string IndexesOfSetGetMustMatch { get { return SR.IndexesOfSetGetMustMatch; } } /// <summary> /// A string like "Accessor method should not have VarArgs." /// </summary> internal static string AccessorsCannotHaveVarArgs { get { return SR.AccessorsCannotHaveVarArgs; } } /// <summary> /// A string like "Accessor indexes cannot be passed ByRef." /// </summary> internal static string AccessorsCannotHaveByRefArgs { get { return SR.AccessorsCannotHaveByRefArgs; } } /// <summary> /// A string like "Bounds count cannot be less than 1" /// </summary> internal static string BoundsCannotBeLessThanOne { get { return SR.BoundsCannotBeLessThanOne; } } /// <summary> /// A string like "Type must not be ByRef" /// </summary> internal static string TypeMustNotBeByRef { get { return SR.TypeMustNotBeByRef; } } /// <summary> /// A string like "Type must not be a pointer type" /// </summary> internal static string TypeMustNotBePointer => SR.TypeMustNotBePointer; /// <summary> /// A string like "Type doesn't have constructor with a given signature" /// </summary> internal static string TypeDoesNotHaveConstructorForTheSignature { get { return SR.TypeDoesNotHaveConstructorForTheSignature; } } /// <summary> /// A string like "Setter should have void type." /// </summary> internal static string SetterMustBeVoid { get { return SR.SetterMustBeVoid; } } /// <summary> /// A string like "Property type must match the value type of setter" /// </summary> internal static string PropertyTypeMustMatchSetter { get { return SR.PropertyTypeMustMatchSetter; } } /// <summary> /// A string like "Both accessors must be static." /// </summary> internal static string BothAccessorsMustBeStatic { get { return SR.BothAccessorsMustBeStatic; } } /// <summary> /// A string like "Static field requires null instance, non-static field requires non-null instance." /// </summary> internal static string OnlyStaticFieldsHaveNullInstance { get { return SR.OnlyStaticFieldsHaveNullInstance; } } /// <summary> /// A string like "Static property requires null instance, non-static property requires non-null instance." /// </summary> internal static string OnlyStaticPropertiesHaveNullInstance { get { return SR.OnlyStaticPropertiesHaveNullInstance; } } /// <summary> /// A string like "Static method requires null instance, non-static method requires non-null instance." /// </summary> internal static string OnlyStaticMethodsHaveNullInstance { get { return SR.OnlyStaticMethodsHaveNullInstance; } } /// <summary> /// A string like "Property cannot have a void type." /// </summary> internal static string PropertyTypeCannotBeVoid { get { return SR.PropertyTypeCannotBeVoid; } } /// <summary> /// A string like "Can only unbox from an object or interface type to a value type." /// </summary> internal static string InvalidUnboxType { get { return SR.InvalidUnboxType; } } /// <summary> /// A string like "Expression must be writeable" /// </summary> internal static string ExpressionMustBeWriteable { get { return SR.ExpressionMustBeWriteable; } } /// <summary> /// A string like "Argument must not have a value type." /// </summary> internal static string ArgumentMustNotHaveValueType { get { return SR.ArgumentMustNotHaveValueType; } } /// <summary> /// A string like "must be reducible node" /// </summary> internal static string MustBeReducible { get { return SR.MustBeReducible; } } /// <summary> /// A string like "All test values must have the same type." /// </summary> internal static string AllTestValuesMustHaveSameType { get { return SR.AllTestValuesMustHaveSameType; } } /// <summary> /// A string like "All case bodies and the default body must have the same type." /// </summary> internal static string AllCaseBodiesMustHaveSameType { get { return SR.AllCaseBodiesMustHaveSameType; } } /// <summary> /// A string like "Default body must be supplied if case bodies are not System.Void." /// </summary> internal static string DefaultBodyMustBeSupplied { get { return SR.DefaultBodyMustBeSupplied; } } /// <summary> /// A string like "Label type must be System.Void if an expression is not supplied" /// </summary> internal static string LabelMustBeVoidOrHaveExpression { get { return SR.LabelMustBeVoidOrHaveExpression; } } /// <summary> /// A string like "Type must be System.Void for this label argument" /// </summary> internal static string LabelTypeMustBeVoid { get { return SR.LabelTypeMustBeVoid; } } /// <summary> /// A string like "Quoted expression must be a lambda" /// </summary> internal static string QuotedExpressionMustBeLambda { get { return SR.QuotedExpressionMustBeLambda; } } /// <summary> /// A string like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables." /// </summary> internal static string VariableMustNotBeByRef(object p0, object p1) { return SR.Format(SR.VariableMustNotBeByRef, p0, p1); } /// <summary> /// A string like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object." /// </summary> internal static string DuplicateVariable(object p0) { return SR.Format(SR.DuplicateVariable, p0); } /// <summary> /// A string like "Start and End must be well ordered" /// </summary> internal static string StartEndMustBeOrdered { get { return SR.StartEndMustBeOrdered; } } /// <summary> /// A string like "fault cannot be used with catch or finally clauses" /// </summary> internal static string FaultCannotHaveCatchOrFinally { get { return SR.FaultCannotHaveCatchOrFinally; } } /// <summary> /// A string like "try must have at least one catch, finally, or fault clause" /// </summary> internal static string TryMustHaveCatchFinallyOrFault { get { return SR.TryMustHaveCatchFinallyOrFault; } } /// <summary> /// A string like "Body of catch must have the same type as body of try." /// </summary> internal static string BodyOfCatchMustHaveSameTypeAsBodyOfTry { get { return SR.BodyOfCatchMustHaveSameTypeAsBodyOfTry; } } /// <summary> /// A string like "Extension node must override the property {0}." /// </summary> internal static string ExtensionNodeMustOverrideProperty(object p0) { return SR.Format(SR.ExtensionNodeMustOverrideProperty, p0); } /// <summary> /// A string like "User-defined operator method '{0}' must be static." /// </summary> internal static string UserDefinedOperatorMustBeStatic(object p0) { return SR.Format(SR.UserDefinedOperatorMustBeStatic, p0); } /// <summary> /// A string like "User-defined operator method '{0}' must not be void." /// </summary> internal static string UserDefinedOperatorMustNotBeVoid(object p0) { return SR.Format(SR.UserDefinedOperatorMustNotBeVoid, p0); } /// <summary> /// A string like "No coercion operator is defined between types '{0}' and '{1}'." /// </summary> internal static string CoercionOperatorNotDefined(object p0, object p1) { return SR.Format(SR.CoercionOperatorNotDefined, p0, p1); } /// <summary> /// A string like "The unary operator {0} is not defined for the type '{1}'." /// </summary> internal static string UnaryOperatorNotDefined(object p0, object p1) { return SR.Format(SR.UnaryOperatorNotDefined, p0, p1); } /// <summary> /// A string like "The binary operator {0} is not defined for the types '{1}' and '{2}'." /// </summary> internal static string BinaryOperatorNotDefined(object p0, object p1, object p2) { return SR.Format(SR.BinaryOperatorNotDefined, p0, p1, p2); } /// <summary> /// A string like "Reference equality is not defined for the types '{0}' and '{1}'." /// </summary> internal static string ReferenceEqualityNotDefined(object p0, object p1) { return SR.Format(SR.ReferenceEqualityNotDefined, p0, p1); } /// <summary> /// A string like "The operands for operator '{0}' do not match the parameters of method '{1}'." /// </summary> internal static string OperandTypesDoNotMatchParameters(object p0, object p1) { return SR.Format(SR.OperandTypesDoNotMatchParameters, p0, p1); } /// <summary> /// A string like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'." /// </summary> internal static string OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1) { return SR.Format(SR.OverloadOperatorTypeDoesNotMatchConversionType, p0, p1); } /// <summary> /// A string like "Conversion is not supported for arithmetic types without operator overloading." /// </summary> internal static string ConversionIsNotSupportedForArithmeticTypes { get { return SR.ConversionIsNotSupportedForArithmeticTypes; } } /// <summary> /// A string like "Argument must be array" /// </summary> internal static string ArgumentMustBeArray { get { return SR.ArgumentMustBeArray; } } /// <summary> /// A string like "Argument must be boolean" /// </summary> internal static string ArgumentMustBeBoolean { get { return SR.ArgumentMustBeBoolean; } } /// <summary> /// A string like "The user-defined equality method '{0}' must return a boolean value." /// </summary> internal static string EqualityMustReturnBoolean(object p0) { return SR.Format(SR.EqualityMustReturnBoolean, p0); } /// <summary> /// A string like "Argument must be either a FieldInfo or PropertyInfo" /// </summary> internal static string ArgumentMustBeFieldInfoOrPropertyInfo { get { return SR.ArgumentMustBeFieldInfoOrPropertyInfo; } } /// <summary> /// A string like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo" /// </summary> internal static string ArgumentMustBeFieldInfoOrPropertyInfoOrMethod { get { return SR.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod; } } /// <summary> /// A string like "Argument must be an instance member" /// </summary> internal static string ArgumentMustBeInstanceMember { get { return SR.ArgumentMustBeInstanceMember; } } /// <summary> /// A string like "Argument must be of an integer type" /// </summary> internal static string ArgumentMustBeInteger { get { return SR.ArgumentMustBeInteger; } } /// <summary> /// A string like "Argument for array index must be of type Int32" /// </summary> internal static string ArgumentMustBeArrayIndexType { get { return SR.ArgumentMustBeArrayIndexType; } } /// <summary> /// A string like "Argument must be single dimensional array type" /// </summary> internal static string ArgumentMustBeSingleDimensionalArrayType { get { return SR.ArgumentMustBeSingleDimensionalArrayType; } } /// <summary> /// A string like "Argument types do not match" /// </summary> internal static string ArgumentTypesMustMatch { get { return SR.ArgumentTypesMustMatch; } } /// <summary> /// A string like "Cannot auto initialize elements of value type through property '{0}', use assignment instead" /// </summary> internal static string CannotAutoInitializeValueTypeElementThroughProperty(object p0) { return SR.Format(SR.CannotAutoInitializeValueTypeElementThroughProperty, p0); } /// <summary> /// A string like "Cannot auto initialize members of value type through property '{0}', use assignment instead" /// </summary> internal static string CannotAutoInitializeValueTypeMemberThroughProperty(object p0) { return SR.Format(SR.CannotAutoInitializeValueTypeMemberThroughProperty, p0); } /// <summary> /// A string like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither" /// </summary> internal static string IncorrectTypeForTypeAs(object p0) { return SR.Format(SR.IncorrectTypeForTypeAs, p0); } /// <summary> /// A string like "Coalesce used with type that cannot be null" /// </summary> internal static string CoalesceUsedOnNonNullType { get { return SR.CoalesceUsedOnNonNullType; } } /// <summary> /// A string like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'" /// </summary> internal static string ExpressionTypeCannotInitializeArrayType(object p0, object p1) { return SR.Format(SR.ExpressionTypeCannotInitializeArrayType, p0, p1); } /// <summary> /// A string like " Argument type '{0}' does not match the corresponding member type '{1}'" /// </summary> internal static string ArgumentTypeDoesNotMatchMember(object p0, object p1) { return SR.Format(SR.ArgumentTypeDoesNotMatchMember, p0, p1); } /// <summary> /// A string like " The member '{0}' is not declared on type '{1}' being created" /// </summary> internal static string ArgumentMemberNotDeclOnType(object p0, object p1) { return SR.Format(SR.ArgumentMemberNotDeclOnType, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be used for return type '{1}'" /// </summary> internal static string ExpressionTypeDoesNotMatchReturn(object p0, object p1) { return SR.Format(SR.ExpressionTypeDoesNotMatchReturn, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be used for assignment to type '{1}'" /// </summary> internal static string ExpressionTypeDoesNotMatchAssignment(object p0, object p1) { return SR.Format(SR.ExpressionTypeDoesNotMatchAssignment, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be used for label of type '{1}'" /// </summary> internal static string ExpressionTypeDoesNotMatchLabel(object p0, object p1) { return SR.Format(SR.ExpressionTypeDoesNotMatchLabel, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be invoked" /// </summary> internal static string ExpressionTypeNotInvocable(object p0) { return SR.Format(SR.ExpressionTypeNotInvocable, p0); } /// <summary> /// A string like "Field '{0}' is not defined for type '{1}'" /// </summary> internal static string FieldNotDefinedForType(object p0, object p1) { return SR.Format(SR.FieldNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance field '{0}' is not defined for type '{1}'" /// </summary> internal static string InstanceFieldNotDefinedForType(object p0, object p1) { return SR.Format(SR.InstanceFieldNotDefinedForType, p0, p1); } /// <summary> /// A string like "Field '{0}.{1}' is not defined for type '{2}'" /// </summary> internal static string FieldInfoNotDefinedForType(object p0, object p1, object p2) { return SR.Format(SR.FieldInfoNotDefinedForType, p0, p1, p2); } /// <summary> /// A string like "Incorrect number of indexes" /// </summary> internal static string IncorrectNumberOfIndexes { get { return SR.IncorrectNumberOfIndexes; } } /// <summary> /// A string like "Incorrect number of parameters supplied for lambda declaration" /// </summary> internal static string IncorrectNumberOfLambdaDeclarationParameters { get { return SR.IncorrectNumberOfLambdaDeclarationParameters; } } /// <summary> /// A string like " Incorrect number of members for constructor" /// </summary> internal static string IncorrectNumberOfMembersForGivenConstructor { get { return SR.IncorrectNumberOfMembersForGivenConstructor; } } /// <summary> /// A string like "Incorrect number of arguments for the given members " /// </summary> internal static string IncorrectNumberOfArgumentsForMembers { get { return SR.IncorrectNumberOfArgumentsForMembers; } } /// <summary> /// A string like "Lambda type parameter must be derived from System.MulticastDelegate" /// </summary> internal static string LambdaTypeMustBeDerivedFromSystemDelegate { get { return SR.LambdaTypeMustBeDerivedFromSystemDelegate; } } /// <summary> /// A string like "Member '{0}' not field or property" /// </summary> internal static string MemberNotFieldOrProperty(object p0) { return SR.Format(SR.MemberNotFieldOrProperty, p0); } /// <summary> /// A string like "Method {0} contains generic parameters" /// </summary> internal static string MethodContainsGenericParameters(object p0) { return SR.Format(SR.MethodContainsGenericParameters, p0); } /// <summary> /// A string like "Method {0} is a generic method definition" /// </summary> internal static string MethodIsGeneric(object p0) { return SR.Format(SR.MethodIsGeneric, p0); } /// <summary> /// A string like "The method '{0}.{1}' is not a property accessor" /// </summary> internal static string MethodNotPropertyAccessor(object p0, object p1) { return SR.Format(SR.MethodNotPropertyAccessor, p0, p1); } /// <summary> /// A string like "The property '{0}' has no 'get' accessor" /// </summary> internal static string PropertyDoesNotHaveGetter(object p0) { return SR.Format(SR.PropertyDoesNotHaveGetter, p0); } /// <summary> /// A string like "The property '{0}' has no 'set' accessor" /// </summary> internal static string PropertyDoesNotHaveSetter(object p0) { return SR.Format(SR.PropertyDoesNotHaveSetter, p0); } /// <summary> /// A string like "The property '{0}' has no 'get' or 'set' accessors" /// </summary> internal static string PropertyDoesNotHaveAccessor(object p0) { return SR.Format(SR.PropertyDoesNotHaveAccessor, p0); } /// <summary> /// A string like "'{0}' is not a member of type '{1}'" /// </summary> internal static string NotAMemberOfType(object p0, object p1) { return SR.Format(SR.NotAMemberOfType, p0, p1); } /// <summary> /// A string like "The expression '{0}' is not supported for type '{1}'" /// </summary> internal static string ExpressionNotSupportedForType(object p0, object p1) { return SR.Format(SR.ExpressionNotSupportedForType, p0, p1); } /// <summary> /// A string like "The expression '{0}' is not supported for nullable type '{1}'" /// </summary> internal static string ExpressionNotSupportedForNullableType(object p0, object p1) { return SR.Format(SR.ExpressionNotSupportedForNullableType, p0, p1); } /// <summary> /// A string like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'" /// </summary> internal static string ParameterExpressionNotValidAsDelegate(object p0, object p1) { return SR.Format(SR.ParameterExpressionNotValidAsDelegate, p0, p1); } /// <summary> /// A string like "Property '{0}' is not defined for type '{1}'" /// </summary> internal static string PropertyNotDefinedForType(object p0, object p1) { return SR.Format(SR.PropertyNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance property '{0}' is not defined for type '{1}'" /// </summary> internal static string InstancePropertyNotDefinedForType(object p0, object p1) { return SR.Format(SR.InstancePropertyNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance property '{0}' that takes no argument is not defined for type '{1}'" /// </summary> internal static string InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1) { return SR.Format(SR.InstancePropertyWithoutParameterNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance property '{0}{1}' is not defined for type '{2}'" /// </summary> internal static string InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2) { return SR.Format(SR.InstancePropertyWithSpecifiedParametersNotDefinedForType, p0, p1, p2); } /// <summary> /// A string like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'" /// </summary> internal static string InstanceAndMethodTypeMismatch(object p0, object p1, object p2) { return SR.Format(SR.InstanceAndMethodTypeMismatch, p0, p1, p2); } /// <summary> /// A string like "Type '{0}' does not have a default constructor" /// </summary> internal static string TypeMissingDefaultConstructor(object p0) { return SR.Format(SR.TypeMissingDefaultConstructor, p0); } /// <summary> /// A string like "Element initializer method must be named 'Add'" /// </summary> internal static string ElementInitializerMethodNotAdd { get { return SR.ElementInitializerMethodNotAdd; } } /// <summary> /// A string like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter" /// </summary> internal static string ElementInitializerMethodNoRefOutParam(object p0, object p1) { return SR.Format(SR.ElementInitializerMethodNoRefOutParam, p0, p1); } /// <summary> /// A string like "Element initializer method must have at least 1 parameter" /// </summary> internal static string ElementInitializerMethodWithZeroArgs { get { return SR.ElementInitializerMethodWithZeroArgs; } } /// <summary> /// A string like "Element initializer method must be an instance method" /// </summary> internal static string ElementInitializerMethodStatic { get { return SR.ElementInitializerMethodStatic; } } /// <summary> /// A string like "Type '{0}' is not IEnumerable" /// </summary> internal static string TypeNotIEnumerable(object p0) { return SR.Format(SR.TypeNotIEnumerable, p0); } /// <summary> /// A string like "Unexpected coalesce operator." /// </summary> internal static string UnexpectedCoalesceOperator { get { return SR.UnexpectedCoalesceOperator; } } /// <summary> /// A string like "Cannot cast from type '{0}' to type '{1}" /// </summary> internal static string InvalidCast(object p0, object p1) { return SR.Format(SR.InvalidCast, p0, p1); } /// <summary> /// A string like "Unhandled binary: {0}" /// </summary> internal static string UnhandledBinary(object p0) { return SR.Format(SR.UnhandledBinary, p0); } /// <summary> /// A string like "Unhandled binding " /// </summary> internal static string UnhandledBinding { get { return SR.UnhandledBinding; } } /// <summary> /// A string like "Unhandled Binding Type: {0}" /// </summary> internal static string UnhandledBindingType(object p0) { return SR.Format(SR.UnhandledBindingType, p0); } /// <summary> /// A string like "Unhandled convert: {0}" /// </summary> internal static string UnhandledConvert(object p0) { return SR.Format(SR.UnhandledConvert, p0); } /// <summary> /// A string like "Unhandled unary: {0}" /// </summary> internal static string UnhandledUnary(object p0) { return SR.Format(SR.UnhandledUnary, p0); } /// <summary> /// A string like "Unknown binding type" /// </summary> internal static string UnknownBindingType { get { return SR.UnknownBindingType; } } /// <summary> /// A string like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types." /// </summary> internal static string UserDefinedOpMustHaveConsistentTypes(object p0, object p1) { return SR.Format(SR.UserDefinedOpMustHaveConsistentTypes, p0, p1); } /// <summary> /// A string like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type." /// </summary> internal static string UserDefinedOpMustHaveValidReturnType(object p0, object p1) { return SR.Format(SR.UserDefinedOpMustHaveValidReturnType, p0, p1); } /// <summary> /// A string like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators." /// </summary> internal static string LogicalOperatorMustHaveBooleanOperators(object p0, object p1) { return SR.Format(SR.LogicalOperatorMustHaveBooleanOperators, p0, p1); } /// <summary> /// A string like "No method '{0}' exists on type '{1}'." /// </summary> internal static string MethodDoesNotExistOnType(object p0, object p1) { return SR.Format(SR.MethodDoesNotExistOnType, p0, p1); } /// <summary> /// A string like "No method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static string MethodWithArgsDoesNotExistOnType(object p0, object p1) { return SR.Format(SR.MethodWithArgsDoesNotExistOnType, p0, p1); } /// <summary> /// A string like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. " /// </summary> internal static string GenericMethodWithArgsDoesNotExistOnType(object p0, object p1) { return SR.Format(SR.GenericMethodWithArgsDoesNotExistOnType, p0, p1); } /// <summary> /// A string like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static string MethodWithMoreThanOneMatch(object p0, object p1) { return SR.Format(SR.MethodWithMoreThanOneMatch, p0, p1); } /// <summary> /// A string like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static string PropertyWithMoreThanOneMatch(object p0, object p1) { return SR.Format(SR.PropertyWithMoreThanOneMatch, p0, p1); } /// <summary> /// A string like "An incorrect number of type args were specified for the declaration of a Func type." /// </summary> internal static string IncorrectNumberOfTypeArgsForFunc { get { return SR.IncorrectNumberOfTypeArgsForFunc; } } /// <summary> /// A string like "An incorrect number of type args were specified for the declaration of an Action type." /// </summary> internal static string IncorrectNumberOfTypeArgsForAction { get { return SR.IncorrectNumberOfTypeArgsForAction; } } /// <summary> /// A string like "Argument type cannot be System.Void." /// </summary> internal static string ArgumentCannotBeOfTypeVoid { get { return SR.ArgumentCannotBeOfTypeVoid; } } /// <summary> /// A string like "{0} must be greater than or equal to {1}" /// </summary> internal static string OutOfRange(object p0, object p1) { return SR.Format(SR.OutOfRange, p0, p1); } /// <summary> /// A string like "Cannot redefine label '{0}' in an inner block." /// </summary> internal static string LabelTargetAlreadyDefined(object p0) { return SR.Format(SR.LabelTargetAlreadyDefined, p0); } /// <summary> /// A string like "Cannot jump to undefined label '{0}'." /// </summary> internal static string LabelTargetUndefined(object p0) { return SR.Format(SR.LabelTargetUndefined, p0); } /// <summary> /// A string like "Control cannot leave a finally block." /// </summary> internal static string ControlCannotLeaveFinally { get { return SR.ControlCannotLeaveFinally; } } /// <summary> /// A string like "Control cannot leave a filter test." /// </summary> internal static string ControlCannotLeaveFilterTest { get { return SR.ControlCannotLeaveFilterTest; } } /// <summary> /// A string like "Cannot jump to ambiguous label '{0}'." /// </summary> internal static string AmbiguousJump(object p0) { return SR.Format(SR.AmbiguousJump, p0); } /// <summary> /// A string like "Control cannot enter a try block." /// </summary> internal static string ControlCannotEnterTry { get { return SR.ControlCannotEnterTry; } } /// <summary> /// A string like "Control cannot enter an expression--only statements can be jumped into." /// </summary> internal static string ControlCannotEnterExpression { get { return SR.ControlCannotEnterExpression; } } /// <summary> /// A string like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values." /// </summary> internal static string NonLocalJumpWithValue(object p0) { return SR.Format(SR.NonLocalJumpWithValue, p0); } /// <summary> /// A string like "Extension should have been reduced." /// </summary> internal static string ExtensionNotReduced { get { return SR.ExtensionNotReduced; } } #if FEATURE_COMPILE_TO_METHODBUILDER /// <summary> /// A string like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value." /// </summary> internal static string CannotCompileConstant(object p0) { return SR.Format(SR.CannotCompileConstant, p0); } /// <summary> /// A string like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite." /// </summary> internal static string CannotCompileDynamic { get { return SR.CannotCompileDynamic; } } /// <summary> /// A string like "MethodBuilder does not have a valid TypeBuilder" /// </summary> internal static string MethodBuilderDoesNotHaveTypeBuilder { get { return SR.MethodBuilderDoesNotHaveTypeBuilder; } } #endif /// <summary> /// A string like "Invalid lvalue for assignment: {0}." /// </summary> internal static string InvalidLvalue(object p0) { return SR.Format(SR.InvalidLvalue, p0); } /// <summary> /// A string like "Invalid member type: {0}." /// </summary> internal static string InvalidMemberType(object p0) { return SR.Format(SR.InvalidMemberType, p0); } /// <summary> /// A string like "unknown lift type: '{0}'." /// </summary> internal static string UnknownLiftType(object p0) { return SR.Format(SR.UnknownLiftType, p0); } /// <summary> /// A string like "Cannot create instance of {0} because it contains generic parameters" /// </summary> internal static string IllegalNewGenericParams(object p0) { return SR.Format(SR.IllegalNewGenericParams, p0); } /// <summary> /// A string like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined" /// </summary> internal static string UndefinedVariable(object p0, object p1, object p2) { return SR.Format(SR.UndefinedVariable, p0, p1, p2); } /// <summary> /// A string like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'" /// </summary> internal static string CannotCloseOverByRef(object p0, object p1) { return SR.Format(SR.CannotCloseOverByRef, p0, p1); } /// <summary> /// A string like "Unexpected VarArgs call to method '{0}'" /// </summary> internal static string UnexpectedVarArgsCall(object p0) { return SR.Format(SR.UnexpectedVarArgsCall, p0); } /// <summary> /// A string like "Rethrow statement is valid only inside a Catch block." /// </summary> internal static string RethrowRequiresCatch { get { return SR.RethrowRequiresCatch; } } /// <summary> /// A string like "Try expression is not allowed inside a filter body." /// </summary> internal static string TryNotAllowedInFilter { get { return SR.TryNotAllowedInFilter; } } /// <summary> /// A string like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type." /// </summary> internal static string MustRewriteToSameNode(object p0, object p1, object p2) { return SR.Format(SR.MustRewriteToSameNode, p0, p1, p2); } /// <summary> /// A string like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite." /// </summary> internal static string MustRewriteChildToSameType(object p0, object p1, object p2) { return SR.Format(SR.MustRewriteChildToSameType, p0, p1, p2); } /// <summary> /// A string like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is intentional, override '{1}' and change it to allow this rewrite." /// </summary> internal static string MustRewriteWithoutMethod(object p0, object p1) { return SR.Format(SR.MustRewriteWithoutMethod, p0, p1); } /// <summary> /// A string like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static string TryNotSupportedForMethodsWithRefArgs(object p0) { return SR.Format(SR.TryNotSupportedForMethodsWithRefArgs, p0); } /// <summary> /// A string like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static string TryNotSupportedForValueTypeInstances(object p0) { return SR.Format(SR.TryNotSupportedForValueTypeInstances, p0); } /// <summary> /// A string like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static string TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return SR.Format(SR.TestValueTypeDoesNotMatchComparisonMethodParameter, p0, p1); } /// <summary> /// A string like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static string SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return SR.Format(SR.SwitchValueTypeDoesNotMatchComparisonMethodParameter, p0, p1); } #if FEATURE_COMPILE_TO_METHODBUILDER && FEATURE_PDB_GENERATOR /// <summary> /// A string like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod." /// </summary> internal static string PdbGeneratorNeedsExpressionCompiler { get { return SR.PdbGeneratorNeedsExpressionCompiler; } } #endif #if FEATURE_COMPILE /// <summary> /// A string like "The operator '{0}' is not implemented for type '{1}'" /// </summary> internal static string OperatorNotImplementedForType(object p0, object p1) { return SR.Format(SR.OperatorNotImplementedForType, p0, p1); } #endif /// <summary> /// A string like "The constructor should not be static" /// </summary> internal static string NonStaticConstructorRequired { get { return SR.NonStaticConstructorRequired; } } /// <summary> /// A string like "The constructor should not be declared on an abstract class" /// </summary> internal static string NonAbstractConstructorRequired { get { return SR.NonAbstractConstructorRequired; } } } }
namespace HeavyLoad { using System; using Correlated; using Load; using log4net; using MassTransit.Transports.Msmq; internal class Program { static readonly ILog _log = LogManager.GetLogger(typeof (Program)); static void Main(string[] args) { _log.Info("HeavyLoad - MassTransit Load Generator"); MsmqEndpointManagement.Manage(new MsmqEndpointAddress(new Uri("msmq://localhost/mt_client")), q => { q.Create(false); q.Purge(); }); Console.WriteLine("HeavyLoad - MassTransit Load Generator"); Console.WriteLine(); //RunLoopbackHandlerLoadTest(); //RunLoopbackConsumerLoadTest(); //RunStructureMapLoadTest(); //RunLocalMsmqLoadTest(); //RunTransactionLoadTest(); //RunCorrelatedMessageTest(); //RunLocalRequestResponseMsmqLoadTest(); //RunRabbitMqLoadTest(); //RunLocalActiveMqLoadTest(); RunLongRunningMemoryTest(); Console.WriteLine("End of line."); } static void RunLocalActiveMqLoadTest() { var stopWatch = new StopWatch(); using (var test = new ActiveMQLoadTest()) { test.Run(stopWatch); } Console.WriteLine("ActiveMQ Load Test: "); Console.WriteLine(stopWatch.ToString()); Console.WriteLine(); } static void RunRabbitMqLoadTest() { try { var stopWatch = new StopWatch(); using (var test = new RabbitMqHandlerLoadTest()) { test.Run(stopWatch); } Console.WriteLine("RabbitMQ Load Test: "); Console.WriteLine(stopWatch.ToString()); Console.WriteLine(); } catch (Exception ex) { Console.WriteLine("Unable to run RabbitMQ Load Test: " + ex); Console.WriteLine("If RabbitMQ is not installed, this is normal"); } } static void RunLocalMsmqLoadTest() { Console.WriteLine("Starting Local MSMQ Load Test"); var stopWatch = new StopWatch(); using (var test = new LocalLoadTest()) { test.Run(stopWatch); } Console.WriteLine("Local MSMQ Load Test: "); Console.WriteLine(stopWatch.ToString()); Console.WriteLine(); } static void RunLocalRequestResponseMsmqLoadTest() { Console.WriteLine("Starting MSMQ Local Request Response Load Test"); var stopWatch = new StopWatch(); using (var test = new LocalMsmqRequestResponseLoadTest()) { test.Run(stopWatch); } Console.WriteLine("Local MSMQ Request Response Load Test: "); Console.WriteLine(stopWatch.ToString()); Console.WriteLine(); } static void RunLongRunningMemoryTest() { var stopWatch = new StopWatch(); using (var test = new LongRunningMemoryTest()) { test.Run(stopWatch); stopWatch.Stop(); } Console.WriteLine("Long Running Memory Test: {0}", stopWatch); } static void RunStructureMapLoadTest() { Console.WriteLine("Starting StructureMap Load Test"); var stopWatch = new StopWatch(); using (var test = new StructureMapConsumerLoadTest()) { test.Run(stopWatch); } Console.WriteLine("StructureMap Load Test: "); Console.WriteLine(stopWatch.ToString()); Console.WriteLine(); } static void RunTransactionLoadTest() { Console.WriteLine("Starting Local MSMQ Transactional Load Test"); var stopWatch = new StopWatch(); using (var test = new TransactionLoadTest()) { test.Run(stopWatch); } Console.WriteLine("Transaction Load Test: "); Console.WriteLine(stopWatch.ToString()); Console.WriteLine(); } static void RunLoopbackHandlerLoadTest() { Console.WriteLine("Starting Local Loopback Handler Load Test"); var stopWatch = new StopWatch(); using (var test = new LoopbackHandlerLoadTest()) { test.Run(stopWatch); } Console.WriteLine("Loopback Load Handler Test: "); Console.WriteLine(stopWatch.ToString()); Console.WriteLine(); } static void RunLoopbackConsumerLoadTest() { Console.WriteLine("Starting Local Loopback Consumer Load Test"); var stopWatch = new StopWatch(); using (var test = new LoopbackConsumerLoadTest()) { test.Run(stopWatch); } Console.WriteLine("Loopback Load Consumer Test: "); Console.WriteLine(stopWatch.ToString()); Console.WriteLine(); } static void RunCorrelatedMessageTest() { Console.WriteLine("Starting Local MSMQ Correlated Load Test"); var stopWatch = new StopWatch(); using (var test = new CorrelatedMessageTest()) { test.Run(stopWatch); } Console.WriteLine("Correlated Message Test: "); Console.WriteLine(stopWatch.ToString()); Console.WriteLine(); } } }
//----------------------------------------------------------------------------- // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Diagnostics.SymbolStore; namespace Microsoft.Cci.Pdb { internal class PdbFile { private PdbFile() // This class can't be instantiated. { } static void LoadGuidStream(BitAccess bits, out Guid doctype, out Guid language, out Guid vendor) { bits.ReadGuid(out language); bits.ReadGuid(out vendor); bits.ReadGuid(out doctype); } static Dictionary<string, int> LoadNameIndex(BitAccess bits) { Dictionary<string, int> result = new Dictionary<string, int>(); int ver; int sig; int age; Guid guid; bits.ReadInt32(out ver); // 0..3 Version bits.ReadInt32(out sig); // 4..7 Signature bits.ReadInt32(out age); // 8..11 Age bits.ReadGuid(out guid); // 12..27 GUID //if (ver != 20000404) { // throw new PdbDebugException("Unsupported PDB Stream version {0}", ver); //} // Read string buffer. int buf; bits.ReadInt32(out buf); // 28..31 Bytes of Strings int beg = bits.Position; int nxt = bits.Position + buf; bits.Position = nxt; // Read map index. int cnt; // n+0..3 hash size. int max; // n+4..7 maximum ni. bits.ReadInt32(out cnt); bits.ReadInt32(out max); BitSet present = new BitSet(bits); BitSet deleted = new BitSet(bits); if (!deleted.IsEmpty) { throw new PdbDebugException("Unsupported PDB deleted bitset is not empty."); } int j = 0; for (int i = 0; i < max; i++) { if (present.IsSet(i)) { int ns; int ni; bits.ReadInt32(out ns); bits.ReadInt32(out ni); string name; int saved = bits.Position; bits.Position = beg + ns; bits.ReadCString(out name); bits.Position = saved; result.Add(name.ToUpperInvariant(), ni); j++; } } if (j != cnt) { throw new PdbDebugException("Count mismatch. ({0} != {1})", j, cnt); } return result; } static IntHashTable LoadNameStream(BitAccess bits) { IntHashTable ht = new IntHashTable(); uint sig; int ver; bits.ReadUInt32(out sig); // 0..3 Signature bits.ReadInt32(out ver); // 4..7 Version // Read (or skip) string buffer. int buf; bits.ReadInt32(out buf); // 8..11 Bytes of Strings if (sig != 0xeffeeffe || ver != 1) { throw new PdbDebugException("Unsupported Name Stream version. "+ "(sig={0:x8}, ver={1})", sig, ver); } int beg = bits.Position; int nxt = bits.Position + buf; bits.Position = nxt; // Read hash table. int siz; bits.ReadInt32(out siz); // n+0..3 Number of hash buckets. nxt = bits.Position; for (int i = 0; i < siz; i++) { int ni; string name; bits.ReadInt32(out ni); if (ni != 0) { int saved = bits.Position; bits.Position = beg + ni; bits.ReadCString(out name); bits.Position = saved; ht.Add(ni, name); } } bits.Position = nxt; return ht; } private static PdbFunction match = new PdbFunction(); private static int FindFunction(PdbFunction[] funcs, ushort sec, uint off) { match.segment = sec; match.address = off; return Array.BinarySearch(funcs, match, PdbFunction.byAddress); } static void LoadManagedLines(PdbFunction[] funcs, IntHashTable names, BitAccess bits, MsfDirectory dir, Dictionary<string, int> nameIndex, PdbReader reader, uint limit) { Array.Sort(funcs, PdbFunction.byAddressAndToken); int begin = bits.Position; IntHashTable checks = ReadSourceFileInfo(bits, limit, names, dir, nameIndex, reader); // Read the lines next. bits.Position = begin; while (bits.Position < limit) { int sig; int siz; bits.ReadInt32(out sig); bits.ReadInt32(out siz); int endSym = bits.Position + siz; switch ((DEBUG_S_SUBSECTION)sig) { case DEBUG_S_SUBSECTION.LINES: { CV_LineSection sec; bits.ReadUInt32(out sec.off); bits.ReadUInt16(out sec.sec); bits.ReadUInt16(out sec.flags); bits.ReadUInt32(out sec.cod); int funcIndex = FindFunction(funcs, sec.sec, sec.off); if (funcIndex < 0) break; var func = funcs[funcIndex]; if (func.lines == null) { while (funcIndex > 0) { var f = funcs[funcIndex-1]; if (f.lines != null || f.segment != sec.sec || f.address != sec.off) break; func = f; funcIndex--; } } else { while (funcIndex < funcs.Length-1 && func.lines != null) { var f = funcs[funcIndex+1]; if (f.segment != sec.sec || f.address != sec.off) break; func = f; funcIndex++; } } if (func.lines != null) break; // Count the line blocks. int begSym = bits.Position; int blocks = 0; while (bits.Position < endSym) { CV_SourceFile file; bits.ReadUInt32(out file.index); bits.ReadUInt32(out file.count); bits.ReadUInt32(out file.linsiz); // Size of payload. int linsiz = (int)file.count * (8 + ((sec.flags & 1) != 0 ? 4 : 0)); bits.Position += linsiz; blocks++; } func.lines = new PdbLines[blocks]; int block = 0; bits.Position = begSym; while (bits.Position < endSym) { CV_SourceFile file; bits.ReadUInt32(out file.index); bits.ReadUInt32(out file.count); bits.ReadUInt32(out file.linsiz); // Size of payload. PdbSource src = (PdbSource)checks[(int)file.index]; PdbLines tmp = new PdbLines(src, file.count); func.lines[block++] = tmp; PdbLine[] lines = tmp.lines; int plin = bits.Position; int pcol = bits.Position + 8 * (int)file.count; for (int i = 0; i < file.count; i++) { CV_Line line; CV_Column column = new CV_Column(); bits.Position = plin + 8 * i; bits.ReadUInt32(out line.offset); bits.ReadUInt32(out line.flags); uint lineBegin = line.flags & (uint)CV_Line_Flags.linenumStart; uint delta = (line.flags & (uint)CV_Line_Flags.deltaLineEnd) >> 24; //bool statement = ((line.flags & (uint)CV_Line_Flags.fStatement) == 0); if ((sec.flags & 1) != 0) { bits.Position = pcol + 4 * i; bits.ReadUInt16(out column.offColumnStart); bits.ReadUInt16(out column.offColumnEnd); } lines[i] = new PdbLine(line.offset, lineBegin, column.offColumnStart, lineBegin+delta, column.offColumnEnd); } } break; } } bits.Position = endSym; } } static void LoadFuncsFromDbiModule(BitAccess bits, DbiModuleInfo info, IntHashTable names, ArrayList funcList, bool readStrings, MsfDirectory dir, Dictionary<string, int> nameIndex, PdbReader reader) { PdbFunction[] funcs = null; bits.Position = 0; int sig; bits.ReadInt32(out sig); if (sig != 4) { throw new PdbDebugException("Invalid signature. (sig={0})", sig); } bits.Position = 4; // Console.WriteLine("{0}:", info.moduleName); funcs = PdbFunction.LoadManagedFunctions(/*info.moduleName,*/ bits, (uint)info.cbSyms, readStrings); if (funcs != null) { bits.Position = info.cbSyms + info.cbOldLines; LoadManagedLines(funcs, names, bits, dir, nameIndex, reader, (uint)(info.cbSyms + info.cbOldLines + info.cbLines)); for (int i = 0; i < funcs.Length; i++) { funcList.Add(funcs[i]); } } } static void LoadDbiStream(BitAccess bits, out DbiModuleInfo[] modules, out DbiDbgHdr header, bool readStrings) { DbiHeader dh = new DbiHeader(bits); header = new DbiDbgHdr(); //if (dh.sig != -1 || dh.ver != 19990903) { // throw new PdbException("Unsupported DBI Stream version, sig={0}, ver={1}", // dh.sig, dh.ver); //} // Read gpmod section. ArrayList modList = new ArrayList(); int end = bits.Position + dh.gpmodiSize; while (bits.Position < end) { DbiModuleInfo mod = new DbiModuleInfo(bits, readStrings); modList.Add(mod); } if (bits.Position != end) { throw new PdbDebugException("Error reading DBI stream, pos={0} != {1}", bits.Position, end); } if (modList.Count > 0) { modules = (DbiModuleInfo[])modList.ToArray(typeof(DbiModuleInfo)); } else { modules = null; } // Skip the Section Contribution substream. bits.Position += dh.secconSize; // Skip the Section Map substream. bits.Position += dh.secmapSize; // Skip the File Info substream. bits.Position += dh.filinfSize; // Skip the TSM substream. bits.Position += dh.tsmapSize; // Skip the EC substream. bits.Position += dh.ecinfoSize; // Read the optional header. end = bits.Position + dh.dbghdrSize; if (dh.dbghdrSize > 0) { header = new DbiDbgHdr(bits); } bits.Position = end; } internal static PdbFunction[] LoadFunctions(Stream read, out Dictionary<uint, PdbTokenLine> tokenToSourceMapping, out string sourceServerData) { tokenToSourceMapping = new Dictionary<uint, PdbTokenLine>(); BitAccess bits = new BitAccess(512 * 1024); PdbFileHeader head = new PdbFileHeader(read, bits); PdbReader reader = new PdbReader(read, head.pageSize); MsfDirectory dir = new MsfDirectory(reader, head, bits); DbiModuleInfo[] modules = null; DbiDbgHdr header; dir.streams[1].Read(reader, bits); Dictionary<string, int> nameIndex = LoadNameIndex(bits); int nameStream; if (!nameIndex.TryGetValue("/NAMES", out nameStream)) { throw new PdbException("No `name' stream"); } dir.streams[nameStream].Read(reader, bits); IntHashTable names = LoadNameStream(bits); int srcsrvStream; if (!nameIndex.TryGetValue("SRCSRV", out srcsrvStream)) sourceServerData = string.Empty; else { DataStream dataStream = dir.streams[srcsrvStream]; byte[] bytes = new byte[dataStream.contentSize]; dataStream.Read(reader, bits); sourceServerData = bits.ReadBString(bytes.Length); } dir.streams[3].Read(reader, bits); LoadDbiStream(bits, out modules, out header, true); ArrayList funcList = new ArrayList(); if (modules != null) { for (int m = 0; m < modules.Length; m++) { var module = modules[m]; if (module.stream > 0) { dir.streams[module.stream].Read(reader, bits); if (module.moduleName == "TokenSourceLineInfo") { LoadTokenToSourceInfo(bits, module, names, dir, nameIndex, reader, tokenToSourceMapping); continue; } LoadFuncsFromDbiModule(bits, module, names, funcList, true, dir, nameIndex, reader); } } } PdbFunction[] funcs = (PdbFunction[])funcList.ToArray(typeof(PdbFunction)); // After reading the functions, apply the token remapping table if it exists. if (header.snTokenRidMap != 0 && header.snTokenRidMap != 0xffff) { dir.streams[header.snTokenRidMap].Read(reader, bits); uint[] ridMap = new uint[dir.streams[header.snTokenRidMap].Length / 4]; bits.ReadUInt32(ridMap); foreach (PdbFunction func in funcs) { func.token = 0x06000000 | ridMap[func.token & 0xffffff]; } } // Array.Sort(funcs, PdbFunction.byAddressAndToken); //Array.Sort(funcs, PdbFunction.byToken); return funcs; } private static void LoadTokenToSourceInfo(BitAccess bits, DbiModuleInfo module, IntHashTable names, MsfDirectory dir, Dictionary<string, int> nameIndex, PdbReader reader, Dictionary<uint, PdbTokenLine> tokenToSourceMapping) { bits.Position = 0; int sig; bits.ReadInt32(out sig); if (sig != 4) { throw new PdbDebugException("Invalid signature. (sig={0})", sig); } bits.Position = 4; while (bits.Position < module.cbSyms) { ushort siz; ushort rec; bits.ReadUInt16(out siz); int star = bits.Position; int stop = bits.Position + siz; bits.Position = star; bits.ReadUInt16(out rec); switch ((SYM)rec) { case SYM.S_OEM: OemSymbol oem; bits.ReadGuid(out oem.idOem); bits.ReadUInt32(out oem.typind); // internal byte[] rgl; // user data, force 4-byte alignment if (oem.idOem == PdbFunction.msilMetaData) { string name = bits.ReadString(); if (name == "TSLI") { uint token; uint file_id; uint line; uint column; uint endLine; uint endColumn; bits.ReadUInt32(out token); bits.ReadUInt32(out file_id); bits.ReadUInt32(out line); bits.ReadUInt32(out column); bits.ReadUInt32(out endLine); bits.ReadUInt32(out endColumn); PdbTokenLine tokenLine; if (!tokenToSourceMapping.TryGetValue(token, out tokenLine)) tokenToSourceMapping.Add(token, new PdbTokenLine(token, file_id, line, column, endLine, endColumn)); else { while (tokenLine.nextLine != null) tokenLine = tokenLine.nextLine; tokenLine.nextLine = new PdbTokenLine(token, file_id, line, column, endLine, endColumn); } } bits.Position = stop; break; } else { throw new PdbDebugException("OEM section: guid={0} ti={1}", oem.idOem, oem.typind); // bits.Position = stop; } case SYM.S_END: bits.Position = stop; break; default: //Console.WriteLine("{0,6}: {1:x2} {2}", // bits.Position, rec, (SYM)rec); bits.Position = stop; break; } } bits.Position = module.cbSyms + module.cbOldLines; int limit = module.cbSyms + module.cbOldLines + module.cbLines; IntHashTable sourceFiles = ReadSourceFileInfo(bits, (uint)limit, names, dir, nameIndex, reader); foreach (var tokenLine in tokenToSourceMapping.Values) { tokenLine.sourceFile = (PdbSource)sourceFiles[(int)tokenLine.file_id]; } } private static IntHashTable ReadSourceFileInfo(BitAccess bits, uint limit, IntHashTable names, MsfDirectory dir, Dictionary<string, int> nameIndex, PdbReader reader) { IntHashTable checks = new IntHashTable(); int begin = bits.Position; while (bits.Position < limit) { int sig; int siz; bits.ReadInt32(out sig); bits.ReadInt32(out siz); int place = bits.Position; int endSym = bits.Position + siz; switch ((DEBUG_S_SUBSECTION)sig) { case DEBUG_S_SUBSECTION.FILECHKSMS: while (bits.Position < endSym) { CV_FileCheckSum chk; int ni = bits.Position - place; bits.ReadUInt32(out chk.name); bits.ReadUInt8(out chk.len); bits.ReadUInt8(out chk.type); string name = (string)names[(int)chk.name]; int guidStream; Guid doctypeGuid = SymDocumentType.Text; Guid languageGuid = Guid.Empty; Guid vendorGuid = Guid.Empty; if (nameIndex.TryGetValue("/SRC/FILES/"+name.ToUpperInvariant(), out guidStream)) { var guidBits = new BitAccess(0x100); dir.streams[guidStream].Read(reader, guidBits); LoadGuidStream(guidBits, out doctypeGuid, out languageGuid, out vendorGuid); } PdbSource src = new PdbSource(/*(uint)ni,*/ name, doctypeGuid, languageGuid, vendorGuid); checks.Add(ni, src); bits.Position += chk.len; bits.Align(4); } bits.Position = endSym; break; default: bits.Position = endSym; break; } } return checks; } } }
// 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 Avalonia.Utilities; using System; using System.Globalization; using System.Linq; namespace Avalonia { /// <summary> /// Defines a rectangle. /// </summary> public struct Rect { /// <summary> /// An empty rectangle. /// </summary> public static readonly Rect Empty = default(Rect); /// <summary> /// The X position. /// </summary> private readonly double _x; /// <summary> /// The Y position. /// </summary> private readonly double _y; /// <summary> /// The width. /// </summary> private readonly double _width; /// <summary> /// The height. /// </summary> private readonly double _height; /// <summary> /// Initializes a new instance of the <see cref="Rect"/> structure. /// </summary> /// <param name="x">The X position.</param> /// <param name="y">The Y position.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public Rect(double x, double y, double width, double height) { _x = x; _y = y; _width = width; _height = height; } /// <summary> /// Initializes a new instance of the <see cref="Rect"/> structure. /// </summary> /// <param name="size">The size of the rectangle.</param> public Rect(Size size) { _x = 0; _y = 0; _width = size.Width; _height = size.Height; } /// <summary> /// Initializes a new instance of the <see cref="Rect"/> structure. /// </summary> /// <param name="position">The position of the rectangle.</param> /// <param name="size">The size of the rectangle.</param> public Rect(Point position, Size size) { _x = position.X; _y = position.Y; _width = size.Width; _height = size.Height; } /// <summary> /// Initializes a new instance of the <see cref="Rect"/> structure. /// </summary> /// <param name="topLeft">The top left position of the rectangle.</param> /// <param name="bottomRight">The bottom right position of the rectangle.</param> public Rect(Point topLeft, Point bottomRight) { _x = topLeft.X; _y = topLeft.Y; _width = bottomRight.X - topLeft.X; _height = bottomRight.Y - topLeft.Y; } /// <summary> /// Gets the X position. /// </summary> public double X => _x; /// <summary> /// Gets the Y position. /// </summary> public double Y => _y; /// <summary> /// Gets the width. /// </summary> public double Width => _width; /// <summary> /// Gets the height. /// </summary> public double Height => _height; /// <summary> /// Gets the position of the rectangle. /// </summary> public Point Position => new Point(_x, _y); /// <summary> /// Gets the size of the rectangle. /// </summary> public Size Size => new Size(_width, _height); /// <summary> /// Gets the right position of the rectangle. /// </summary> public double Right => _x + _width; /// <summary> /// Gets the bottom position of the rectangle. /// </summary> public double Bottom => _y + _height; /// <summary> /// Gets the top left point of the rectangle. /// </summary> public Point TopLeft => new Point(_x, _y); /// <summary> /// Gets the top right point of the rectangle. /// </summary> public Point TopRight => new Point(Right, _y); /// <summary> /// Gets the bottom left point of the rectangle. /// </summary> public Point BottomLeft => new Point(_x, Bottom); /// <summary> /// Gets the bottom right point of the rectangle. /// </summary> public Point BottomRight => new Point(Right, Bottom); /// <summary> /// Gets the center point of the rectangle. /// </summary> public Point Center => new Point(_x + (_width / 2), _y + (_height / 2)); /// <summary> /// Gets a value that indicates whether the rectangle is empty. /// </summary> public bool IsEmpty => _width == 0 && _height == 0; /// <summary> /// Checks for equality between two <see cref="Rect"/>s. /// </summary> /// <param name="left">The first rect.</param> /// <param name="right">The second rect.</param> /// <returns>True if the rects are equal; otherwise false.</returns> public static bool operator ==(Rect left, Rect right) { return left.Position == right.Position && left.Size == right.Size; } /// <summary> /// Checks for unequality between two <see cref="Rect"/>s. /// </summary> /// <param name="left">The first rect.</param> /// <param name="right">The second rect.</param> /// <returns>True if the rects are unequal; otherwise false.</returns> public static bool operator !=(Rect left, Rect right) { return !(left == right); } /// <summary> /// Multiplies a rectangle by a scaling vector. /// </summary> /// <param name="rect">The rectangle.</param> /// <param name="scale">The vector scale.</param> /// <returns>The scaled rectangle.</returns> public static Rect operator *(Rect rect, Vector scale) { return new Rect( rect.X * scale.X, rect.Y * scale.Y, rect.Width * scale.X, rect.Height * scale.Y); } /// <summary> /// Divides a rectangle by a vector. /// </summary> /// <param name="rect">The rectangle.</param> /// <param name="scale">The vector scale.</param> /// <returns>The scaled rectangle.</returns> public static Rect operator /(Rect rect, Vector scale) { return new Rect( rect.X / scale.X, rect.Y / scale.Y, rect.Width / scale.X, rect.Height / scale.Y); } /// <summary> /// Determines whether a point in in the bounds of the rectangle. /// </summary> /// <param name="p">The point.</param> /// <returns>true if the point is in the bounds of the rectangle; otherwise false.</returns> public bool Contains(Point p) { return p.X >= _x && p.X <= _x + _width && p.Y >= _y && p.Y <= _y + _height; } /// <summary> /// Determines whether the rectangle fully contains another rectangle. /// </summary> /// <param name="r">The rectangle.</param> /// <returns>true if the rectangle is fully contained; otherwise false.</returns> public bool Contains(Rect r) { return Contains(r.TopLeft) && Contains(r.BottomRight); } /// <summary> /// Centers another rectangle in this rectangle. /// </summary> /// <param name="rect">The rectangle to center.</param> /// <returns>The centered rectangle.</returns> public Rect CenterRect(Rect rect) { return new Rect( _x + ((_width - rect._width) / 2), _y + ((_height - rect._height) / 2), rect._width, rect._height); } /// <summary> /// Inflates the rectangle. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The inflated rectangle.</returns> public Rect Inflate(double thickness) { return Inflate(new Thickness(thickness)); } /// <summary> /// Inflates the rectangle. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The inflated rectangle.</returns> public Rect Inflate(Thickness thickness) { return new Rect( new Point(_x - thickness.Left, _y - thickness.Top), Size.Inflate(thickness)); } /// <summary> /// Deflates the rectangle. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The deflated rectangle.</returns> /// <remarks>The deflated rectangle size cannot be less than 0.</remarks> public Rect Deflate(double thickness) { return Deflate(new Thickness(thickness / 2)); } /// <summary> /// Deflates the rectangle by a <see cref="Thickness"/>. /// </summary> /// <param name="thickness">The thickness.</param> /// <returns>The deflated rectangle.</returns> /// <remarks>The deflated rectangle size cannot be less than 0.</remarks> public Rect Deflate(Thickness thickness) { return new Rect( new Point(_x + thickness.Left, _y + thickness.Top), Size.Deflate(thickness)); } /// <summary> /// Returns a boolean indicating whether the given object is equal to this rectangle. /// </summary> /// <param name="obj">The object to compare against.</param> /// <returns>True if the object is equal to this rectangle; false otherwise.</returns> public override bool Equals(object obj) { if (obj is Rect) { var other = (Rect)obj; return Position == other.Position && Size == other.Size; } return false; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = (hash * 23) + X.GetHashCode(); hash = (hash * 23) + Y.GetHashCode(); hash = (hash * 23) + Width.GetHashCode(); hash = (hash * 23) + Height.GetHashCode(); return hash; } } /// <summary> /// Gets the intersection of two rectangles. /// </summary> /// <param name="rect">The other rectangle.</param> /// <returns>The intersection.</returns> public Rect Intersect(Rect rect) { var newLeft = (rect.X > X) ? rect.X : X; var newTop = (rect.Y > Y) ? rect.Y : Y; var newRight = (rect.Right < Right) ? rect.Right : Right; var newBottom = (rect.Bottom < Bottom) ? rect.Bottom : Bottom; if ((newRight > newLeft) && (newBottom > newTop)) { return new Rect(newLeft, newTop, newRight - newLeft, newBottom - newTop); } else { return Empty; } } /// <summary> /// Determines whether a rectangle intersects with this rectangle. /// </summary> /// <param name="rect">The other rectangle.</param> /// <returns> /// True if the specified rectangle intersects with this one; otherwise false. /// </returns> public bool Intersects(Rect rect) { return (rect.X < Right) && (X < rect.Right) && (rect.Y < Bottom) && (Y < rect.Bottom); } /// <summary> /// Returns the axis-aligned bounding box of a transformed rectangle. /// </summary> /// <param name="matrix">The transform.</param> /// <returns>The bounding box</returns> public Rect TransformToAABB(Matrix matrix) { var points = new[] { TopLeft.Transform(matrix), TopRight.Transform(matrix), BottomRight.Transform(matrix), BottomLeft.Transform(matrix), }; var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { if (p.X < left) left = p.X; if (p.X > right) right = p.X; if (p.Y < top) top = p.Y; if (p.Y > bottom) bottom = p.Y; } return new Rect(new Point(left, top), new Point(right, bottom)); } /// <summary> /// Translates the rectangle by an offset. /// </summary> /// <param name="offset">The offset.</param> /// <returns>The translated rectangle.</returns> public Rect Translate(Vector offset) { return new Rect(Position + offset, Size); } /// <summary> /// Gets the union of two rectangles. /// </summary> /// <param name="rect">The other rectangle.</param> /// <returns>The union.</returns> public Rect Union(Rect rect) { if (IsEmpty) { return rect; } else if (rect.IsEmpty) { return this; } else { var x1 = Math.Min(this.X, rect.X); var x2 = Math.Max(this.Right, rect.Right); var y1 = Math.Min(this.Y, rect.Y); var y2 = Math.Max(this.Bottom, rect.Bottom); return new Rect(new Point(x1, y1), new Point(x2, y2)); } } /// <summary> /// Returns a new <see cref="Rect"/> with the specified X position. /// </summary> /// <param name="x">The x position.</param> /// <returns>The new <see cref="Rect"/>.</returns> public Rect WithX(double x) { return new Rect(x, _y, _width, _height); } /// <summary> /// Returns a new <see cref="Rect"/> with the specified Y position. /// </summary> /// <param name="y">The y position.</param> /// <returns>The new <see cref="Rect"/>.</returns> public Rect WithY(double y) { return new Rect(_x, y, _width, _height); } /// <summary> /// Returns a new <see cref="Rect"/> with the specified width. /// </summary> /// <param name="width">The width.</param> /// <returns>The new <see cref="Rect"/>.</returns> public Rect WithWidth(double width) { return new Rect(_x, _y, width, _height); } /// <summary> /// Returns a new <see cref="Rect"/> with the specified height. /// </summary> /// <param name="height">The height.</param> /// <returns>The new <see cref="Rect"/>.</returns> public Rect WithHeight(double height) { return new Rect(_x, _y, _width, height); } /// <summary> /// Returns the string representation of the rectangle. /// </summary> /// <returns>The string representation of the rectangle.</returns> public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "{0}, {1}, {2}, {3}", _x, _y, _width, _height); } /// <summary> /// Parses a <see cref="Rect"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The parsed <see cref="Rect"/>.</returns> public static Rect Parse(string s) { using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid Rect")) { return new Rect( tokenizer.ReadDouble(), tokenizer.ReadDouble(), tokenizer.ReadDouble(), tokenizer.ReadDouble() ); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { public abstract partial class PipeStream : Stream { // The Windows implementation of PipeStream sets the stream's handle during // creation, and as such should always have a handle, but the Unix implementation // sometimes sets the handle not during creation but later during connection. // As such, validation during member access needs to verify a valid handle on // Windows, but can't assume a valid handle on Unix. internal const bool CheckOperationsRequiresSetHandle = false; internal static string GetPipePath(string serverName, string pipeName) { if (serverName != "." && serverName != Interop.Sys.GetHostName()) { // Cross-machine pipes are not supported. throw new PlatformNotSupportedException(); } if (pipeName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { // Since pipes are stored as files in the file system, we don't support // pipe names that are actually paths or that otherwise have invalid // filename characters in them. throw new PlatformNotSupportedException(); } // Return the pipe path return Path.Combine(EnsurePipeDirectoryPath(), pipeName); } /// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { Interop.Sys.FileStatus status; int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status)); if (result == 0) { if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO) { throw new IOException(SR.IO_InvalidPipeHandle); } } } /// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> [SecurityCritical] private void InitializeAsyncHandle(SafePipeHandle handle) { // nop } private void UninitializeAsyncHandle() { // nop } private int ReadCore(byte[] buffer, int offset, int count) { return ReadCoreNoCancellation(buffer, offset, count); } private void WriteCore(byte[] buffer, int offset, int count) { WriteCoreNoCancellation(buffer, offset, count); } private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { SemaphoreSlim activeAsync = EnsureAsyncActiveSemaphoreInitialized(); await activeAsync.WaitAsync(cancellationToken).ForceAsync(); try { return cancellationToken.CanBeCanceled ? ReadCoreWithCancellation(buffer, offset, count, cancellationToken) : ReadCoreNoCancellation(buffer, offset, count); } finally { activeAsync.Release(); } } private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { SemaphoreSlim activeAsync = EnsureAsyncActiveSemaphoreInitialized(); await activeAsync.WaitAsync(cancellationToken).ForceAsync(); try { if (cancellationToken.CanBeCanceled) WriteCoreWithCancellation(buffer, offset, count, cancellationToken); else WriteCoreNoCancellation(buffer, offset, count); } finally { activeAsync.Release(); } } // Blocks until the other end of the pipe has read in all written buffer. [SecurityCritical] public void WaitForPipeDrain() { CheckWriteOperations(); if (!CanWrite) { throw Error.GetWriteNotSupported(); } throw new PlatformNotSupportedException(); // no mechanism for this on Unix } // Gets the transmission mode for the pipe. This is virtual so that subclassing types can // override this in cases where only one mode is legal (such as anonymous pipes) public virtual PipeTransmissionMode TransmissionMode { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } } // Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read // access. If that passes, call to GetNamedPipeInfo will succeed. public virtual int InBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { CheckPipePropertyOperations(); if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } return GetPipeBufferSize(); } } // Gets the buffer size in the outbound direction for the pipe. This uses cached version // if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe. // However, returning cached is good fallback, especially if user specified a value in // the ctor. public virtual int OutBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } return GetPipeBufferSize(); } } public virtual PipeTransmissionMode ReadMode { [SecurityCritical] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] set { CheckPipePropertyOperations(); if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg); } if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based { throw new PlatformNotSupportedException(); } // nop, since it's already the only valid value } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private static string s_pipeDirectoryPath; /// <summary> /// We want to ensure that only one asynchronous operation is actually in flight /// at a time. The base Stream class ensures this by serializing execution via a /// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due /// to having specialized support for cancellation, we do the same serialization here. /// </summary> private SemaphoreSlim _asyncActiveSemaphore; private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } private static string EnsurePipeDirectoryPath() { const string PipesFeatureName = "pipes"; // Ideally this would simply use PersistedFiles.GetTempFeatureDirectory(PipesFeatureName) and then // Directory.CreateDirectory to ensure it exists. But this assembly doesn't reference System.IO.FileSystem. // As such, we'd be calling GetTempFeatureDirectory, only to then need to parse it in order // to create each of the individual directories as part of the path. We instead access the named portions // of the path directly and do the building of the path and directory structure manually. // First ensure we know what the full path should be, e.g. /tmp/.dotnet/corefx/pipes/ string fullPath = s_pipeDirectoryPath; string tempPath = null; if (fullPath == null) { tempPath = Path.GetTempPath(); fullPath = Path.Combine(tempPath, PersistedFiles.TopLevelHiddenDirectory, PersistedFiles.SecondLevelDirectory, PipesFeatureName); s_pipeDirectoryPath = fullPath; } // Then create the directory if it doesn't already exist. If we get any error back from stat, // just proceed to build up the directory, failing in the CreateDirectory calls if there's some // problem. Similarly, it's possible stat succeeds but the path is a file rather than directory; we'll // call that success for now and let this fail later when the code tries to create a file in this "directory" // (we don't want to overwrite/delete whatever that unknown file may be, and this is similar to other cases // we can't control where the file system is manipulated concurrently with and separately from this code). Interop.Sys.FileStatus ignored; bool pathExists = Interop.Sys.Stat(fullPath, out ignored) == 0; if (!pathExists) { // We need to build up the directory manually. Ensure we have the temp directory in which // we'll create the structure, e.g. /tmp/ if (tempPath == null) { tempPath = Path.GetTempPath(); } Debug.Assert(Interop.Sys.Stat(tempPath, out ignored) == 0, "Path.GetTempPath() directory could not be accessed"); // Create /tmp/.dotnet/ if it doesn't exist. string partialPath = Path.Combine(tempPath, PersistedFiles.TopLevelHiddenDirectory); CreateDirectory(partialPath); // Create /tmp/.dotnet/corefx/ if it doesn't exist partialPath = Path.Combine(partialPath, PersistedFiles.SecondLevelDirectory); CreateDirectory(partialPath); // Create /tmp/.dotnet/corefx/pipes/ if it doesn't exist CreateDirectory(fullPath); } return fullPath; } private static void CreateDirectory(string directoryPath) { int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.S_IRWXU); // If successful created, we're done. if (result >= 0) return; // If the directory already exists, consider it a success. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EEXIST) return; // Otherwise, fail. throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true); } internal static Interop.Sys.OpenFlags TranslateFlags(PipeDirection direction, PipeOptions options, HandleInheritability inheritability) { // Translate direction Interop.Sys.OpenFlags flags = direction == PipeDirection.InOut ? Interop.Sys.OpenFlags.O_RDWR : direction == PipeDirection.Out ? Interop.Sys.OpenFlags.O_WRONLY : Interop.Sys.OpenFlags.O_RDONLY; // Translate options if ((options & PipeOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } // Translate inheritability. if ((inheritability & HandleInheritability.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // PipeOptions.Asynchronous is ignored, at least for now. Asynchronous processing // is handling just by queueing a work item to do the work synchronously on a pool thread. return flags; } private unsafe int ReadCoreNoCancellation(byte[] buffer, int offset, int count) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); fixed (byte* bufPtr = buffer) { int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr + offset, count)); Debug.Assert(result <= count); return result; } } private unsafe int ReadCoreWithCancellation(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); Debug.Assert(cancellationToken.CanBeCanceled, "ReadCoreNoCancellation should be used if cancellation can't happen"); // Register for a cancellation request. This will throw if cancellation has already been requested, // and otherwise will write to the cancellation pipe if/when cancellation has been requested. using (DescriptorCancellationRegistration cancellation = RegisterForCancellation(cancellationToken)) { bool gotRef = false; try { cancellation.Poll.DangerousAddRef(ref gotRef); fixed (byte* bufPtr = buffer) { // We want to wait for data to be available on either the pipe we want to read from // or on the cancellation pipe, which would signal a cancellation request. Interop.Sys.PollEvent* events = stackalloc Interop.Sys.PollEvent[2]; events[0] = new Interop.Sys.PollEvent { FileDescriptor = (int)_handle.DangerousGetHandle(), Events = Interop.Sys.PollEvents.POLLIN }; events[1] = new Interop.Sys.PollEvent { FileDescriptor = (int)cancellation.Poll.DangerousGetHandle(), Events = Interop.Sys.PollEvents.POLLIN }; // Some systems (at least OS X) appear to have a race condition in poll with FIFOs where the poll can // end up not noticing writes of greater than the internal buffer size. Restarting the poll causes it // to notice. To deal with that, we loop around poll, first starting with a small timeout and backing off // to a larger one. This ensures we'll at least eventually notice such changes in these corner // cases, while not adding too much overhead on systems that don't suffer from the problem. const int InitialMsTimeout = 30, MaxMsTimeout = 2000; for (int timeout = InitialMsTimeout; ; timeout = Math.Min(timeout * 2, MaxMsTimeout)) { // Do the poll. uint signaledFdCount; Interop.CheckIo(Interop.Sys.Poll(events, 2, timeout, &signaledFdCount)); cancellationToken.ThrowIfCancellationRequested(); if (signaledFdCount != 0) { // Our pipe is ready. Break out of the loop to read from it. Debug.Assert((events[0].TriggeredEvents & Interop.Sys.PollEvents.POLLIN) != 0, "Expected revents on read fd to have POLLIN set"); break; } } // Read it. Debug.Assert((events[0].TriggeredEvents & Interop.Sys.PollEvents.POLLIN) != 0); int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr + offset, count)); Debug.Assert(result <= count); Debug.Assert(result >= 0); // return what we read. return result; } } finally { if (gotRef) cancellation.Poll.DangerousRelease(); } } } private unsafe void WriteCoreNoCancellation(byte[] buffer, int offset, int count) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); fixed (byte* bufPtr = buffer) { while (count > 0) { int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr + offset, count)); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } } private void WriteCoreWithCancellation(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); // NOTE: // We currently ignore cancellationToken. Unlike on Windows, writes to pipes on Unix are likely to succeed // immediately, even if no reader is currently listening, as long as there's room in the kernel buffer. // However it's still possible for write to block if the buffer is full. We could try using a poll mechanism // like we do for read, but checking for POLLOUT is only going to tell us that there's room to write at least // one byte to the pipe, not enough room to write enough that we won't block. The only way to guarantee // that would seem to be writing one byte at a time, which has huge overheads when writing large chunks of data. // Given all this, at least for now we just do an initial check for cancellation and then call to the // non -cancelable version. cancellationToken.ThrowIfCancellationRequested(); WriteCoreNoCancellation(buffer, offset, count); } /// <summary>Creates an anonymous pipe.</summary> /// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param> /// <param name="reader">The resulting reader end of the pipe.</param> /// <param name="writer">The resulting writer end of the pipe.</param> internal static unsafe void CreateAnonymousPipe( HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer) { // Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations reader = new SafePipeHandle(); writer = new SafePipeHandle(); // Create the OS pipe int* fds = stackalloc int[2]; CreateAnonymousPipe(inheritability, fds); // Store the file descriptors into our safe handles reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]); writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]); } /// <summary> /// Creates a cancellation registration. This creates a pipe that'll have one end written to /// when cancellation is requested. The other end can be poll'd to see when cancellation has occurred. /// </summary> private static unsafe DescriptorCancellationRegistration RegisterForCancellation(CancellationToken cancellationToken) { Debug.Assert(cancellationToken.CanBeCanceled); // Fast path: before doing any real work, throw if cancellation has already been requested cancellationToken.ThrowIfCancellationRequested(); // Create a pipe we can use to send a signal to the reader/writer // to wake it up if blocked. SafePipeHandle poll, send; CreateAnonymousPipe(HandleInheritability.None, out poll, out send); // Register a cancellation callback to send a byte to the cancellation pipe CancellationTokenRegistration reg = cancellationToken.Register(s => { SafePipeHandle sendRef = (SafePipeHandle)s; byte b = 1; Interop.CheckIo(Interop.Sys.Write(sendRef, &b, 1)); }, send); // Return a disposable struct that will unregister the cancellation registration // and dispose of the pipe. return new DescriptorCancellationRegistration(reg, poll, send); } /// <summary>Disposable struct that'll clean up the results of a RegisterForCancellation operation.</summary> private struct DescriptorCancellationRegistration : IDisposable { private CancellationTokenRegistration _registration; private readonly SafePipeHandle _poll; private readonly SafePipeHandle _send; internal DescriptorCancellationRegistration( CancellationTokenRegistration registration, SafePipeHandle poll, SafePipeHandle send) { Debug.Assert(poll != null); Debug.Assert(send != null); _registration = registration; _poll = poll; _send = send; } internal SafePipeHandle Poll { get { return _poll; } } public void Dispose() { // Dispose the registration prior to disposing of the pipe handles. // Otherwise a concurrent cancellation request could try to use // the already disposed pipe. _registration.Dispose(); if (_send != null) _send.Dispose(); if (_poll != null) _poll.Dispose(); } } private int CheckPipeCall(int result) { if (result == -1) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EPIPE) State = PipeState.Broken; throw Interop.GetExceptionForIoErrno(errorInfo); } return result; } internal void InitializeBufferSize(SafePipeHandle handle, int bufferSize) { // bufferSize is just advisory and ignored if platform does not support setting pipe capacity via fcntl. if (bufferSize > 0 && Interop.Sys.Fcntl.CanGetSetPipeSz) { CheckPipeCall(Interop.Sys.Fcntl.SetPipeSz(handle, bufferSize)); } } private int GetPipeBufferSize() { if (!Interop.Sys.Fcntl.CanGetSetPipeSz) { throw new PlatformNotSupportedException(); } // If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction). // If we don't, the pipe has been created but not yet connected (in the case of named pipes), // so just return the buffer size that was passed to the constructor. return _handle != null ? CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) : _outBufferSize; } internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr) { var flags = (inheritability & HandleInheritability.Inheritable) == 0 ? Interop.Sys.PipeFlags.O_CLOEXEC : 0; Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags)); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands { /// <summary> /// Base class for all variable commands. /// /// Because -Scope is defined in VariableCommandBase, all derived commands /// must implement -Scope. /// </summary> public abstract class VariableCommandBase : PSCmdlet { #region Parameters /// <summary> /// Selects active scope to work with; used for all variable commands. /// </summary> [Parameter] [ValidateNotNullOrEmpty] public string Scope { get; set; } #endregion parameters /// <summary> /// The Include parameter for all the variable commands /// </summary> /// protected string[] IncludeFilters { get { return _include; } set { if (value == null) { value = new string[0]; } _include = value; } } private string[] _include = new string[0]; /// <summary> /// The Exclude parameter for all the variable commands /// </summary> /// protected string[] ExcludeFilters { get { return _exclude; } set { if (value == null) { value = new string[0]; } _exclude = value; } } private string[] _exclude = new string[0]; #region helpers /// <summary> /// Gets the matching variable for the specified name, using the /// Include, Exclude, and Scope parameters defined in the base class. /// </summary> /// /// <param name="name"> /// The name or pattern of the variables to retrieve. /// </param> /// /// <param name="lookupScope"> /// The scope to do the lookup in. If null or empty the normal scoping /// rules apply. /// </param> /// /// <param name="wasFiltered"> /// True is returned if a variable exists of the given name but was filtered /// out via globbing, include, or exclude. /// </param> /// /// <param name="quiet"> /// If true, don't report errors when trying to access private variables. /// </param> /// /// <returns> /// A collection of the variables matching the name, include, and exclude /// pattern in the specified scope. /// </returns> /// internal List<PSVariable> GetMatchingVariables(string name, string lookupScope, out bool wasFiltered, bool quiet) { wasFiltered = false; List<PSVariable> result = new List<PSVariable>(); if (String.IsNullOrEmpty(name)) { name = "*"; } bool nameContainsWildcard = WildcardPattern.ContainsWildcardCharacters(name); // Now create the filters WildcardPattern nameFilter = WildcardPattern.Get( name, WildcardOptions.IgnoreCase); Collection<WildcardPattern> includeFilters = SessionStateUtilities.CreateWildcardsFromStrings( _include, WildcardOptions.IgnoreCase); Collection<WildcardPattern> excludeFilters = SessionStateUtilities.CreateWildcardsFromStrings( _exclude, WildcardOptions.IgnoreCase); if (!nameContainsWildcard) { // Filter the name here against the include and exclude so that // we can report if the name was filtered vs. there being no // variable existing of that name. bool isIncludeMatch = SessionStateUtilities.MatchesAnyWildcardPattern( name, includeFilters, true); bool isExcludeMatch = SessionStateUtilities.MatchesAnyWildcardPattern( name, excludeFilters, false); if (!isIncludeMatch || isExcludeMatch) { wasFiltered = true; return result; } } // First get the appropriate view of the variables. If no scope // is specified, flatten all scopes to produce a currently active // view. IDictionary<string, PSVariable> variableTable = null; if (String.IsNullOrEmpty(lookupScope)) { variableTable = SessionState.Internal.GetVariableTable(); } else { variableTable = SessionState.Internal.GetVariableTableAtScope(lookupScope); } CommandOrigin origin = MyInvocation.CommandOrigin; foreach (KeyValuePair<string, PSVariable> entry in variableTable) { bool isNameMatch = nameFilter.IsMatch(entry.Key); bool isIncludeMatch = SessionStateUtilities.MatchesAnyWildcardPattern( entry.Key, includeFilters, true); bool isExcludeMatch = SessionStateUtilities.MatchesAnyWildcardPattern( entry.Key, excludeFilters, false); if (isNameMatch) { if (isIncludeMatch && !isExcludeMatch) { // See if the variable is visible if (!SessionState.IsVisible(origin, entry.Value)) { // In quiet mode, don't report private variable accesses unless they are specific matches... if (quiet || nameContainsWildcard) { wasFiltered = true; continue; } else { // Generate an error for elements that aren't visible... try { SessionState.ThrowIfNotVisible(origin, entry.Value); } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); // Only report the error once... wasFiltered = true; continue; } } } result.Add(entry.Value); } else { wasFiltered = true; } } else { if (nameContainsWildcard) { wasFiltered = true; } } } return result; } #endregion helpers } /// <summary> /// Implements get-variable command. /// </summary> [Cmdlet(VerbsCommon.Get, "Variable", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113336")] [OutputType(typeof(PSVariable))] public class GetVariableCommand : VariableCommandBase { #region parameters /// <summary> /// Name of the PSVariable /// </summary> [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public string[] Name { get { return _name; } set { if (value == null) { value = new string[] { "*" }; } _name = value; } } private string[] _name = new string[] { "*" }; /// <summary> /// Output only the value(s) of the requested variable(s). /// </summary> [Parameter] public SwitchParameter ValueOnly { get { return _valueOnly; } set { _valueOnly = value; } } private bool _valueOnly; /// <summary> /// The Include parameter for all the variable commands /// </summary> /// [Parameter] public string[] Include { get { return IncludeFilters; } set { IncludeFilters = value; } } /// <summary> /// The Exclude parameter for all the variable commands /// </summary> /// [Parameter] public string[] Exclude { get { return ExcludeFilters; } set { ExcludeFilters = value; } } #endregion parameters /// <summary> /// Implements ProcessRecord() method for get-variabit's le command. /// </summary> protected override void ProcessRecord() { foreach (string varName in _name) { bool wasFiltered = false; List<PSVariable> matchingVariables = GetMatchingVariables(varName, Scope, out wasFiltered, /*quiet*/ false); matchingVariables.Sort( delegate (PSVariable left, PSVariable right) { return StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name); }); bool matchFound = false; foreach (PSVariable matchingVariable in matchingVariables) { matchFound = true; if (_valueOnly) { WriteObject(matchingVariable.Value); } else { WriteObject(matchingVariable); } } if (!matchFound && !wasFiltered) { ItemNotFoundException itemNotFound = new ItemNotFoundException( varName, "VariableNotFound", SessionStateStrings.VariableNotFound); WriteError( new ErrorRecord( itemNotFound.ErrorRecord, itemNotFound)); } } } } /// <summary> /// Class implementing new-variable command /// </summary> [Cmdlet(VerbsCommon.New, "Variable", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113361")] public sealed class NewVariableCommand : VariableCommandBase { #region parameters /// <summary> /// Name of the PSVariable /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)] public string Name { get; set; } /// <summary> /// Value of the PSVariable /// </summary> [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public object Value { get; set; } /// <summary> /// Description of the variable /// </summary> [Parameter] public string Description { get; set; } /// <summary> /// The options for the variable to specify if the variable should /// be ReadOnly, Constant, and/or Private. /// </summary> /// [Parameter] public ScopedItemOptions Option { get; set; } = ScopedItemOptions.None; /// <summary> /// Specifies the visiblity of the new variable... /// </summary> [Parameter] public SessionStateEntryVisibility Visibility { get { return (SessionStateEntryVisibility)_visibility; } set { _visibility = value; } } private SessionStateEntryVisibility? _visibility; /// <summary> /// Force the operation to make the best attempt at setting the variable. /// </summary> [Parameter] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// The variable object should be passed down the pipeline. /// </summary> [Parameter] public SwitchParameter PassThru { get { return _passThru; } set { _passThru = value; } } private bool _passThru; #endregion parameters /// <summary> /// Add objects received on the pipeline to an ArrayList of values, to /// take the place of the Value parameter if none was specified on the /// command line. /// </summary> /// protected override void ProcessRecord() { // If Force is not specified, see if the variable already exists // in the specified scope. If the scope isn't specified, then // check to see if it exists in the current scope. if (!Force) { PSVariable varFound = null; if (String.IsNullOrEmpty(Scope)) { varFound = SessionState.PSVariable.GetAtScope(Name, "local"); } else { varFound = SessionState.PSVariable.GetAtScope(Name, Scope); } if (varFound != null) { SessionStateException sessionStateException = new SessionStateException( Name, SessionStateCategory.Variable, "VariableAlreadyExists", SessionStateStrings.VariableAlreadyExists, ErrorCategory.ResourceExists); WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); return; } } // Since the variable doesn't exist or -Force was specified, // Call should process to validate the set with the user. string action = VariableCommandStrings.NewVariableAction; string target = StringUtil.Format(VariableCommandStrings.NewVariableTarget, Name, Value); if (ShouldProcess(target, action)) { PSVariable newVariable = new PSVariable(Name, Value, Option); if (_visibility != null) { newVariable.Visibility = (SessionStateEntryVisibility)_visibility; } if (Description != null) { newVariable.Description = Description; } try { if (String.IsNullOrEmpty(Scope)) { SessionState.Internal.NewVariable(newVariable, Force); } else { SessionState.Internal.NewVariableAtScope(newVariable, Scope, Force); } } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); return; } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); return; } if (_passThru) { WriteObject(newVariable); } } } // ProcessRecord } // NewVariableCommand /// <summary> /// This class implements set-variable command /// </summary> [Cmdlet(VerbsCommon.Set, "Variable", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113401")] [OutputType(typeof(PSVariable))] public sealed class SetVariableCommand : VariableCommandBase { #region parameters /// <summary> /// Name of the PSVariable(s) to set /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)] public string[] Name { get; set; } /// <summary> /// Value of the PSVariable /// </summary> [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public object Value { get; set; } = AutomationNull.Value; /// <summary> /// The Include parameter for all the variable commands /// </summary> /// [Parameter] public string[] Include { get { return IncludeFilters; } set { IncludeFilters = value; } } /// <summary> /// The Exclude parameter for all the variable commands /// </summary> /// [Parameter] public string[] Exclude { get { return ExcludeFilters; } set { ExcludeFilters = value; } } /// <summary> /// Description of the variable /// </summary> [Parameter] public string Description { get; set; } /// <summary> /// The options for the variable to specify if the variable should /// be ReadOnly, Constant, and/or Private. /// </summary> /// [Parameter] public ScopedItemOptions Option { get { return (ScopedItemOptions)_options; } set { _options = value; } } private Nullable<ScopedItemOptions> _options; /// <summary> /// Force the operation to make the best attempt at setting the variable. /// </summary> [Parameter] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Sets the visibility of the variable... /// </summary> [Parameter] public SessionStateEntryVisibility Visibility { get { return (SessionStateEntryVisibility)_visibility; } set { _visibility = value; } } private SessionStateEntryVisibility? _visibility; /// <summary> /// The variable object should be passed down the pipeline. /// </summary> [Parameter] public SwitchParameter PassThru { get { return _passThru; } set { _passThru = value; } } private bool _passThru; private bool _nameIsFormalParameter; private bool _valueIsFormalParameter; #endregion parameters /// <summary> /// Checks to see if the name and value parameters were /// bound as formal parameters. /// </summary> protected override void BeginProcessing() { if (Name != null && Name.Length > 0) { _nameIsFormalParameter = true; } if (Value != AutomationNull.Value) { _valueIsFormalParameter = true; } } /// <summary> /// If name and value are both specified as a formal parameters, then /// just ignore the incoming objects in ProcessRecord. /// If name is a formal parameter but the value is coming from the pipeline, /// then accumulate the values in the valueList and set the variable during /// EndProcessing(). /// If name is not a formal parameter, then set /// the variable each time ProcessRecord is called. /// </summary> /// protected override void ProcessRecord() { if (_nameIsFormalParameter && _valueIsFormalParameter) { return; } if (_nameIsFormalParameter && !_valueIsFormalParameter) { if (Value != AutomationNull.Value) { if (_valueList == null) { _valueList = new ArrayList(); } _valueList.Add(Value); } } else { SetVariable(Name, Value); } } private ArrayList _valueList; /// <summary> /// Sets the variable if the name was specified as a formal parameter /// but the value came from the pipeline. /// </summary> protected override void EndProcessing() { if (_nameIsFormalParameter) { if (_valueIsFormalParameter) { SetVariable(Name, Value); } else { if (_valueList != null) { if (_valueList.Count == 1) { SetVariable(Name, _valueList[0]); } else if (_valueList.Count == 0) { SetVariable(Name, AutomationNull.Value); } else { SetVariable(Name, _valueList.ToArray()); } } else { SetVariable(Name, AutomationNull.Value); } } } } /// <summary> /// Sets the variables of the given names to the specified value. /// </summary> /// /// <param name="varNames"> /// The name(s) of the variables to set. /// </param> /// /// <param name="varValue"> /// The value to set the variable to. /// </param> /// private void SetVariable(string[] varNames, object varValue) { CommandOrigin origin = MyInvocation.CommandOrigin; foreach (string varName in varNames) { // First look for existing variables to set. List<PSVariable> matchingVariables = new List<PSVariable>(); bool wasFiltered = false; if (!String.IsNullOrEmpty(Scope)) { // We really only need to find matches if the scope was specified. // If the scope wasn't specified then we need to create the // variable in the local scope. matchingVariables = GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false); } else { // Since the scope wasn't specified, it doesn't matter if there // is a variable in another scope, it only matters if there is a // variable in the local scope. matchingVariables = GetMatchingVariables( varName, System.Management.Automation.StringLiterals.Local, out wasFiltered, false); } // We only want to create the variable if we are not filtering // the name. if (matchingVariables.Count == 0 && !wasFiltered) { try { ScopedItemOptions newOptions = ScopedItemOptions.None; if (!String.IsNullOrEmpty(Scope) && String.Equals("private", Scope, StringComparison.OrdinalIgnoreCase)) { newOptions = ScopedItemOptions.Private; } if (_options != null) { newOptions |= (ScopedItemOptions)_options; } object newVarValue = varValue; if (newVarValue == AutomationNull.Value) { newVarValue = null; } PSVariable varToSet = new PSVariable( varName, newVarValue, newOptions); if (Description == null) { Description = String.Empty; } varToSet.Description = Description; // If visiblity was specified, set it on the variable if (_visibility != null) { varToSet.Visibility = Visibility; } string action = VariableCommandStrings.SetVariableAction; string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, varName, newVarValue); if (ShouldProcess(target, action)) { object result = null; if (String.IsNullOrEmpty(Scope)) { result = SessionState.Internal.SetVariable(varToSet, Force, origin); } else { result = SessionState.Internal.SetVariableAtScope(varToSet, Scope, Force, origin); } if (_passThru && result != null) { WriteObject(result); } } } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); continue; } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); continue; } } else { foreach (PSVariable matchingVariable in matchingVariables) { string action = VariableCommandStrings.SetVariableAction; string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, matchingVariable.Name, varValue); if (ShouldProcess(target, action)) { object result = null; try { // Since the variable existed in the specified scope, or // in the local scope if no scope was specified, use // the reference returned to set the variable properties. // If we want to force setting over a readonly variable // we have to temporarily mark the variable writable. bool wasReadOnly = false; if (Force && (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0) { matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true); wasReadOnly = true; } // Now change the value, options, or description // and set the variable if (varValue != AutomationNull.Value) { matchingVariable.Value = varValue; } if (Description != null) { matchingVariable.Description = Description; } if (_options != null) { matchingVariable.Options = (ScopedItemOptions)_options; } else { if (wasReadOnly) { matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true); } } // If visiblity was specified, set it on the variable if (_visibility != null) { matchingVariable.Visibility = Visibility; } result = matchingVariable; } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); continue; } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); continue; } if (_passThru && result != null) { WriteObject(result); } } } } } } // ProcessRecord } // SetVariableCommand /// <summary> /// The Remove-Variable cmdlet implementation /// </summary> [Cmdlet(VerbsCommon.Remove, "Variable", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113380")] public sealed class RemoveVariableCommand : VariableCommandBase { #region parameters /// <summary> /// Name of the PSVariable(s) to set /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)] public string[] Name { get; set; } /// <summary> /// The Include parameter for all the variable commands /// </summary> /// [Parameter] public string[] Include { get { return IncludeFilters; } set { IncludeFilters = value; } } /// <summary> /// The Exclude parameter for all the variable commands /// </summary> /// [Parameter] public string[] Exclude { get { return ExcludeFilters; } set { ExcludeFilters = value; } } /// <summary> /// If true, the variable is removed even if it is ReadOnly /// </summary> /// [Parameter] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; #endregion parameters /// <summary> /// Removes the matching variables from the specified scope /// </summary> /// protected override void ProcessRecord() { // Removal of variables only happens in the local scope if the // scope wasn't explicitly specified by the user. if (Scope == null) { Scope = "local"; } foreach (string varName in Name) { // First look for existing variables to set. bool wasFiltered = false; List<PSVariable> matchingVariables = GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false); if (matchingVariables.Count == 0 && !wasFiltered) { // Since the variable wasn't found and no glob // characters were specified, write an error. ItemNotFoundException itemNotFound = new ItemNotFoundException( varName, "VariableNotFound", SessionStateStrings.VariableNotFound); WriteError( new ErrorRecord( itemNotFound.ErrorRecord, itemNotFound)); continue; } foreach (PSVariable matchingVariable in matchingVariables) { // Since the variable doesn't exist or -Force was specified, // Call should process to validate the set with the user. string action = VariableCommandStrings.RemoveVariableAction; string target = StringUtil.Format(VariableCommandStrings.RemoveVariableTarget, matchingVariable.Name); if (ShouldProcess(target, action)) { try { if (String.IsNullOrEmpty(Scope)) { SessionState.Internal.RemoveVariable(matchingVariable, _force); } else { SessionState.Internal.RemoveVariableAtScope(matchingVariable, Scope, _force); } } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); } } } } } // ProcessRecord } // RemoveVariableCommand /// <summary> /// This class implements set-variable command /// </summary> [Cmdlet(VerbsCommon.Clear, "Variable", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113285")] [OutputType(typeof(PSVariable))] public sealed class ClearVariableCommand : VariableCommandBase { #region parameters /// <summary> /// Name of the PSVariable(s) to set /// </summary> [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)] public string[] Name { get; set; } /// <summary> /// The Include parameter for all the variable commands /// </summary> /// [Parameter] public string[] Include { get { return IncludeFilters; } set { IncludeFilters = value; } } /// <summary> /// The Exclude parameter for all the variable commands /// </summary> /// [Parameter] public string[] Exclude { get { return ExcludeFilters; } set { ExcludeFilters = value; } } /// <summary> /// Force the operation to make the best attempt at clearing the variable. /// </summary> [Parameter] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// The variable object should be passed down the pipeline. /// </summary> [Parameter] public SwitchParameter PassThru { get { return _passThru; } set { _passThru = value; } } private bool _passThru; #endregion parameters /// <summary> /// The implementation of the Clear-Variable command /// </summary> /// protected override void ProcessRecord() { foreach (string varName in Name) { bool wasFiltered = false; List<PSVariable> matchingVariables = GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false); if (matchingVariables.Count == 0 && !wasFiltered) { // Since the variable wasn't found and no glob // characters were specified, write an error. ItemNotFoundException itemNotFound = new ItemNotFoundException( varName, "VariableNotFound", SessionStateStrings.VariableNotFound); WriteError( new ErrorRecord( itemNotFound.ErrorRecord, itemNotFound)); continue; } foreach (PSVariable matchingVariable in matchingVariables) { // Since the variable doesn't exist or -Force was specified, // Call should process to validate the set with the user. string action = VariableCommandStrings.ClearVariableAction; string target = StringUtil.Format(VariableCommandStrings.ClearVariableTarget, matchingVariable.Name); if (ShouldProcess(target, action)) { PSVariable result = matchingVariable; try { if (_force && (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0) { // Remove the ReadOnly bit to set the value and then reapply matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true); result = ClearValue(matchingVariable); matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true); } else { result = ClearValue(matchingVariable); } } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); continue; } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); continue; } if (_passThru) { WriteObject(result); } } } } } // ProcessRecord /// <summary> /// Clears the value of the variable using the PSVariable instance if the scope /// was specified or using standard variable lookup if the scope was not specified. /// </summary> /// /// <param name="matchingVariable"> /// The variable that matched the name parameter(s). /// </param> /// private PSVariable ClearValue(PSVariable matchingVariable) { PSVariable result = matchingVariable; if (Scope != null) { matchingVariable.Value = null; } else { SessionState.PSVariable.Set(matchingVariable.Name, null); result = SessionState.PSVariable.Get(matchingVariable.Name); } return result; } } // ClearVariableCommand }
// This file was generated by St4mpede.Surface 2016-06-09 22:41:54Z. namespace TheDal.Surface { using System; using System.Collections.Generic; using System.Linq; using Dapper; /// <summary> This is the Surface for the User table. /// </summary> public class UserSurface { public UserSurface() { } /// <summary> This method is used for adding a new record in the database. /// <para>St4mpede guid:{BC89740A-CBA5-4EDE-BFF4-9B0D8BA4058F}</para> /// </summary> private TheDAL.Poco.User Add( TheDAL.CommitScope context, System.String userName, System.String hashedPassword, System.DateTime lastLoggedOnDatetime ) { return Add( context, new TheDAL.Poco.User( 0, userName, hashedPassword, lastLoggedOnDatetime )); } /// <summary> This method is used for adding a new record in the database. /// <para>St4mpede guid:{759FBA46-A462-4E4A-BA2B-9B5AFDA572DE}</para> /// </summary> private TheDAL.Poco.User Add( TheDAL.CommitScope context, TheDAL.Poco.User user ) { const string Sql = @" Insert Into User ( UserName, HashedPassword, LastLoggedOnDatetime ) Values ( @UserName, @HashedPassword, @LastLoggedOnDatetime ) Select * From User Where UserId = Scope_Identity()"; var ret = context.Connection.Query<TheDAL.Poco.User>( Sql, new { userId = user.UserId }, context.Transaction, false, null, null); return ret.Single(); } /// <summary> This method is used for deleting a record. /// <para>St4mpede guid:{F74246AE-0295-4094-AA7F-1D118C11229D}</para> /// </summary> public void Delete( TheDAL.CommitScope context, TheDAL.Poco.User user ) { DeleteById( context, user.UserId); } /// <summary> This method is used for deleting a record by its primary key. /// <para>St4mpede guid:{F0137E62-1D45-4B92-A48E-05954850FFE8}</para> /// </summary> public void DeleteById( TheDAL.CommitScope context, System.Int32 userId ) { const string Sql = @" Delete From User Where UserId = @userId "; context.Connection.Execute( Sql, new { userId = userId }, context.Transaction, null, null); } /// <summary> This method returns every record for this table/surface. /// Do not use it on too big tables. /// <para>St4mpede guid:{4A910A99-9A50-4977-B2A2-404240CDDC73}</para> /// </summary> public IList<TheDAL.Poco.User> GetAll( TheDAL.CommitScope context ) { const string Sql = @" Select * From User "; var res = context.Connection.Query<TheDAL.Poco.User>( Sql, null, context.Transaction, false, null, null); return res.ToList(); } /// <summary> This method is used for getting a record but its Id/primary key. /// If nothing is found an exception is thrown. If you want to get null back use LoadById <see cref="LoadById"/> instead. /// <para>St4mpede guid:{71CF185E-0DD1-4FAE-9721-920B5C3C12D9}</para> /// </summary> public TheDAL.Poco.User GetById( TheDAL.CommitScope context, System.Int32 userId ) { const string Sql = @" Select * From User Where UserId = @userId "; var res = context.Connection.Query<TheDAL.Poco.User>( Sql, new { userId = userId }, context.Transaction, false, null, null); return res.Single(); } /// <summary> This method is used for getting a record but its Id/primary key. /// If nothing is found an null is returned. If you want to throw an exception use GetById <see cref="GetById"> instead. /// <para>St4mpede guid:{BC171F29-81F2-41ED-AC5C-AD6884EC9718}</para> /// </summary> public TheDAL.Poco.User LoadById( TheDAL.CommitScope context, System.Int32 userId ) { const string Sql = @" Select * From User Where UserId = @userId "; var res = context.Connection.Query<TheDAL.Poco.User>( Sql, new { userId = userId }, context.Transaction, false, null, null); return res.SingleOrDefault(); } /// <summary> This method is used for updating an existing record in the database. /// <para>St4mpede guid:{5A4CE926-447C-4F3F-ADFC-8CA9229C60BF}</para> /// </summary> private TheDAL.Poco.User Update( TheDAL.CommitScope context, System.Int32 userId, System.String userName, System.String hashedPassword, System.DateTime lastLoggedOnDatetime ) { return Update( context, new TheDAL.Poco.User( userId, userName, hashedPassword, lastLoggedOnDatetime )); } /// <summary> This method is used for updating an existing record in the database. /// <para>St4mpede guid:{B2B1B845-5F93-4A5C-9F90-FBA570228542}</para> /// </summary> private TheDAL.Poco.User Update( TheDAL.CommitScope context, TheDAL.Poco.User user ) { const string Sql = @" Update User Set UserName = @userName, HashedPassword = @hashedPassword, LastLoggedOnDatetime = @lastLoggedOnDatetime Where UserId = @UserId Select * From User Where UserId = $userId "; var ret = context.Connection.Query<TheDAL.Poco.User>( Sql, new { userId = user.UserId, userName = user.UserName, hashedPassword = user.HashedPassword, lastLoggedOnDatetime = user.LastLoggedOnDatetime }, context.Transaction, false, null, null); return ret.Single(); } /// <summary> This method is used for creating a new or updating an existing record in the database. /// If the primary key is 0 (zero) we know it is a new record and try to add it. Otherwise we try to update the record. /// <para>St4mpede guid:{A821E709-7333-4ABA-9F38-E85617C906FE}</para> /// </summary> public TheDAL.Poco.User Upsert( TheDAL.CommitScope context, System.Int32 userId, System.String userName, System.String hashedPassword, System.DateTime lastLoggedOnDatetime ) { return Upsert( context, new TheDAL.Poco.User( userId, userName, hashedPassword, lastLoggedOnDatetime )); } /// <summary> This method is used for creating a new or updating an existing record in the database. /// If the primary key is default value (typically null or zero) we know it is a new record and try to add it. Otherwise we try to update the record. /// <para>St4mpede guid:{97D67E96-7C3E-4D8B-8984-104896646077}</para> /// </summary> public TheDAL.Poco.User Upsert( TheDAL.CommitScope context, TheDAL.Poco.User user ) { if(user.UserId == default(System.Int32)){ return Add(context, user); }else{ return Update(context, user); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryModuloTests { #region Test methods [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void CheckByteModuloTest() { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteModulo(array[i], array[j]); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void CheckSByteModuloTest() { 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++) { VerifySByteModulo(array[i], array[j]); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckUShortModuloTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckShortModuloTest(bool useInterpreter) { 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++) { VerifyShortModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckUIntModuloTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckIntModuloTest(bool useInterpreter) { 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++) { VerifyIntModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckULongModuloTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongModulo(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLongModuloTest(bool useInterpreter) { 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++) { VerifyLongModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckFloatModuloTest(bool useInterpreter) { 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++) { VerifyFloatModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDoubleModuloTest(bool useInterpreter) { 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++) { VerifyDoubleModulo(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDecimalModuloTest(bool useInterpreter) { 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++) { VerifyDecimalModulo(array[i], array[j], useInterpreter); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void CheckCharModuloTest() { char[] array = new char[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyCharModulo(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyByteModulo(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 VerifySByteModulo(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 VerifyUShortModulo(ushort a, ushort b, bool useInterpreter) { 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(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyShortModulo(short a, short b, bool useInterpreter) { 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(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyUIntModulo(uint a, uint b, bool useInterpreter) { 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(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyIntModulo(int a, int b, bool useInterpreter) { 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(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == int.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyULongModulo(ulong a, ulong b, bool useInterpreter) { 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(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyLongModulo(long a, long b, bool useInterpreter) { 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(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == long.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyFloatModulo(float a, float b, bool useInterpreter) { 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(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyDoubleModulo(double a, double b, bool useInterpreter) { 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(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyDecimalModulo(decimal a, decimal b, bool useInterpreter) { 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(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyCharModulo(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 [Fact] public static void CannotReduce() { Expression exp = Expression.Modulo(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.Modulo(null, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.Modulo(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.Modulo(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.Modulo(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { BinaryExpression e = Expression.Modulo(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a % b)", e.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Cache; using System.Net.Sockets; using System.Security; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net { internal enum FtpOperation { DownloadFile = 0, ListDirectory = 1, ListDirectoryDetails = 2, UploadFile = 3, UploadFileUnique = 4, AppendFile = 5, DeleteFile = 6, GetDateTimestamp = 7, GetFileSize = 8, Rename = 9, MakeDirectory = 10, RemoveDirectory = 11, PrintWorkingDirectory = 12, Other = 13, } [Flags] internal enum FtpMethodFlags { None = 0x0, IsDownload = 0x1, IsUpload = 0x2, TakesParameter = 0x4, MayTakeParameter = 0x8, DoesNotTakeParameter = 0x10, ParameterIsDirectory = 0x20, ShouldParseForResponseUri = 0x40, HasHttpCommand = 0x80, MustChangeWorkingDirectoryToPath = 0x100 } internal class FtpMethodInfo { internal string Method; internal FtpOperation Operation; internal FtpMethodFlags Flags; internal string HttpCommand; internal FtpMethodInfo(string method, FtpOperation operation, FtpMethodFlags flags, string httpCommand) { Method = method; Operation = operation; Flags = flags; HttpCommand = httpCommand; } internal bool HasFlag(FtpMethodFlags flags) { return (Flags & flags) != 0; } internal bool IsCommandOnly { get { return (Flags & (FtpMethodFlags.IsDownload | FtpMethodFlags.IsUpload)) == 0; } } internal bool IsUpload { get { return (Flags & FtpMethodFlags.IsUpload) != 0; } } internal bool IsDownload { get { return (Flags & FtpMethodFlags.IsDownload) != 0; } } /// <summary> /// <para>True if we should attempt to get a response uri /// out of a server response</para> /// </summary> internal bool ShouldParseForResponseUri { get { return (Flags & FtpMethodFlags.ShouldParseForResponseUri) != 0; } } internal static FtpMethodInfo GetMethodInfo(string method) { method = method.ToUpper(CultureInfo.InvariantCulture); foreach (FtpMethodInfo methodInfo in s_knownMethodInfo) if (method == methodInfo.Method) return methodInfo; // We don't support generic methods throw new ArgumentException(SR.net_ftp_unsupported_method, nameof(method)); } private static readonly FtpMethodInfo[] s_knownMethodInfo = { new FtpMethodInfo(WebRequestMethods.Ftp.DownloadFile, FtpOperation.DownloadFile, FtpMethodFlags.IsDownload | FtpMethodFlags.HasHttpCommand | FtpMethodFlags.TakesParameter, "GET"), new FtpMethodInfo(WebRequestMethods.Ftp.ListDirectory, FtpOperation.ListDirectory, FtpMethodFlags.IsDownload | FtpMethodFlags.MustChangeWorkingDirectoryToPath | FtpMethodFlags.HasHttpCommand | FtpMethodFlags.MayTakeParameter, "GET"), new FtpMethodInfo(WebRequestMethods.Ftp.ListDirectoryDetails, FtpOperation.ListDirectoryDetails, FtpMethodFlags.IsDownload | FtpMethodFlags.MustChangeWorkingDirectoryToPath | FtpMethodFlags.HasHttpCommand | FtpMethodFlags.MayTakeParameter, "GET"), new FtpMethodInfo(WebRequestMethods.Ftp.UploadFile, FtpOperation.UploadFile, FtpMethodFlags.IsUpload | FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.UploadFileWithUniqueName, FtpOperation.UploadFileUnique, FtpMethodFlags.IsUpload | FtpMethodFlags.MustChangeWorkingDirectoryToPath | FtpMethodFlags.DoesNotTakeParameter | FtpMethodFlags.ShouldParseForResponseUri, null), new FtpMethodInfo(WebRequestMethods.Ftp.AppendFile, FtpOperation.AppendFile, FtpMethodFlags.IsUpload | FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.DeleteFile, FtpOperation.DeleteFile, FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.GetDateTimestamp, FtpOperation.GetDateTimestamp, FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.GetFileSize, FtpOperation.GetFileSize, FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.Rename, FtpOperation.Rename, FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.MakeDirectory, FtpOperation.MakeDirectory, FtpMethodFlags.TakesParameter | FtpMethodFlags.ParameterIsDirectory, null), new FtpMethodInfo(WebRequestMethods.Ftp.RemoveDirectory, FtpOperation.RemoveDirectory, FtpMethodFlags.TakesParameter | FtpMethodFlags.ParameterIsDirectory, null), new FtpMethodInfo(WebRequestMethods.Ftp.PrintWorkingDirectory, FtpOperation.PrintWorkingDirectory, FtpMethodFlags.DoesNotTakeParameter, null) }; } /// <summary> /// <para>The FtpWebRequest class implements a basic FTP client interface. /// </summary> public sealed class FtpWebRequest : WebRequest { private object _syncObject; private ICredentials _authInfo; private readonly Uri _uri; private FtpMethodInfo _methodInfo; private string _renameTo = null; private bool _getRequestStreamStarted; private bool _getResponseStarted; private DateTime _startTime; private int _timeout = s_DefaultTimeout; private int _remainingTimeout; private long _contentLength = 0; private long _contentOffset = 0; private X509CertificateCollection _clientCertificates; private bool _passive = true; private bool _binary = true; private string _connectionGroupName; private ServicePoint _servicePoint; private bool _async; private bool _aborted; private bool _timedOut; private Exception _exception; private TimerThread.Queue _timerQueue = s_DefaultTimerQueue; private TimerThread.Callback _timerCallback; private bool _enableSsl; private FtpControlStream _connection; private Stream _stream; private RequestStage _requestStage; private bool _onceFailed; private WebHeaderCollection _ftpRequestHeaders; private FtpWebResponse _ftpWebResponse; private int _readWriteTimeout = 5 * 60 * 1000; // 5 minutes. private ContextAwareResult _writeAsyncResult; private LazyAsyncResult _readAsyncResult; private LazyAsyncResult _requestCompleteAsyncResult; private static readonly NetworkCredential s_defaultFtpNetworkCredential = new NetworkCredential("anonymous", "anonymous@", String.Empty); private const int s_DefaultTimeout = 100000; // 100 seconds private static readonly TimerThread.Queue s_DefaultTimerQueue = TimerThread.GetOrCreateQueue(s_DefaultTimeout); // Used by FtpControlStream internal FtpMethodInfo MethodInfo { get { return _methodInfo; } } public static new RequestCachePolicy DefaultCachePolicy { get { return WebRequest.DefaultCachePolicy; } set { // We don't support caching, so ignore attempts to set this property. } } /// <summary> /// <para> /// Selects FTP command to use. WebRequestMethods.Ftp.DownloadFile is default. /// Not allowed to be changed once request is started. /// </para> /// </summary> public override string Method { get { return _methodInfo.Method; } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_ftp_invalid_method_name, nameof(value)); } if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } try { _methodInfo = FtpMethodInfo.GetMethodInfo(value); } catch (ArgumentException) { throw new ArgumentException(SR.net_ftp_unsupported_method, nameof(value)); } } } /// <summary> /// <para> /// Sets the target name for the WebRequestMethods.Ftp.Rename command. /// Not allowed to be changed once request is started. /// </para> /// </summary> public string RenameTo { get { return _renameTo; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (String.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_ftp_invalid_renameto, nameof(value)); } _renameTo = value; } } /// <summary> /// <para>Used for clear text authentication with FTP server</para> /// </summary> public override ICredentials Credentials { get { return _authInfo; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value == CredentialCache.DefaultNetworkCredentials) { throw new ArgumentException(SR.net_ftp_no_defaultcreds, nameof(value)); } _authInfo = value; } } /// <summary> /// <para>Gets the Uri used to make the request</para> /// </summary> public override Uri RequestUri { get { return _uri; } } /// <summary> /// <para>Timeout of the blocking calls such as GetResponse and GetRequestStream (default 100 secs)</para> /// </summary> public override int Timeout { get { return _timeout; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value < 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero); } if (_timeout != value) { _timeout = value; _timerQueue = null; } } } internal int RemainingTimeout { get { return _remainingTimeout; } } /// <summary> /// <para>Used to control the Timeout when calling Stream.Read and Stream.Write. /// Applies to Streams returned from GetResponse().GetResponseStream() and GetRequestStream(). /// Default is 5 mins. /// </para> /// </summary> public int ReadWriteTimeout { get { return _readWriteTimeout; } set { if (_getResponseStarted) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } _readWriteTimeout = value; } } /// <summary> /// <para>Used to specify what offset we will read at</para> /// </summary> public long ContentOffset { get { return _contentOffset; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _contentOffset = value; } } /// <summary> /// <para>Gets or sets the data size of to-be uploaded data</para> /// </summary> public override long ContentLength { get { return _contentLength; } set { _contentLength = value; } } public override IWebProxy Proxy { get { return null; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } // Ignore, since we do not support proxied requests. } } public override string ConnectionGroupName { get { return _connectionGroupName; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } _connectionGroupName = value; } } public ServicePoint ServicePoint { get { if (_servicePoint == null) { _servicePoint = ServicePointManager.FindServicePoint(_uri); } return _servicePoint; } } internal bool Aborted { get { return _aborted; } } internal FtpWebRequest(Uri uri) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, uri); if ((object)uri.Scheme != (object)Uri.UriSchemeFtp) throw new ArgumentOutOfRangeException(nameof(uri)); _timerCallback = new TimerThread.Callback(TimerCallback); _syncObject = new object(); NetworkCredential networkCredential = null; _uri = uri; _methodInfo = FtpMethodInfo.GetMethodInfo(WebRequestMethods.Ftp.DownloadFile); if (_uri.UserInfo != null && _uri.UserInfo.Length != 0) { string userInfo = _uri.UserInfo; string username = userInfo; string password = ""; int index = userInfo.IndexOf(':'); if (index != -1) { username = Uri.UnescapeDataString(userInfo.Substring(0, index)); index++; // skip ':' password = Uri.UnescapeDataString(userInfo.Substring(index, userInfo.Length - index)); } networkCredential = new NetworkCredential(username, password); } if (networkCredential == null) { networkCredential = s_defaultFtpNetworkCredential; } _authInfo = networkCredential; } // // Used to query for the Response of an FTP request // public override WebResponse GetResponse() { if (NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } try { CheckError(); if (_ftpWebResponse != null) { return _ftpWebResponse; } if (_getResponseStarted) { throw new InvalidOperationException(SR.net_repcall); } _getResponseStarted = true; _startTime = DateTime.UtcNow; _remainingTimeout = Timeout; if (Timeout != System.Threading.Timeout.Infinite) { _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds); if (_remainingTimeout <= 0) { throw ExceptionHelper.TimeoutException; } } RequestStage prev = FinishRequestStage(RequestStage.RequestStarted); if (prev >= RequestStage.RequestStarted) { if (prev < RequestStage.ReadReady) { lock (_syncObject) { if (_requestStage < RequestStage.ReadReady) _readAsyncResult = new LazyAsyncResult(null, null, null); } // GetRequeststream or BeginGetRequestStream has not finished yet if (_readAsyncResult != null) _readAsyncResult.InternalWaitForCompletion(); CheckError(); } } else { SubmitRequest(false); if (_methodInfo.IsUpload) FinishRequestStage(RequestStage.WriteReady); else FinishRequestStage(RequestStage.ReadReady); CheckError(); EnsureFtpWebResponse(null); } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); // if _exception == null, we are about to throw an exception to the user // and we haven't saved the exception, which also means we haven't dealt // with it. So just release the connection and log this for investigation. if (_exception == null) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); SetException(exception); FinishRequestStage(RequestStage.CheckForError); } throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _ftpWebResponse); } return _ftpWebResponse; } /// <summary> /// <para>Used to query for the Response of an FTP request [async version]</para> /// </summary> public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } ContextAwareResult asyncResult; try { if (_ftpWebResponse != null) { asyncResult = new ContextAwareResult(this, state, callback); asyncResult.InvokeCallback(_ftpWebResponse); return asyncResult; } if (_getResponseStarted) { throw new InvalidOperationException(SR.net_repcall); } _getResponseStarted = true; CheckError(); RequestStage prev = FinishRequestStage(RequestStage.RequestStarted); asyncResult = new ContextAwareResult(true, true, this, state, callback); _readAsyncResult = asyncResult; if (prev >= RequestStage.RequestStarted) { // To make sure the context is flowed asyncResult.StartPostingAsyncOp(); asyncResult.FinishPostingAsyncOp(); if (prev >= RequestStage.ReadReady) asyncResult = null; else { lock (_syncObject) { if (_requestStage >= RequestStage.ReadReady) asyncResult = null; ; } } if (asyncResult == null) { // need to complete it now asyncResult = (ContextAwareResult)_readAsyncResult; if (!asyncResult.InternalPeekCompleted) asyncResult.InvokeCallback(); } } else { // Do internal processing in this handler to optimize context flowing. lock (asyncResult.StartPostingAsyncOp()) { SubmitRequest(true); asyncResult.FinishPostingAsyncOp(); } FinishRequestStage(RequestStage.CheckForError); } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return asyncResult; } /// <summary> /// <para>Returns result of query for the Response of an FTP request [async version]</para> /// </summary> public override WebResponse EndGetResponse(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { // parameter validation if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse")); } castedAsyncResult.InternalWaitForCompletion(); castedAsyncResult.EndCalled = true; CheckError(); } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return _ftpWebResponse; } /// <summary> /// <para>Used to query for the Request stream of an FTP Request</para> /// </summary> public override Stream GetRequestStream() { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } try { if (_getRequestStreamStarted) { throw new InvalidOperationException(SR.net_repcall); } _getRequestStreamStarted = true; if (!_methodInfo.IsUpload) { throw new ProtocolViolationException(SR.net_nouploadonget); } CheckError(); _startTime = DateTime.UtcNow; _remainingTimeout = Timeout; if (Timeout != System.Threading.Timeout.Infinite) { _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds); if (_remainingTimeout <= 0) { throw ExceptionHelper.TimeoutException; } } FinishRequestStage(RequestStage.RequestStarted); SubmitRequest(false); FinishRequestStage(RequestStage.WriteReady); CheckError(); if (_stream.CanTimeout) { _stream.WriteTimeout = ReadWriteTimeout; _stream.ReadTimeout = ReadWriteTimeout; } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return _stream; } /// <summary> /// <para>Used to query for the Request stream of an FTP Request [async version]</para> /// </summary> public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } ContextAwareResult asyncResult = null; try { if (_getRequestStreamStarted) { throw new InvalidOperationException(SR.net_repcall); } _getRequestStreamStarted = true; if (!_methodInfo.IsUpload) { throw new ProtocolViolationException(SR.net_nouploadonget); } CheckError(); FinishRequestStage(RequestStage.RequestStarted); asyncResult = new ContextAwareResult(true, true, this, state, callback); lock (asyncResult.StartPostingAsyncOp()) { _writeAsyncResult = asyncResult; SubmitRequest(true); asyncResult.FinishPostingAsyncOp(); FinishRequestStage(RequestStage.CheckForError); } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return asyncResult; } public override Stream EndGetRequestStream(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); Stream requestStream = null; try { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse")); } castedAsyncResult.InternalWaitForCompletion(); castedAsyncResult.EndCalled = true; CheckError(); requestStream = _stream; castedAsyncResult.EndCalled = true; if (requestStream.CanTimeout) { requestStream.WriteTimeout = ReadWriteTimeout; requestStream.ReadTimeout = ReadWriteTimeout; } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return requestStream; } // // NOTE1: The caller must synchronize access to SubmitRequest(), only one call is allowed for a particular request. // NOTE2: This method eats all exceptions so the caller must rethrow them. // private void SubmitRequest(bool isAsync) { try { _async = isAsync; // // FYI: Will do 2 attempts max as per AttemptedRecovery // Stream stream; while (true) { FtpControlStream connection = _connection; if (connection == null) { if (isAsync) { CreateConnectionAsync(); return; } connection = CreateConnection(); _connection = connection; } if (!isAsync) { if (Timeout != System.Threading.Timeout.Infinite) { _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds); if (_remainingTimeout <= 0) { throw ExceptionHelper.TimeoutException; } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Request being submitted"); connection.SetSocketTimeoutOption(RemainingTimeout); try { stream = TimedSubmitRequestHelper(isAsync); } catch (Exception e) { if (AttemptedRecovery(e)) { if (!isAsync) { if (Timeout != System.Threading.Timeout.Infinite) { _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds); if (_remainingTimeout <= 0) { throw; } } } continue; } throw; } // no retry needed break; } } catch (WebException webException) { // If this was a timeout, throw a timeout exception IOException ioEx = webException.InnerException as IOException; if (ioEx != null) { SocketException sEx = ioEx.InnerException as SocketException; if (sEx != null) { if (sEx.SocketErrorCode == SocketError.TimedOut) { SetException(new WebException(SR.net_timeout, WebExceptionStatus.Timeout)); } } } SetException(webException); } catch (Exception exception) { SetException(exception); } } private Exception TranslateConnectException(Exception e) { SocketException se = e as SocketException; if (se != null) { if (se.SocketErrorCode == SocketError.HostNotFound) { return new WebException(SR.net_webstatus_NameResolutionFailure, WebExceptionStatus.NameResolutionFailure); } else { return new WebException(SR.net_webstatus_ConnectFailure, WebExceptionStatus.ConnectFailure); } } // Wasn't a socket error, so leave as is return e; } private async void CreateConnectionAsync() { string hostname = _uri.Host; int port = _uri.Port; TcpClient client = new TcpClient(); object result; try { await client.ConnectAsync(hostname, port).ConfigureAwait(false); result = new FtpControlStream(client); } catch (Exception e) { result = TranslateConnectException(e); } AsyncRequestCallback(result); } private FtpControlStream CreateConnection() { string hostname = _uri.Host; int port = _uri.Port; TcpClient client = new TcpClient(); try { client.Connect(hostname, port); } catch (Exception e) { throw TranslateConnectException(e); } return new FtpControlStream(client); } private Stream TimedSubmitRequestHelper(bool isAsync) { if (isAsync) { // non-null in the case of re-submit (recovery) if (_requestCompleteAsyncResult == null) _requestCompleteAsyncResult = new LazyAsyncResult(null, null, null); return _connection.SubmitRequest(this, true, true); } Stream stream = null; bool timedOut = false; TimerThread.Timer timer = TimerQueue.CreateTimer(_timerCallback, null); try { stream = _connection.SubmitRequest(this, false, true); } catch (Exception exception) { if (!(exception is SocketException || exception is ObjectDisposedException) || !timer.HasExpired) { timer.Cancel(); throw; } timedOut = true; } if (timedOut || !timer.Cancel()) { _timedOut = true; throw ExceptionHelper.TimeoutException; } if (stream != null) { lock (_syncObject) { if (_aborted) { ((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent); CheckError(); //must throw throw new InternalException(); //consider replacing this on Assert } _stream = stream; } } return stream; } /// <summary> /// <para>Because this is called from the timer thread, neither it nor any methods it calls can call user code.</para> /// </summary> private void TimerCallback(TimerThread.Timer timer, int timeNoticed, object context) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); FtpControlStream connection = _connection; if (connection != null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "aborting connection"); connection.AbortConnect(); } } private TimerThread.Queue TimerQueue { get { if (_timerQueue == null) { _timerQueue = TimerThread.GetOrCreateQueue(RemainingTimeout); } return _timerQueue; } } /// <summary> /// <para>Returns true if we should restart the request after an error</para> /// </summary> private bool AttemptedRecovery(Exception e) { if (e is OutOfMemoryException || _onceFailed || _aborted || _timedOut || _connection == null || !_connection.RecoverableFailure) { return false; } _onceFailed = true; lock (_syncObject) { if (_connection != null) { _connection.CloseSocket(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connection: {_connection}"); _connection = null; } else { return false; } } return true; } /// <summary> /// <para>Updates and sets our exception to be thrown</para> /// </summary> private void SetException(Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); if (exception is OutOfMemoryException) { _exception = exception; throw exception; } FtpControlStream connection = _connection; if (_exception == null) { if (exception is WebException) { EnsureFtpWebResponse(exception); _exception = new WebException(exception.Message, null, ((WebException)exception).Status, _ftpWebResponse); } else if (exception is AuthenticationException || exception is SecurityException) { _exception = exception; } else if (connection != null && connection.StatusCode != FtpStatusCode.Undefined) { EnsureFtpWebResponse(exception); _exception = new WebException(SR.Format(SR.net_ftp_servererror, connection.StatusLine), exception, WebExceptionStatus.ProtocolError, _ftpWebResponse); } else { _exception = new WebException(exception.Message, exception); } if (connection != null && _ftpWebResponse != null) _ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); } } /// <summary> /// <para>Opposite of SetException, rethrows the exception</para> /// </summary> private void CheckError() { if (_exception != null) { ExceptionDispatchInfo.Throw(_exception); } } internal void RequestCallback(object obj) { if (_async) AsyncRequestCallback(obj); else SyncRequestCallback(obj); } // // Only executed for Sync requests when the pipline is completed // private void SyncRequestCallback(object obj) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, obj); RequestStage stageMode = RequestStage.CheckForError; try { bool completedRequest = obj == null; Exception exception = obj as Exception; if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"exp:{exception} completedRequest:{completedRequest}"); if (exception != null) { SetException(exception); } else if (!completedRequest) { throw new InternalException(); } else { FtpControlStream connection = _connection; if (connection != null) { EnsureFtpWebResponse(null); // This to update response status and exit message if any. // Note that status 221 "Service closing control connection" is always suppressed. _ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); } stageMode = RequestStage.ReleaseConnection; } } catch (Exception exception) { SetException(exception); } finally { FinishRequestStage(stageMode); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); CheckError(); //will throw on error } } // // Only executed for Async requests // private void AsyncRequestCallback(object obj) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, obj); RequestStage stageMode = RequestStage.CheckForError; try { FtpControlStream connection; connection = obj as FtpControlStream; FtpDataStream stream = obj as FtpDataStream; Exception exception = obj as Exception; bool completedRequest = (obj == null); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"stream:{stream} conn:{connection} exp:{exception} completedRequest:{completedRequest}"); while (true) { if (exception != null) { if (AttemptedRecovery(exception)) { connection = CreateConnection(); if (connection == null) return; exception = null; } if (exception != null) { SetException(exception); break; } } if (connection != null) { lock (_syncObject) { if (_aborted) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connect:{connection}"); connection.CloseSocket(); break; } _connection = connection; if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _connection); } try { stream = (FtpDataStream)TimedSubmitRequestHelper(true); } catch (Exception e) { exception = e; continue; } return; } else if (stream != null) { lock (_syncObject) { if (_aborted) { ((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent); break; } _stream = stream; } stream.SetSocketTimeoutOption(Timeout); EnsureFtpWebResponse(null); stageMode = stream.CanRead ? RequestStage.ReadReady : RequestStage.WriteReady; } else if (completedRequest) { connection = _connection; if (connection != null) { EnsureFtpWebResponse(null); // This to update response status and exit message if any. // Note that the status 221 "Service closing control connection" is always suppressed. _ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); } stageMode = RequestStage.ReleaseConnection; } else { throw new InternalException(); } break; } } catch (Exception exception) { SetException(exception); } finally { FinishRequestStage(stageMode); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } } private enum RequestStage { CheckForError = 0, // Do nothing except if there is an error then auto promote to ReleaseConnection RequestStarted, // Mark this request as started WriteReady, // First half is done, i.e. either writer or response stream. This is always assumed unless Started or CheckForError ReadReady, // Second half is done, i.e. the read stream can be accesses. ReleaseConnection // Release the control connection (request is read i.e. done-done) } // // Returns a previous stage // private RequestStage FinishRequestStage(RequestStage stage) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"state:{stage}"); if (_exception != null) stage = RequestStage.ReleaseConnection; RequestStage prev; LazyAsyncResult writeResult; LazyAsyncResult readResult; FtpControlStream connection; lock (_syncObject) { prev = _requestStage; if (stage == RequestStage.CheckForError) return prev; if (prev == RequestStage.ReleaseConnection && stage == RequestStage.ReleaseConnection) { return RequestStage.ReleaseConnection; } if (stage > prev) _requestStage = stage; if (stage <= RequestStage.RequestStarted) return prev; writeResult = _writeAsyncResult; readResult = _readAsyncResult; connection = _connection; if (stage == RequestStage.ReleaseConnection) { if (_exception == null && !_aborted && prev != RequestStage.ReadReady && _methodInfo.IsDownload && !_ftpWebResponse.IsFromCache) { return prev; } _connection = null; } } try { // First check to see on releasing the connection if ((stage == RequestStage.ReleaseConnection || prev == RequestStage.ReleaseConnection) && connection != null) { try { if (_exception != null) { connection.Abort(_exception); } } finally { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connection: {connection}"); connection.CloseSocket(); if (_async) if (_requestCompleteAsyncResult != null) _requestCompleteAsyncResult.InvokeCallback(); } } return prev; } finally { try { // In any case we want to signal the writer if came here if (stage >= RequestStage.WriteReady) { // If writeResult == null and this is an upload request, it means // that the user has called GetResponse() without calling // GetRequestStream() first. So they are not interested in a // stream. Therefore we close the stream so that the // request/pipeline can continue if (_methodInfo.IsUpload && !_getRequestStreamStarted) { if (_stream != null) _stream.Close(); } else if (writeResult != null && !writeResult.InternalPeekCompleted) writeResult.InvokeCallback(); } } finally { // The response is ready either with or without a stream if (stage >= RequestStage.ReadReady && readResult != null && !readResult.InternalPeekCompleted) readResult.InvokeCallback(); } } } /// <summary> /// <para>Aborts underlying connection to FTP server (command & data)</para> /// </summary> public override void Abort() { if (_aborted) return; if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { Stream stream; FtpControlStream connection; lock (_syncObject) { if (_requestStage >= RequestStage.ReleaseConnection) return; _aborted = true; stream = _stream; connection = _connection; _exception = ExceptionHelper.RequestAbortedException; } if (stream != null) { if (!(stream is ICloseEx)) { NetEventSource.Fail(this, "The _stream member is not CloseEx hence the risk of connection been orphaned."); } ((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent); } if (connection != null) connection.Abort(ExceptionHelper.RequestAbortedException); } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } } public bool KeepAlive { get { return true; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } // We don't support connection pooling, so just silently ignore this. } } public override RequestCachePolicy CachePolicy { get { return FtpWebRequest.DefaultCachePolicy; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } // We don't support caching, so just silently ignore this. } } /// <summary> /// <para>True by default, false allows transmission using text mode</para> /// </summary> public bool UseBinary { get { return _binary; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } _binary = value; } } public bool UsePassive { get { return _passive; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } _passive = value; } } public X509CertificateCollection ClientCertificates { get { return LazyInitializer.EnsureInitialized(ref _clientCertificates, ref _syncObject, () => new X509CertificateCollection()); } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _clientCertificates = value; } } /// <summary> /// <para>Set to true if we need SSL</para> /// </summary> public bool EnableSsl { get { return _enableSsl; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } _enableSsl = value; } } public override WebHeaderCollection Headers { get { if (_ftpRequestHeaders == null) { _ftpRequestHeaders = new WebHeaderCollection(); } return _ftpRequestHeaders; } set { _ftpRequestHeaders = value; } } // NOT SUPPORTED method public override string ContentType { get { throw ExceptionHelper.PropertyNotSupportedException; } set { throw ExceptionHelper.PropertyNotSupportedException; } } // NOT SUPPORTED method public override bool UseDefaultCredentials { get { throw ExceptionHelper.PropertyNotSupportedException; } set { throw ExceptionHelper.PropertyNotSupportedException; } } // NOT SUPPORTED method public override bool PreAuthenticate { get { throw ExceptionHelper.PropertyNotSupportedException; } set { throw ExceptionHelper.PropertyNotSupportedException; } } /// <summary> /// <para>True if a request has been submitted (ie already active)</para> /// </summary> private bool InUse { get { if (_getRequestStreamStarted || _getResponseStarted) { return true; } else { return false; } } } /// <summary> /// <para>Creates an FTP WebResponse based off the responseStream and our active Connection</para> /// </summary> private void EnsureFtpWebResponse(Exception exception) { if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null)) { lock (_syncObject) { if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null)) { Stream responseStream = _stream; if (_methodInfo.IsUpload) { responseStream = null; } if (_stream != null && _stream.CanRead && _stream.CanTimeout) { _stream.ReadTimeout = ReadWriteTimeout; _stream.WriteTimeout = ReadWriteTimeout; } FtpControlStream connection = _connection; long contentLength = connection != null ? connection.ContentLength : -1; if (responseStream == null) { // If the last command was SIZE, we set the ContentLength on // the FtpControlStream to be the size of the file returned in the // response. We should propagate that file size to the response so // users can access it. This also maintains the compatibility with // HTTP when returning size instead of content. if (contentLength < 0) contentLength = 0; } if (_ftpWebResponse != null) { _ftpWebResponse.SetResponseStream(responseStream); } else { if (connection != null) _ftpWebResponse = new FtpWebResponse(responseStream, contentLength, connection.ResponseUri, connection.StatusCode, connection.StatusLine, connection.LastModified, connection.BannerMessage, connection.WelcomeMessage, connection.ExitMessage); else _ftpWebResponse = new FtpWebResponse(responseStream, -1, _uri, FtpStatusCode.Undefined, null, DateTime.Now, null, null, null); } } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Returns {_ftpWebResponse} with stream {_ftpWebResponse._responseStream}"); return; } internal void DataStreamClosed(CloseExState closeState) { if ((closeState & CloseExState.Abort) == 0) { if (!_async) { if (_connection != null) _connection.CheckContinuePipeline(); } else { _requestCompleteAsyncResult.InternalWaitForCompletion(); CheckError(); } } else { FtpControlStream connection = _connection; if (connection != null) connection.Abort(ExceptionHelper.RequestAbortedException); } } } // class FtpWebRequest // // Class used by the WebRequest.Create factory to create FTP requests // internal class FtpWebRequestCreator : IWebRequestCreate { internal FtpWebRequestCreator() { } public WebRequest Create(Uri uri) { return new FtpWebRequest(uri); } } // class FtpWebRequestCreator } // namespace System.Net
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; /* GoogleAnalyticsV4 is an interface for developers to send hits to Google Analytics. The class will delegate the hits to the appropriate helper class depending on the platform being built for - Android, iOS or Measurement Protocol for all others. Each method has a simple form with the hit parameters, or developers can pass a builder to the same method name in order to add custom metrics or custom dimensions to the hit. */ public class GoogleAnalyticsV4 : MonoBehaviour { private string uncaughtExceptionStackTrace = null; private bool initialized = false; public enum DebugMode { ERROR, WARNING, INFO, VERBOSE }; [Tooltip("The tracking code to be used for Android. Example value: UA-XXXX-Y.")] public string androidTrackingCode; [Tooltip("The tracking code to be used for iOS. Example value: UA-XXXX-Y.")] public string IOSTrackingCode; [Tooltip("The tracking code to be used for platforms other than Android and iOS. Example value: UA-XXXX-Y.")] public string otherTrackingCode; [Tooltip("The application name. This value should be modified in the " + "Unity Player Settings.")] public string productName; [Tooltip("The application identifier. Example value: com.company.app.")] public string bundleIdentifier; [Tooltip("The application version. Example value: 1.2")] public string bundleVersion; [RangedTooltip("The dispatch period in seconds. Only required for Android " + "and iOS.", 0, 3600)] public int dispatchPeriod = 5; [RangedTooltip("The sample rate to use. Only required for Android and" + " iOS.", 0, 100)] public int sampleFrequency = 100; [Tooltip("The log level. Default is WARNING.")] public DebugMode logLevel = DebugMode.WARNING; [Tooltip("If checked, the IP address of the sender will be anonymized.")] public bool anonymizeIP = false; [Tooltip("Automatically report uncaught exceptions.")] public bool UncaughtExceptionReporting = false; [Tooltip("Automatically send a launch event when the game starts up.")] public bool sendLaunchEvent = false; [Tooltip("If checked, hits will not be dispatched. Use for testing.")] public bool dryRun = false; // TODO: Create conditional textbox attribute [Tooltip("The amount of time in seconds your application can stay in" + "the background before the session is ended. Default is 30 minutes" + " (1800 seconds). A value of -1 will disable session management.")] public int sessionTimeout = 1800; [AdvertiserOptIn()] public bool enableAdId = false; public static GoogleAnalyticsV4 instance = null; [HideInInspector] public readonly static string currencySymbol = "USD"; public readonly static string EVENT_HIT = "createEvent"; public readonly static string APP_VIEW = "createAppView"; public readonly static string SET = "set"; public readonly static string SET_ALL = "setAll"; public readonly static string SEND = "send"; public readonly static string ITEM_HIT = "createItem"; public readonly static string TRANSACTION_HIT = "createTransaction"; public readonly static string SOCIAL_HIT = "createSocial"; public readonly static string TIMING_HIT = "createTiming"; public readonly static string EXCEPTION_HIT = "createException"; #if UNITY_ANDROID && !UNITY_EDITOR private GoogleAnalyticsAndroidV4 androidTracker = new GoogleAnalyticsAndroidV4(); #elif UNITY_IPHONE && !UNITY_EDITOR private GoogleAnalyticsiOSV3 iosTracker = new GoogleAnalyticsiOSV3(); #else private GoogleAnalyticsMPV3 mpTracker = new GoogleAnalyticsMPV3(); #endif void Awake() { InitializeTracker (); if (sendLaunchEvent) { LogEvent("Google Analytics", "Auto Instrumentation", "Game Launch", 0); } if (UncaughtExceptionReporting) { #if UNITY_5_0 Application.logMessageReceived += HandleException; #else Application.RegisterLogCallback (HandleException); #endif if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Enabling uncaught exception reporting."); } } } void Update() { if (!string.IsNullOrEmpty(uncaughtExceptionStackTrace)) { LogException(uncaughtExceptionStackTrace, true); uncaughtExceptionStackTrace = null; } } private void HandleException(string condition, string stackTrace, LogType type) { if (type == LogType.Exception) { uncaughtExceptionStackTrace = condition + "\n" + stackTrace + UnityEngine.StackTraceUtility.ExtractStackTrace(); } } // TODO: Error checking on initialization parameters private void InitializeTracker() { if (!initialized || instance == null) { instance = this; DontDestroyOnLoad(instance); Debug.Log("Initializing Google Analytics 0.2."); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.SetTrackingCode(androidTrackingCode); androidTracker.SetAppName(productName); androidTracker.SetBundleIdentifier(bundleIdentifier); androidTracker.SetAppVersion(bundleVersion); androidTracker.SetDispatchPeriod(dispatchPeriod); androidTracker.SetSampleFrequency(sampleFrequency); androidTracker.SetLogLevelValue(logLevel); androidTracker.SetAnonymizeIP(anonymizeIP); androidTracker.SetAdIdCollection(enableAdId); androidTracker.SetDryRun(dryRun); androidTracker.InitializeTracker(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.SetTrackingCode(IOSTrackingCode); iosTracker.SetAppName(productName); iosTracker.SetBundleIdentifier(bundleIdentifier); iosTracker.SetAppVersion(bundleVersion); iosTracker.SetDispatchPeriod(dispatchPeriod); iosTracker.SetSampleFrequency(sampleFrequency); iosTracker.SetLogLevelValue(logLevel); iosTracker.SetAnonymizeIP(anonymizeIP); iosTracker.SetAdIdCollection(enableAdId); iosTracker.SetDryRun(dryRun); iosTracker.InitializeTracker(); #else mpTracker.SetTrackingCode(otherTrackingCode); mpTracker.SetBundleIdentifier(bundleIdentifier); mpTracker.SetAppName(productName); mpTracker.SetAppVersion(bundleVersion); mpTracker.SetLogLevelValue(logLevel); mpTracker.SetAnonymizeIP(anonymizeIP); mpTracker.SetDryRun(dryRun); mpTracker.InitializeTracker(); #endif initialized = true; SetOnTracker(Fields.DEVELOPER_ID, "GbOCSs"); } } public void SetAppLevelOptOut(bool optOut) { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.SetOptOut(optOut); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.SetOptOut(optOut); #else mpTracker.SetOptOut(optOut); #endif } public void SetUserIDOverride(string userID) { SetOnTracker(Fields.USER_ID, userID); } public void ClearUserIDOverride() { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.ClearUserIDOverride(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.ClearUserIDOverride(); #else mpTracker.ClearUserIDOverride(); #endif } public void DispatchHits() { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.DispatchHits(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.DispatchHits(); #else //Do nothing #endif } public void StartSession() { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.StartSession(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.StartSession(); #else mpTracker.StartSession(); #endif } public void StopSession() { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.StopSession(); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.StopSession(); #else mpTracker.StopSession(); #endif } // Use values from Fields for the fieldName parameter ie. Fields.SCREEN_NAME public void SetOnTracker(Field fieldName, object value) { InitializeTracker(); #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.SetTrackerVal(fieldName, value); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.SetTrackerVal(fieldName, value); #else mpTracker.SetTrackerVal(fieldName, value); #endif } public void LogScreen(string title) { AppViewHitBuilder builder = new AppViewHitBuilder().SetScreenName(title); LogScreen(builder); } public void LogScreen(AppViewHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging screen."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogScreen(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogScreen(builder); #else mpTracker.LogScreen(builder); #endif } public void LogEvent(string eventCategory, string eventAction, string eventLabel, long value) { EventHitBuilder builder = new EventHitBuilder() .SetEventCategory(eventCategory) .SetEventAction(eventAction) .SetEventLabel(eventLabel) .SetEventValue(value); LogEvent(builder); } public void LogEvent(EventHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging event."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogEvent (builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogEvent(builder); #else mpTracker.LogEvent(builder); #endif } public void LogTransaction(string transID, string affiliation, double revenue, double tax, double shipping) { LogTransaction (transID, affiliation, revenue, tax, shipping, ""); } public void LogTransaction(string transID, string affiliation, double revenue, double tax, double shipping, string currencyCode) { TransactionHitBuilder builder = new TransactionHitBuilder() .SetTransactionID(transID) .SetAffiliation(affiliation) .SetRevenue(revenue) .SetTax(tax) .SetShipping(shipping) .SetCurrencyCode(currencyCode); LogTransaction(builder); } public void LogTransaction(TransactionHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging transaction."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogTransaction(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogTransaction(builder); #else mpTracker.LogTransaction(builder); #endif } public void LogItem(string transID, string name, string sku, string category, double price, long quantity) { LogItem (transID, name, sku, category, price, quantity, null); } public void LogItem(string transID, string name, string sku, string category, double price, long quantity, string currencyCode) { ItemHitBuilder builder = new ItemHitBuilder() .SetTransactionID(transID) .SetName(name) .SetSKU(sku) .SetCategory(category) .SetPrice(price) .SetQuantity(quantity) .SetCurrencyCode(currencyCode); LogItem(builder); } public void LogItem(ItemHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging item."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogItem(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogItem(builder); #else mpTracker.LogItem(builder); #endif } public void LogException(string exceptionDescription, bool isFatal) { ExceptionHitBuilder builder = new ExceptionHitBuilder() .SetExceptionDescription(exceptionDescription) .SetFatal(isFatal); LogException(builder); } public void LogException(ExceptionHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging exception."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogException(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogException(builder); #else mpTracker.LogException(builder); #endif } public void LogSocial(string socialNetwork, string socialAction, string socialTarget) { SocialHitBuilder builder = new SocialHitBuilder() .SetSocialNetwork(socialNetwork) .SetSocialAction(socialAction) .SetSocialTarget(socialTarget); LogSocial(builder); } public void LogSocial(SocialHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging social."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogSocial(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogSocial(builder); #else mpTracker.LogSocial(builder); #endif } public void LogTiming(string timingCategory, long timingInterval, string timingName, string timingLabel) { TimingHitBuilder builder = new TimingHitBuilder() .SetTimingCategory(timingCategory) .SetTimingInterval(timingInterval) .SetTimingName(timingName) .SetTimingLabel(timingLabel); LogTiming(builder); } public void LogTiming(TimingHitBuilder builder) { InitializeTracker(); if (builder.Validate() == null) { return; } if (GoogleAnalyticsV4.belowThreshold(logLevel, GoogleAnalyticsV4.DebugMode.VERBOSE)) { Debug.Log("Logging timing."); } #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.LogTiming(builder); #elif UNITY_IPHONE && !UNITY_EDITOR iosTracker.LogTiming(builder); #else mpTracker.LogTiming(builder); #endif } public void Dispose() { initialized = false; #if UNITY_ANDROID && !UNITY_EDITOR androidTracker.Dispose(); #elif UNITY_IPHONE && !UNITY_EDITOR #else #endif } public static bool belowThreshold(GoogleAnalyticsV4.DebugMode userLogLevel, GoogleAnalyticsV4.DebugMode comparelogLevel) { if (comparelogLevel == userLogLevel) { return true; } else if (userLogLevel == GoogleAnalyticsV4.DebugMode.ERROR) { return false; } else if (userLogLevel == GoogleAnalyticsV4.DebugMode.VERBOSE) { return true; } else if (userLogLevel == GoogleAnalyticsV4.DebugMode.WARNING && (comparelogLevel == GoogleAnalyticsV4.DebugMode.INFO || comparelogLevel == GoogleAnalyticsV4.DebugMode.VERBOSE)) { return false; } else if (userLogLevel == GoogleAnalyticsV4.DebugMode.INFO && (comparelogLevel == GoogleAnalyticsV4.DebugMode.VERBOSE)) { return false; } return true; } // Instance for running Coroutines from platform specific classes public static GoogleAnalyticsV4 getInstance() { return instance; } }
using System; using System.Drawing; using NUnit.Framework; namespace OpenQA.Selenium { [TestFixture] public class WindowTest : DriverTestFixture { private Size originalWindowSize; [SetUp] public void GetBrowserWindowSize() { driver.Manage().Window.Position = new Point(50, 50); this.originalWindowSize = driver.Manage().Window.Size; } [TearDown] public void RestoreBrowserWindow() { driver.Manage().Window.Size = originalWindowSize; } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToGetTheSizeOfTheCurrentWindow() { Size size = driver.Manage().Window.Size; Assert.That(size.Width, Is.GreaterThan(0)); Assert.That(size.Height, Is.GreaterThan(0)); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToSetTheSizeOfTheCurrentWindow() { IWindow window = driver.Manage().Window; Size size = window.Size; // resize relative to the initial size, since we don't know what it is Size targetSize = new Size(size.Width - 20, size.Height - 20); ChangeSizeBy(-20, -20); Size newSize = window.Size; Assert.AreEqual(targetSize.Width, newSize.Width); Assert.AreEqual(targetSize.Height, newSize.Height); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToSetTheSizeOfTheCurrentWindowFromFrame() { IWindow window = driver.Manage().Window; Size size = window.Size; driver.Url = framesetPage; driver.SwitchTo().Frame("fourth"); try { // resize relative to the initial size, since we don't know what it is Size targetSize = new Size(size.Width - 20, size.Height - 20); window.Size = targetSize; Size newSize = window.Size; Assert.AreEqual(targetSize.Width, newSize.Width); Assert.AreEqual(targetSize.Height, newSize.Height); } finally { driver.SwitchTo().DefaultContent(); } } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToSetTheSizeOfTheCurrentWindowFromIFrame() { IWindow window = driver.Manage().Window; Size size = window.Size; driver.Url = iframePage; driver.SwitchTo().Frame("iframe1-name"); try { // resize relative to the initial size, since we don't know what it is Size targetSize = new Size(size.Width - 20, size.Height - 20); window.Size = targetSize; Size newSize = window.Size; Assert.AreEqual(targetSize.Width, newSize.Width); Assert.AreEqual(targetSize.Height, newSize.Height); } finally { driver.SwitchTo().DefaultContent(); } } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToGetThePositionOfTheCurrentWindow() { Point position = driver.Manage().Window.Position; Assert.That(position.X, Is.GreaterThan(0)); Assert.That(position.Y, Is.GreaterThan(0)); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToSetThePositionOfTheCurrentWindow() { IWindow window = driver.Manage().Window; window.Size = new Size(200, 200); Point position = window.Position; Point targetPosition = new Point(position.X + 10, position.Y + 10); window.Position = targetPosition; Point newLocation = window.Position; Assert.AreEqual(targetPosition.X, newLocation.X); Assert.AreEqual(targetPosition.Y, newLocation.Y); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToMaximizeTheCurrentWindow() { Size targetSize = new Size(640, 275); ChangeSizeTo(targetSize); Maximize(); IWindow window = driver.Manage().Window; Assert.That(window.Size.Height, Is.GreaterThan(targetSize.Height)); Assert.That(window.Size.Width, Is.GreaterThan(targetSize.Width)); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToMaximizeTheWindowFromFrame() { driver.Url = framesetPage; ChangeSizeTo(new Size(640, 275)); driver.SwitchTo().Frame("fourth"); try { Maximize(); } finally { driver.SwitchTo().DefaultContent(); } } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToMaximizeTheWindowFromIframe() { driver.Url = iframePage; ChangeSizeTo(new Size(640, 275)); driver.SwitchTo().Frame("iframe1-name"); try { Maximize(); } finally { driver.SwitchTo().DefaultContent(); } } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver does not implement the full screen command")] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToFullScreenTheCurrentWindow() { Size targetSize = new Size(640, 275); ChangeSizeTo(targetSize); FullScreen(); IWindow window = driver.Manage().Window; Size windowSize = window.Size; Point windowPosition = window.Position; Assert.That(windowSize.Height, Is.GreaterThan(targetSize.Height)); Assert.That(windowSize.Width, Is.GreaterThan(targetSize.Width)); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome window size does not report zero when minimized.")] [IgnoreBrowser(Browser.Edge, "Edge window size does not report zero when minimized.")] [IgnoreBrowser(Browser.Opera, "Not implemented in driver")] public void ShouldBeAbleToMinimizeTheCurrentWindow() { Size targetSize = new Size(640, 275); ChangeSizeTo(targetSize); Minimize(); IWindow window = driver.Manage().Window; Size windowSize = window.Size; Point windowPosition = window.Position; Assert.That(windowSize.Height, Is.LessThan(targetSize.Height)); Assert.That(windowSize.Width, Is.LessThan(targetSize.Width)); Assert.That(windowPosition.X, Is.LessThan(0)); Assert.That(windowPosition.Y, Is.LessThan(0)); } private void FullScreen() { IWindow window = driver.Manage().Window; Size currentSize = window.Size; window.FullScreen(); } private void Maximize() { IWindow window = driver.Manage().Window; Size currentSize = window.Size; window.Maximize(); WaitFor(WindowHeightToBeGreaterThan(currentSize.Height), "Window height was not greater than " + currentSize.Height.ToString()); WaitFor(WindowWidthToBeGreaterThan(currentSize.Width), "Window width was not greater than " + currentSize.Width.ToString()); } private void Minimize() { IWindow window = driver.Manage().Window; Size currentSize = window.Size; window.Minimize(); WaitFor(WindowHeightToBeLessThan(currentSize.Height), "Window height was not less than " + currentSize.Height.ToString()); WaitFor(WindowWidthToBeLessThan(currentSize.Width), "Window width was not less than " + currentSize.Width.ToString()); } private void ChangeSizeTo(Size targetSize) { IWindow window = driver.Manage().Window; window.Size = targetSize; WaitFor(WindowHeightToBeEqualTo(targetSize.Height), "Window height was not " + targetSize.Height.ToString()); WaitFor(WindowWidthToBeEqualTo(targetSize.Width), "Window width was not " + targetSize.Width.ToString()); } private void ChangeSizeBy(int deltaX, int deltaY) { IWindow window = driver.Manage().Window; Size size = window.Size; ChangeSizeTo(new Size(size.Width + deltaX, size.Height + deltaY)); } private Func<bool> WindowHeightToBeEqualTo(int height) { return () => { return driver.Manage().Window.Size.Height == height; }; } private Func<bool> WindowWidthToBeEqualTo(int width) { return () => { return driver.Manage().Window.Size.Width == width; }; } private Func<bool> WindowHeightToBeGreaterThan(int height) { return () => { return driver.Manage().Window.Size.Height > height; }; } private Func<bool> WindowWidthToBeGreaterThan(int width) { return () => { return driver.Manage().Window.Size.Width > width; }; } private Func<bool> WindowHeightToBeLessThan(int height) { return () => { return driver.Manage().Window.Size.Height < height; }; } private Func<bool> WindowWidthToBeLessThan(int width) { return () => { return driver.Manage().Window.Size.Width < width; }; } } }
//----------------------------------------------------------------------- // <copyright file="StageActorRefSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Threading.Tasks; using Akka.Actor; using Akka.Event; using Akka.Streams.Dsl; using Akka.Streams.Stage; using Akka.Streams.TestKit.Tests; using Akka.TestKit.Internal; using Akka.TestKit.TestEvent; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class StageActorRefSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public StageActorRefSpec(ITestOutputHelper helper) : base(helper) { var settings = ActorMaterializerSettings.Create(Sys); Materializer = ActorMaterializer.Create(Sys, settings); } private static GraphStageWithMaterializedValue<SinkShape<int>, Task<int>> SumStage(IActorRef probe) => new SumTestStage(probe); [Fact] public void A_Graph_stage_ActorRef_must_receive_messages() { var t = Source.Maybe<int>().ToMaterialized(SumStage(TestActor), Keep.Both).Run(Materializer); var res = t.Item2; var stageRef = ExpectMsg<IActorRef>(); stageRef.Tell(new Add(1)); stageRef.Tell(new Add(2)); stageRef.Tell(new Add(3)); stageRef.Tell(StopNow.Instance); res.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); res.Result.Should().Be(6); } [Fact] public void A_Graph_stage_ActorRef_must_be_able_to_be_replied_to() { var t = Source.Maybe<int>().ToMaterialized(SumStage(TestActor), Keep.Both).Run(Materializer); var res = t.Item2; var stageRef = ExpectMsg<IActorRef>(); stageRef.Tell(new AddAndTell(1)); ExpectMsg(1); stageRef.Should().Be(LastSender); LastSender.Tell(new AddAndTell(9)); ExpectMsg(10); stageRef.Tell(StopNow.Instance); res.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); res.Result.Should().Be(10); } [Fact] public void A_Graph_stage_ActorRef_must_yield_the_same_self_ref_each_time() { var t = Source.Maybe<int>().ToMaterialized(SumStage(TestActor), Keep.Both).Run(Materializer); var res = t.Item2; var stageRef = ExpectMsg<IActorRef>(); stageRef.Tell(CallInitStageActorRef.Instance); var explicitlyObtained = ExpectMsg<IActorRef>(); stageRef.Should().Be(explicitlyObtained); explicitlyObtained.Tell(new AddAndTell(1)); ExpectMsg(1); LastSender.Tell(new AddAndTell(2)); ExpectMsg(3); stageRef.Tell(new AddAndTell(3)); ExpectMsg(6); stageRef.Tell(StopNow.Instance); res.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); res.Result.Should().Be(6); } [Fact] public void A_Graph_stage_ActorRef_must_be_watchable() { var t = Source.Maybe<int>().ToMaterialized(SumStage(TestActor), Keep.Both).Run(Materializer); var source = t.Item1; var res = t.Item2; var stageRef = ExpectMsg<IActorRef>(); Watch(stageRef); stageRef.Tell(new Add(1)); source.SetResult(0); res.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); res.Result.Should().Be(1); ExpectTerminated(stageRef); } [Fact] public void A_Graph_stage_ActorRef_must_be_able_to_become() { var t = Source.Maybe<int>().ToMaterialized(SumStage(TestActor), Keep.Both).Run(Materializer); var source = t.Item1; var res = t.Item2; var stageRef = ExpectMsg<IActorRef>(); Watch(stageRef); stageRef.Tell(new Add(1)); stageRef.Tell(BecomeStringEcho.Instance); stageRef.Tell(42); ExpectMsg("42"); source.SetResult(0); res.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); res.Result.Should().Be(1); } [Fact] public void A_Graph_stage_ActorRef_must_reply_Terminated_when_terminated_stage_is_watched() { var t = Source.Maybe<int>().ToMaterialized(SumStage(TestActor), Keep.Both).Run(Materializer); var source = t.Item1; var res = t.Item2; var stageRef = ExpectMsg<IActorRef>(); Watch(stageRef); stageRef.Tell(new Add(1)); source.SetResult(0); res.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); res.Result.Should().Be(1); ExpectTerminated(stageRef); var p = CreateTestProbe(); p.Watch(stageRef); p.ExpectTerminated(stageRef); } [Fact] public void A_Graph_stage_ActorRef_must_be_unwatchable() { var t = Source.Maybe<int>().ToMaterialized(SumStage(TestActor), Keep.Both).Run(Materializer); var source = t.Item1; var res = t.Item2; var stageRef = ExpectMsg<IActorRef>(); Watch(stageRef); Unwatch(stageRef); stageRef.Tell(new Add(1)); source.SetResult(0); res.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); res.Result.Should().Be(1); ExpectNoMsg(100); } [Fact] public void A_Graph_stage_ActorRef_must_ignore_and_log_warnings_for_PoisonPill_and_Kill_messages() { var t = Source.Maybe<int>().ToMaterialized(SumStage(TestActor), Keep.Both).Run(Materializer); var source = t.Item1; var res = t.Item2; var stageRef = ExpectMsg<IActorRef>(); stageRef.Tell(new Add(40)); Sys.EventStream.Publish(new Mute(new CustomEventFilter(e => e is Warning))); Sys.EventStream.Subscribe(TestActor, typeof (Warning)); stageRef.Tell(PoisonPill.Instance); var warn = ExpectMsg<Warning>(TimeSpan.FromSeconds(1)); warn.Message.ToString() .Should() .MatchRegex( "<PoisonPill> message sent to StageActorRef\\(akka\\://test/user/StreamSupervisor-[0-9]+/StageActorRef-[0-9]\\) will be ignored, since it is not a real Actor. Use a custom message type to communicate with it instead."); stageRef.Tell(Kill.Instance); warn = ExpectMsg<Warning>(TimeSpan.FromSeconds(1)); warn.Message.ToString() .Should() .MatchRegex( "<Kill> message sent to StageActorRef\\(akka\\://test/user/StreamSupervisor-[0-9]+/StageActorRef-[0-9]\\) will be ignored, since it is not a real Actor. Use a custom message type to communicate with it instead."); source.SetResult(2); res.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); res.Result.Should().Be(42); } [Fact] public void A_Graph_stage_ActorRef_must_be_able_to_watch_other_actors() { var killMe = ActorOf(dsl => { }, "KilMe"); var t = Source.Maybe<int>().ToMaterialized(SumStage(TestActor), Keep.Both).Run(Materializer); var source = t.Item1; var res = t.Item2; var stageRef = ExpectMsg<IActorRef>(); stageRef.Tell(new WatchMe(killMe)); stageRef.Tell(new Add(1)); killMe.Tell(PoisonPill.Instance); ExpectMsg<WatcheeTerminated>().Watchee.Should().Be(killMe); source.SetResult(0); res.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); res.Result.Should().Be(1); } private sealed class Add { public readonly int N; public Add(int n) { N = n; } } private sealed class AddAndTell { public readonly int N; public AddAndTell(int n) { N = n; } } private sealed class CallInitStageActorRef { public static readonly CallInitStageActorRef Instance = new CallInitStageActorRef(); private CallInitStageActorRef() { } } private sealed class BecomeStringEcho { public static readonly BecomeStringEcho Instance = new BecomeStringEcho(); private BecomeStringEcho() { } } private sealed class PullNow { public static readonly PullNow Instance = new PullNow(); private PullNow() { } } private sealed class StopNow { public static readonly StopNow Instance = new StopNow(); private StopNow() { } } private sealed class WatchMe { public WatchMe(IActorRef watchee) { Watchee = watchee; } public IActorRef Watchee { get; } } private sealed class WatcheeTerminated { public WatcheeTerminated(IActorRef watchee) { Watchee = watchee; } public IActorRef Watchee { get; } } private class SumTestStage : GraphStageWithMaterializedValue<SinkShape<int>, Task<int>> { private readonly IActorRef _probe; #region internal classes private class Logic : GraphStageLogic { private readonly SumTestStage _stage; private readonly TaskCompletionSource<int> _promise; private int _sum; private StageActorRef _self; public Logic(SumTestStage stage, TaskCompletionSource<int> promise) : base(stage.Shape) { _stage = stage; _promise = promise; SetHandler(stage._inlet, onPush: () => { _sum += Grab(stage._inlet); promise.TrySetResult(_sum); CompleteStage(); }, onUpstreamFinish: () => { promise.TrySetResult(_sum); CompleteStage(); }, onUpstreamFailure: ex => { promise.TrySetException(ex); FailStage(ex); }); } public override void PreStart() { Pull(_stage._inlet); _self = GetStageActorRef(Behaviour); _stage._probe.Tell(_self); } private void Behaviour(Tuple<IActorRef, object> args) { var msg = args.Item2; var sender = args.Item1; msg.Match() .With<Add>(a => _sum += a.N) .With<PullNow>(() => Pull(_stage._inlet)) .With<CallInitStageActorRef>(() => sender.Tell(GetStageActorRef(Behaviour), _self)) .With<BecomeStringEcho>(() => GetStageActorRef(tuple => tuple.Item1.Tell(tuple.Item2.ToString()))) .With<StopNow>(() => { _promise.TrySetResult(_sum); CompleteStage(); }).With<AddAndTell>(a => { _sum += a.N; sender.Tell(_sum, _self); }) .With<WatchMe>(w => _self.Watch(w.Watchee)) .With<Terminated>(t => _stage._probe.Tell(new WatcheeTerminated(t.ActorRef))); } } #endregion private readonly Inlet<int> _inlet = new Inlet<int>("IntSum.in"); public SumTestStage(IActorRef probe) { _probe = probe; Shape = new SinkShape<int>(_inlet); } public override SinkShape<int> Shape { get; } public override ILogicAndMaterializedValue<Task<int>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var promise = new TaskCompletionSource<int>(); return new LogicAndMaterializedValue<Task<int>>(new Logic(this, promise), promise.Task); } } } }
// 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 { public class Random { // // Private Constants // private const int MBIG = int.MaxValue; private const int MSEED = 161803398; // // Member Variables // private int _inext; private int _inextp; private readonly int[] _seedArray = new int[56]; // // Public Constants // // // Native Declarations // // // Constructors // /*========================================================================================= **Action: Initializes a new instance of the Random class, using a default seed value ===========================================================================================*/ public Random() : this(GenerateSeed()) { } /*========================================================================================= **Action: Initializes a new instance of the Random class, using a specified seed value ===========================================================================================*/ public Random(int Seed) { int ii = 0; int mj, mk; // Initialize our Seed array. int subtraction = (Seed == int.MinValue) ? int.MaxValue : Math.Abs(Seed); mj = MSEED - subtraction; _seedArray[55] = mj; mk = 1; for (int i = 1; i < 55; i++) { // Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position. if ((ii += 21) >= 55) ii -= 55; _seedArray[ii] = mk; mk = mj - mk; if (mk < 0) mk += MBIG; mj = _seedArray[ii]; } for (int k = 1; k < 5; k++) { for (int i = 1; i < 56; i++) { int n = i + 30; if (n >= 55) n -= 55; _seedArray[i] -= _seedArray[1 + n]; if (_seedArray[i] < 0) _seedArray[i] += MBIG; } } _inext = 0; _inextp = 21; } // // Package Private Methods // /*====================================Sample==================================== **Action: Return a new random number [0..1) and reSeed the Seed array. **Returns: A double [0..1) **Arguments: None **Exceptions: None ==============================================================================*/ protected virtual double Sample() { // Including this division at the end gives us significantly improved // random number distribution. return InternalSample() * (1.0 / MBIG); } private int InternalSample() { int retVal; int locINext = _inext; int locINextp = _inextp; if (++locINext >= 56) locINext = 1; if (++locINextp >= 56) locINextp = 1; retVal = _seedArray[locINext] - _seedArray[locINextp]; if (retVal == MBIG) retVal--; if (retVal < 0) retVal += MBIG; _seedArray[locINext] = retVal; _inext = locINext; _inextp = locINextp; return retVal; } [ThreadStatic] private static Random? t_threadRandom; private static readonly Random s_globalRandom = new Random(GenerateGlobalSeed()); /*=====================================GenerateSeed===================================== **Returns: An integer that can be used as seed values for consecutively creating lots of instances on the same thread within a short period of time. ========================================================================================*/ private static int GenerateSeed() { Random? rnd = t_threadRandom; if (rnd == null) { int seed; lock (s_globalRandom) { seed = s_globalRandom.Next(); } rnd = new Random(seed); t_threadRandom = rnd; } return rnd.Next(); } /*==================================GenerateGlobalSeed==================================== **Action: Creates a number to use as global seed. **Returns: An integer that is safe to use as seed values for thread-local seed generators. ==========================================================================================*/ private static unsafe int GenerateGlobalSeed() { int result; Interop.GetRandomBytes((byte*)&result, sizeof(int)); return result; } // // Public Instance Methods // /*=====================================Next===================================== **Returns: An int [0..int.MaxValue) **Arguments: None **Exceptions: None. ==============================================================================*/ public virtual int Next() { return InternalSample(); } private double GetSampleForLargeRange() { // The distribution of double value returned by Sample // is not distributed well enough for a large range. // If we use Sample for a range [int.MinValue..int.MaxValue) // We will end up getting even numbers only. int result = InternalSample(); // Note we can't use addition here. The distribution will be bad if we do that. bool negative = (InternalSample() % 2 == 0) ? true : false; // decide the sign based on second sample if (negative) { result = -result; } double d = result; d += (int.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1) d /= 2 * (uint)int.MaxValue - 1; return d; } /*=====================================Next===================================== **Returns: An int [minvalue..maxvalue) **Arguments: minValue -- the least legal value for the Random number. ** maxValue -- One greater than the greatest legal return value. **Exceptions: None. ==============================================================================*/ public virtual int Next(int minValue, int maxValue) { if (minValue > maxValue) { throw new ArgumentOutOfRangeException(nameof(minValue), SR.Format(SR.Argument_MinMaxValue, nameof(minValue), nameof(maxValue))); } long range = (long)maxValue - minValue; if (range <= int.MaxValue) { return (int)(Sample() * range) + minValue; } else { return (int)((long)(GetSampleForLargeRange() * range) + minValue); } } /*=====================================Next===================================== **Returns: An int [0..maxValue) **Arguments: maxValue -- One more than the greatest legal return value. **Exceptions: None. ==============================================================================*/ public virtual int Next(int maxValue) { if (maxValue < 0) { throw new ArgumentOutOfRangeException(nameof(maxValue), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(maxValue))); } return (int)(Sample() * maxValue); } /*=====================================Next===================================== **Returns: A double [0..1) **Arguments: None **Exceptions: None ==============================================================================*/ public virtual double NextDouble() { return Sample(); } /*==================================NextBytes=================================== **Action: Fills the byte array with random bytes [0..0x7f]. The entire array is filled. **Returns:Void **Arguments: buffer -- the array to be filled. **Exceptions: None ==============================================================================*/ public virtual void NextBytes(byte[] buffer) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)InternalSample(); } } public virtual void NextBytes(Span<byte> buffer) { for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)Next(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; namespace SocketHttpListener.Net { [ComVisible(true)] public class WebHeaderCollection : NameValueCollection { [Flags] internal enum HeaderInfo { Request = 1, Response = 1 << 1, MultiValue = 1 << 10 } static readonly bool[] allowed_chars = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, true, true, false, false, false, true, true, false, true, true, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false }; static readonly Dictionary<string, HeaderInfo> headers; HeaderInfo? headerRestriction; HeaderInfo? headerConsistency; static WebHeaderCollection() { headers = new Dictionary<string, HeaderInfo>(StringComparer.OrdinalIgnoreCase) { { "Allow", HeaderInfo.MultiValue }, { "Accept", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Accept-Charset", HeaderInfo.MultiValue }, { "Accept-Encoding", HeaderInfo.MultiValue }, { "Accept-Language", HeaderInfo.MultiValue }, { "Accept-Ranges", HeaderInfo.MultiValue }, { "Age", HeaderInfo.Response }, { "Authorization", HeaderInfo.MultiValue }, { "Cache-Control", HeaderInfo.MultiValue }, { "Cookie", HeaderInfo.MultiValue }, { "Connection", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Content-Encoding", HeaderInfo.MultiValue }, { "Content-Length", HeaderInfo.Request | HeaderInfo.Response }, { "Content-Type", HeaderInfo.Request }, { "Content-Language", HeaderInfo.MultiValue }, { "Date", HeaderInfo.Request }, { "Expect", HeaderInfo.Request | HeaderInfo.MultiValue}, { "Host", HeaderInfo.Request }, { "If-Match", HeaderInfo.MultiValue }, { "If-Modified-Since", HeaderInfo.Request }, { "If-None-Match", HeaderInfo.MultiValue }, { "Keep-Alive", HeaderInfo.Response }, { "Pragma", HeaderInfo.MultiValue }, { "Proxy-Authenticate", HeaderInfo.MultiValue }, { "Proxy-Authorization", HeaderInfo.MultiValue }, { "Proxy-Connection", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Range", HeaderInfo.Request | HeaderInfo.MultiValue }, { "Referer", HeaderInfo.Request }, { "Set-Cookie", HeaderInfo.MultiValue }, { "Set-Cookie2", HeaderInfo.MultiValue }, { "Server", HeaderInfo.Response }, { "TE", HeaderInfo.MultiValue }, { "Trailer", HeaderInfo.MultiValue }, { "Transfer-Encoding", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo.MultiValue }, { "Translate", HeaderInfo.Request | HeaderInfo.Response }, { "Upgrade", HeaderInfo.MultiValue }, { "User-Agent", HeaderInfo.Request }, { "Vary", HeaderInfo.MultiValue }, { "Via", HeaderInfo.MultiValue }, { "Warning", HeaderInfo.MultiValue }, { "WWW-Authenticate", HeaderInfo.Response | HeaderInfo. MultiValue }, { "SecWebSocketAccept", HeaderInfo.Response }, { "SecWebSocketExtensions", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo. MultiValue }, { "SecWebSocketKey", HeaderInfo.Request }, { "Sec-WebSocket-Protocol", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo. MultiValue }, { "SecWebSocketVersion", HeaderInfo.Response | HeaderInfo. MultiValue } }; } // Methods public void Add(string header) { if (header == null) throw new ArgumentNullException("header"); int pos = header.IndexOf(':'); if (pos == -1) throw new ArgumentException("no colon found", "header"); this.Add(header.Substring(0, pos), header.Substring(pos + 1)); } public override void Add(string name, string value) { if (name == null) throw new ArgumentNullException("name"); CheckRestrictedHeader(name); this.AddWithoutValidate(name, value); } protected void AddWithoutValidate(string headerName, string headerValue) { if (!IsHeaderName(headerName)) throw new ArgumentException("invalid header name: " + headerName, "headerName"); if (headerValue == null) headerValue = String.Empty; else headerValue = headerValue.Trim(); if (!IsHeaderValue(headerValue)) throw new ArgumentException("invalid header value: " + headerValue, "headerValue"); AddValue(headerName, headerValue); } internal void AddValue(string headerName, string headerValue) { base.Add(headerName, headerValue); } internal string[] GetValues_internal(string header, bool split) { if (header == null) throw new ArgumentNullException("header"); string[] values = base.GetValues(header); if (values == null || values.Length == 0) return null; if (split && IsMultiValue(header)) { List<string> separated = null; foreach (var value in values) { if (value.IndexOf(',') < 0) { if (separated != null) separated.Add(value); continue; } if (separated == null) { separated = new List<string>(values.Length + 1); foreach (var v in values) { if (v == value) break; separated.Add(v); } } var slices = value.Split(','); var slices_length = slices.Length; if (value[value.Length - 1] == ',') --slices_length; for (int i = 0; i < slices_length; ++i) { separated.Add(slices[i].Trim()); } } if (separated != null) return separated.ToArray(); } return values; } public override string[] GetValues(string header) { return GetValues_internal(header, true); } public override string[] GetValues(int index) { string[] values = base.GetValues(index); if (values == null || values.Length == 0) { return null; } return values; } public static bool IsRestricted(string headerName) { return IsRestricted(headerName, false); } public static bool IsRestricted(string headerName, bool response) { if (headerName == null) throw new ArgumentNullException("headerName"); if (headerName.Length == 0) throw new ArgumentException("empty string", "headerName"); if (!IsHeaderName(headerName)) throw new ArgumentException("Invalid character in header"); HeaderInfo info; if (!headers.TryGetValue(headerName, out info)) return false; var flag = response ? HeaderInfo.Response : HeaderInfo.Request; return (info & flag) != 0; } public override void Remove(string name) { if (name == null) throw new ArgumentNullException("name"); CheckRestrictedHeader(name); base.Remove(name); } public override void Set(string name, string value) { if (name == null) throw new ArgumentNullException("name"); if (!IsHeaderName(name)) throw new ArgumentException("invalid header name"); if (value == null) value = String.Empty; else value = value.Trim(); if (!IsHeaderValue(value)) throw new ArgumentException("invalid header value"); CheckRestrictedHeader(name); base.Set(name, value); } public byte[] ToByteArray() { return Encoding.UTF8.GetBytes(ToString()); } internal string ToStringMultiValue() { StringBuilder sb = new StringBuilder(); int count = base.Count; for (int i = 0; i < count; i++) { string key = GetKey(i); if (IsMultiValue(key)) { foreach (string v in GetValues(i)) { sb.Append(key) .Append(": ") .Append(v) .Append("\r\n"); } } else { sb.Append(key) .Append(": ") .Append(Get(i)) .Append("\r\n"); } } return sb.Append("\r\n").ToString(); } public override string ToString() { StringBuilder sb = new StringBuilder(); int count = base.Count; for (int i = 0; i < count; i++) sb.Append(GetKey(i)) .Append(": ") .Append(Get(i)) .Append("\r\n"); return sb.Append("\r\n").ToString(); } public override string[] AllKeys { get { return base.AllKeys; } } public override int Count { get { return base.Count; } } public override KeysCollection Keys { get { return base.Keys; } } public override string Get(int index) { return base.Get(index); } public override string Get(string name) { return base.Get(name); } public override string GetKey(int index) { return base.GetKey(index); } public override void Clear() { base.Clear(); } public override IEnumerator GetEnumerator() { return base.GetEnumerator(); } // Internal Methods // With this we don't check for invalid characters in header. See bug #55994. internal void SetInternal(string header) { int pos = header.IndexOf(':'); if (pos == -1) throw new ArgumentException("no colon found", "header"); SetInternal(header.Substring(0, pos), header.Substring(pos + 1)); } internal void SetInternal(string name, string value) { if (value == null) value = String.Empty; else value = value.Trim(); if (!IsHeaderValue(value)) throw new ArgumentException("invalid header value"); if (IsMultiValue(name)) { base.Add(name, value); } else { base.Remove(name); base.Set(name, value); } } // Private Methods void CheckRestrictedHeader(string headerName) { if (!headerRestriction.HasValue) return; HeaderInfo info; if (!headers.TryGetValue(headerName, out info)) return; if ((info & headerRestriction.Value) != 0) throw new ArgumentException("This header must be modified with the appropriate property."); } internal static bool IsMultiValue(string headerName) { if (headerName == null) return false; HeaderInfo info; return headers.TryGetValue(headerName, out info) && (info & HeaderInfo.MultiValue) != 0; } internal static bool IsHeaderValue(string value) { // TEXT any 8 bit value except CTL's (0-31 and 127) // but including \r\n space and \t // after a newline at least one space or \t must follow // certain header fields allow comments () int len = value.Length; for (int i = 0; i < len; i++) { char c = value[i]; if (c == 127) return false; if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t')) return false; if (c == '\n' && ++i < len) { c = value[i]; if (c != ' ' && c != '\t') return false; } } return true; } internal static bool IsHeaderName(string name) { if (name == null || name.Length == 0) return false; int len = name.Length; for (int i = 0; i < len; i++) { char c = name[i]; if (c > 126 || !allowed_chars[c]) return false; } return true; } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Gl { /// <summary> /// [GL] glGenQueriesEXT: Binding for glGenQueriesEXT. /// </summary> /// <param name="ids"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static void GenQueriesEXT(uint[] ids) { unsafe { fixed (uint* p_ids = ids) { Debug.Assert(Delegates.pglGenQueriesEXT != null, "pglGenQueriesEXT not implemented"); Delegates.pglGenQueriesEXT(ids.Length, p_ids); LogCommand("glGenQueriesEXT", null, ids.Length, ids ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGenQueriesEXT: Binding for glGenQueriesEXT. /// </summary> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static uint GenQueryEXT() { uint retValue; unsafe { Delegates.pglGenQueriesEXT(1, &retValue); LogCommand("glGenQueriesEXT", null, 1, "{ " + retValue + " }" ); } DebugCheckErrors(null); return (retValue); } /// <summary> /// [GL] glDeleteQueriesEXT: Binding for glDeleteQueriesEXT. /// </summary> /// <param name="ids"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static void DeleteQueriesEXT(params uint[] ids) { unsafe { fixed (uint* p_ids = ids) { Debug.Assert(Delegates.pglDeleteQueriesEXT != null, "pglDeleteQueriesEXT not implemented"); Delegates.pglDeleteQueriesEXT(ids.Length, p_ids); LogCommand("glDeleteQueriesEXT", null, ids.Length, ids ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glIsQueryEXT: Binding for glIsQueryEXT. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static bool IsQueryEXT(uint id) { bool retValue; Debug.Assert(Delegates.pglIsQueryEXT != null, "pglIsQueryEXT not implemented"); retValue = Delegates.pglIsQueryEXT(id); LogCommand("glIsQueryEXT", retValue, id ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GL] glBeginQueryEXT: Binding for glBeginQueryEXT. /// </summary> /// <param name="target"> /// A <see cref="T:QueryTarget"/>. /// </param> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static void BeginQueryEXT(QueryTarget target, uint id) { Debug.Assert(Delegates.pglBeginQueryEXT != null, "pglBeginQueryEXT not implemented"); Delegates.pglBeginQueryEXT((int)target, id); LogCommand("glBeginQueryEXT", null, target, id ); DebugCheckErrors(null); } /// <summary> /// [GL] glEndQueryEXT: Binding for glEndQueryEXT. /// </summary> /// <param name="target"> /// A <see cref="T:QueryTarget"/>. /// </param> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static void EndQueryEXT(QueryTarget target) { Debug.Assert(Delegates.pglEndQueryEXT != null, "pglEndQueryEXT not implemented"); Delegates.pglEndQueryEXT((int)target); LogCommand("glEndQueryEXT", null, target ); DebugCheckErrors(null); } /// <summary> /// [GL] glGetQueryivEXT: Binding for glGetQueryivEXT. /// </summary> /// <param name="target"> /// A <see cref="T:QueryTarget"/>. /// </param> /// <param name="pname"> /// A <see cref="T:QueryParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static void GetQueryEXT(QueryTarget target, QueryParameterName pname, [Out] int[] @params) { unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglGetQueryivEXT != null, "pglGetQueryivEXT not implemented"); Delegates.pglGetQueryivEXT((int)target, (int)pname, p_params); LogCommand("glGetQueryivEXT", null, target, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetQueryivEXT: Binding for glGetQueryivEXT. /// </summary> /// <param name="target"> /// A <see cref="T:QueryTarget"/>. /// </param> /// <param name="pname"> /// A <see cref="T:QueryParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static void GetQueryEXT(QueryTarget target, QueryParameterName pname, out int @params) { unsafe { fixed (int* p_params = &@params) { Debug.Assert(Delegates.pglGetQueryivEXT != null, "pglGetQueryivEXT not implemented"); Delegates.pglGetQueryivEXT((int)target, (int)pname, p_params); LogCommand("glGetQueryivEXT", null, target, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetQueryObjectuivEXT: Binding for glGetQueryObjectuivEXT. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:QueryObjectParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static void GetQueryObjectuivEXT(uint id, QueryObjectParameterName pname, [Out] uint[] @params) { unsafe { fixed (uint* p_params = @params) { Debug.Assert(Delegates.pglGetQueryObjectuivEXT != null, "pglGetQueryObjectuivEXT not implemented"); Delegates.pglGetQueryObjectuivEXT(id, (int)pname, p_params); LogCommand("glGetQueryObjectuivEXT", null, id, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetQueryObjectuivEXT: Binding for glGetQueryObjectuivEXT. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:QueryObjectParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] public static void GetQueryObjectuivEXT(uint id, QueryObjectParameterName pname, out uint @params) { unsafe { fixed (uint* p_params = &@params) { Debug.Assert(Delegates.pglGetQueryObjectuivEXT != null, "pglGetQueryObjectuivEXT not implemented"); Delegates.pglGetQueryObjectuivEXT(id, (int)pname, p_params); LogCommand("glGetQueryObjectuivEXT", null, id, pname, @params ); } } DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glGenQueriesEXT(int n, uint* ids); [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [ThreadStatic] internal static glGenQueriesEXT pglGenQueriesEXT; [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glDeleteQueriesEXT(int n, uint* ids); [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [ThreadStatic] internal static glDeleteQueriesEXT pglDeleteQueriesEXT; [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal delegate bool glIsQueryEXT(uint id); [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [ThreadStatic] internal static glIsQueryEXT pglIsQueryEXT; [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glBeginQueryEXT(int target, uint id); [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [ThreadStatic] internal static glBeginQueryEXT pglBeginQueryEXT; [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glEndQueryEXT(int target); [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [ThreadStatic] internal static glEndQueryEXT pglEndQueryEXT; [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetQueryivEXT(int target, int pname, int* @params); [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [ThreadStatic] internal static glGetQueryivEXT pglGetQueryivEXT; [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetQueryObjectuivEXT(uint id, int pname, uint* @params); [RequiredByFeature("GL_EXT_disjoint_timer_query", Api = "gles2")] [RequiredByFeature("GL_EXT_occlusion_query_boolean", Api = "gles2")] [ThreadStatic] internal static glGetQueryObjectuivEXT pglGetQueryObjectuivEXT; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Avatar.Chat { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ChatModule")] public class ChatModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int DEBUG_CHANNEL = 2147483647; private bool m_enabled = true; private int m_saydistance = 20; private int m_shoutdistance = 100; private int m_whisperdistance = 10; private List<Scene> m_scenes = new List<Scene>(); internal object m_syncy = new object(); internal IConfig m_config; #region ISharedRegionModule Members public virtual void Initialise(IConfigSource config) { m_config = config.Configs["Chat"]; if (null == m_config) { m_log.Info("[CHAT]: no config found, plugin disabled"); m_enabled = false; return; } if (!m_config.GetBoolean("enabled", true)) { m_log.Info("[CHAT]: plugin disabled by configuration"); m_enabled = false; return; } m_whisperdistance = config.Configs["Chat"].GetInt("whisper_distance", m_whisperdistance); m_saydistance = config.Configs["Chat"].GetInt("say_distance", m_saydistance); m_shoutdistance = config.Configs["Chat"].GetInt("shout_distance", m_shoutdistance); } public virtual void AddRegion(Scene scene) { if (!m_enabled) return; lock (m_syncy) { if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnChatFromWorld += OnChatFromWorld; scene.EventManager.OnChatBroadcast += OnChatBroadcast; } } m_log.InfoFormat("[CHAT]: Initialized for {0} w:{1} s:{2} S:{3}", scene.RegionInfo.RegionName, m_whisperdistance, m_saydistance, m_shoutdistance); } public virtual void RegionLoaded(Scene scene) { } public virtual void RemoveRegion(Scene scene) { if (!m_enabled) return; lock (m_syncy) { if (m_scenes.Contains(scene)) { scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnChatFromWorld -= OnChatFromWorld; scene.EventManager.OnChatBroadcast -= OnChatBroadcast; m_scenes.Remove(scene); } } } public virtual void Close() { } public virtual void PostInitialise() { } public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "ChatModule"; } } #endregion public virtual void OnNewClient(IClientAPI client) { client.OnChatFromClient += OnChatFromClient; } protected OSChatMessage FixPositionOfChatMessage(OSChatMessage c) { ScenePresence avatar; Scene scene = (Scene)c.Scene; if ((avatar = scene.GetScenePresence(c.Sender.AgentId)) != null) c.Position = avatar.AbsolutePosition; return c; } public virtual void OnChatFromClient(Object sender, OSChatMessage c) { c = FixPositionOfChatMessage(c); // redistribute to interested subscribers Scene scene = (Scene)c.Scene; scene.EventManager.TriggerOnChatFromClient(sender, c); // early return if not on public or debug channel if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; // sanity check: if (c.Sender == null) { m_log.ErrorFormat("[CHAT]: OnChatFromClient from {0} has empty Sender field!", sender); return; } DeliverChatToAvatars(ChatSourceType.Agent, c); } public virtual void OnChatFromWorld(Object sender, OSChatMessage c) { // early return if not on public or debug channel if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; DeliverChatToAvatars(ChatSourceType.Object, c); } protected virtual void DeliverChatToAvatars(ChatSourceType sourceType, OSChatMessage c) { string fromName = c.From; UUID fromID = UUID.Zero; UUID ownerID = UUID.Zero; UUID targetID = c.TargetUUID; string message = c.Message; IScene scene = c.Scene; Vector3 fromPos = c.Position; Vector3 regionPos = new Vector3(scene.RegionInfo.RegionLocX * Constants.RegionSize, scene.RegionInfo.RegionLocY * Constants.RegionSize, 0); if (c.Channel == DEBUG_CHANNEL) c.Type = ChatTypeEnum.DebugChannel; switch (sourceType) { case ChatSourceType.Agent: if (!(scene is Scene)) { m_log.WarnFormat("[CHAT]: scene {0} is not a Scene object, cannot obtain scene presence for {1}", scene.RegionInfo.RegionName, c.Sender.AgentId); return; } ScenePresence avatar = (scene as Scene).GetScenePresence(c.Sender.AgentId); fromPos = avatar.AbsolutePosition; fromName = avatar.Name; fromID = c.Sender.AgentId; ownerID = c.Sender.AgentId; break; case ChatSourceType.Object: fromID = c.SenderUUID; if (c.SenderObject != null && c.SenderObject is SceneObjectPart) ownerID = ((SceneObjectPart)c.SenderObject).OwnerID; break; } // TODO: iterate over message if (message.Length >= 1000) // libomv limit message = message.Substring(0, 1000); // m_log.DebugFormat( // "[CHAT]: DCTA: fromID {0} fromName {1}, region{2}, cType {3}, sType {4}, targetID {5}", // fromID, fromName, scene.RegionInfo.RegionName, c.Type, sourceType, targetID); HashSet<UUID> receiverIDs = new HashSet<UUID>(); foreach (Scene s in m_scenes) { if (targetID == UUID.Zero) { // This should use ForEachClient, but clients don't have a position. // If camera is moved into client, then camera position can be used s.ForEachRootScenePresence( delegate(ScenePresence presence) { if (TrySendChatMessage( presence, fromPos, regionPos, fromID, ownerID, fromName, c.Type, message, sourceType, false)) receiverIDs.Add(presence.UUID); } ); } else { // This is a send to a specific client eg from llRegionSayTo // no need to check distance etc, jand send is as say ScenePresence presence = s.GetScenePresence(targetID); if (presence != null && !presence.IsChildAgent) { if (TrySendChatMessage( presence, fromPos, regionPos, fromID, ownerID, fromName, ChatTypeEnum.Say, message, sourceType, true)) receiverIDs.Add(presence.UUID); } } } (scene as Scene).EventManager.TriggerOnChatToClients( fromID, receiverIDs, message, c.Type, fromPos, fromName, sourceType, ChatAudibleLevel.Fully); } static private Vector3 CenterOfRegion = new Vector3(128, 128, 30); public virtual void OnChatBroadcast(Object sender, OSChatMessage c) { if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; ChatTypeEnum cType = c.Type; if (c.Channel == DEBUG_CHANNEL) cType = ChatTypeEnum.DebugChannel; if (cType == ChatTypeEnum.Region) cType = ChatTypeEnum.Say; if (c.Message.Length > 1100) c.Message = c.Message.Substring(0, 1000); // broadcast chat works by redistributing every incoming chat // message to each avatar in the scene. string fromName = c.From; UUID fromID = UUID.Zero; ChatSourceType sourceType = ChatSourceType.Object; if (null != c.Sender) { ScenePresence avatar = (c.Scene as Scene).GetScenePresence(c.Sender.AgentId); fromID = c.Sender.AgentId; fromName = avatar.Name; sourceType = ChatSourceType.Agent; } else if (c.SenderUUID != UUID.Zero) { fromID = c.SenderUUID; } // m_log.DebugFormat("[CHAT] Broadcast: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, cType, sourceType); HashSet<UUID> receiverIDs = new HashSet<UUID>(); ((Scene)c.Scene).ForEachRootClient( delegate(IClientAPI client) { // don't forward SayOwner chat from objects to // non-owner agents if ((c.Type == ChatTypeEnum.Owner) && (null != c.SenderObject) && (((SceneObjectPart)c.SenderObject).OwnerID != client.AgentId)) return; client.SendChatMessage( c.Message, (byte)cType, CenterOfRegion, fromName, fromID, fromID, (byte)sourceType, (byte)ChatAudibleLevel.Fully); receiverIDs.Add(client.AgentId); }); (c.Scene as Scene).EventManager.TriggerOnChatToClients( fromID, receiverIDs, c.Message, cType, CenterOfRegion, fromName, sourceType, ChatAudibleLevel.Fully); } /// <summary> /// Try to send a message to the given presence /// </summary> /// <param name="presence">The receiver</param> /// <param name="fromPos"></param> /// <param name="regionPos">/param> /// <param name="fromAgentID"></param> /// <param name='ownerID'> /// Owner of the message. For at least some messages from objects, this has to be correctly filled with the owner's UUID. /// This is the case for script error messages in viewer 3 since LLViewer change EXT-7762 /// </param> /// <param name="fromName"></param> /// <param name="type"></param> /// <param name="message"></param> /// <param name="src"></param> /// <returns>true if the message was sent to the receiver, false if it was not sent due to failing a /// precondition</returns> protected virtual bool TrySendChatMessage( ScenePresence presence, Vector3 fromPos, Vector3 regionPos, UUID fromAgentID, UUID ownerID, string fromName, ChatTypeEnum type, string message, ChatSourceType src, bool ignoreDistance) { // don't send stuff to child agents if (presence.IsChildAgent) return false; Vector3 fromRegionPos = fromPos + regionPos; Vector3 toRegionPos = presence.AbsolutePosition + new Vector3(presence.Scene.RegionInfo.RegionLocX * Constants.RegionSize, presence.Scene.RegionInfo.RegionLocY * Constants.RegionSize, 0); int dis = (int)Util.GetDistanceTo(toRegionPos, fromRegionPos); if (!ignoreDistance) { if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance || type == ChatTypeEnum.Say && dis > m_saydistance || type == ChatTypeEnum.Shout && dis > m_shoutdistance) { return false; } } // TODO: should change so the message is sent through the avatar rather than direct to the ClientView presence.ControllingClient.SendChatMessage( message, (byte) type, fromPos, fromName, fromAgentID, ownerID, (byte)src, (byte)ChatAudibleLevel.Fully); return true; } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Xml.Serialization; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Data; ////////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend. // //Override methods in the logic front class. // ////////////////////////////////////////////////////////////// namespace VotingInfo.Database.Logic.Data { [Serializable] public abstract partial class CandidateMetaDataLogicBase : LogicBase<CandidateMetaDataLogicBase> { //Put your code in a separate file. This is auto generated. [XmlArray] public List<CandidateMetaDataContract> Results; public CandidateMetaDataLogicBase() { Results = new List<CandidateMetaDataContract>(); } /// <summary> /// Run CandidateMetaData_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldContentInspectionId , int fldCandidateId , int fldMetaDataId , string fldMetaDataValue ) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@CandidateId", fldCandidateId) , new SqlParameter("@MetaDataId", fldMetaDataId) , new SqlParameter("@MetaDataValue", fldMetaDataValue) }); result = (int?)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Run CandidateMetaData_Insert. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldContentInspectionId , int fldCandidateId , int fldMetaDataId , string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@CandidateId", fldCandidateId) , new SqlParameter("@MetaDataId", fldMetaDataId) , new SqlParameter("@MetaDataValue", fldMetaDataValue) }); return (int?)cmd.ExecuteScalar(); } } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>1, if insert was successful</returns> public int Insert(CandidateMetaDataContract row) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@CandidateId", row.CandidateId) , new SqlParameter("@MetaDataId", row.MetaDataId) , new SqlParameter("@MetaDataValue", row.MetaDataValue) }); result = (int?)cmd.ExecuteScalar(); row.CandidateMetaDataId = result; } }); return result != null ? 1 : 0; } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>1, if insert was successful</returns> public int Insert(CandidateMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { int? result = null; using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@CandidateId", row.CandidateId) , new SqlParameter("@MetaDataId", row.MetaDataId) , new SqlParameter("@MetaDataValue", row.MetaDataValue) }); result = (int?)cmd.ExecuteScalar(); row.CandidateMetaDataId = result; } return result != null ? 1 : 0; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<CandidateMetaDataContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = InsertAll(rows, x, null); }); return rowCount; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<CandidateMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Insert(row, connection, transaction); return rowCount; } /// <summary> /// Run CandidateMetaData_Update. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> public virtual int Update(int fldCandidateMetaDataId , int fldContentInspectionId , int fldCandidateId , int fldMetaDataId , string fldMetaDataValue ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", fldCandidateMetaDataId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@CandidateId", fldCandidateId) , new SqlParameter("@MetaDataId", fldMetaDataId) , new SqlParameter("@MetaDataValue", fldMetaDataValue) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run CandidateMetaData_Update. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(int fldCandidateMetaDataId , int fldContentInspectionId , int fldCandidateId , int fldMetaDataId , string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", fldCandidateMetaDataId) , new SqlParameter("@ContentInspectionId", fldContentInspectionId) , new SqlParameter("@CandidateId", fldCandidateId) , new SqlParameter("@MetaDataId", fldMetaDataId) , new SqlParameter("@MetaDataValue", fldMetaDataValue) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(CandidateMetaDataContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", row.CandidateMetaDataId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@CandidateId", row.CandidateId) , new SqlParameter("@MetaDataId", row.MetaDataId) , new SqlParameter("@MetaDataValue", row.MetaDataValue) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(CandidateMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", row.CandidateMetaDataId) , new SqlParameter("@ContentInspectionId", row.ContentInspectionId) , new SqlParameter("@CandidateId", row.CandidateId) , new SqlParameter("@MetaDataId", row.MetaDataId) , new SqlParameter("@MetaDataValue", row.MetaDataValue) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<CandidateMetaDataContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = UpdateAll(rows, x, null); }); return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<CandidateMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Update(row, connection, transaction); return rowCount; } /// <summary> /// Run CandidateMetaData_Delete. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> public virtual int Delete(int fldCandidateMetaDataId ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", fldCandidateMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run CandidateMetaData_Delete. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(int fldCandidateMetaDataId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", fldCandidateMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(CandidateMetaDataContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", row.CandidateMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(CandidateMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", row.CandidateMetaDataId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<CandidateMetaDataContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = DeleteAll(rows, x, null); }); return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<CandidateMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Delete(row, connection, transaction); return rowCount; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldCandidateMetaDataId ) { bool result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Exists]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", fldCandidateMetaDataId) }); result = (bool)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldCandidateMetaDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Exists]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", fldCandidateMetaDataId) }); return (bool)cmd.ExecuteScalar(); } } /// <summary> /// Run CandidateMetaData_Search, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool Search(string fldMetaDataValue ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Search]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataValue", fldMetaDataValue) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run CandidateMetaData_Search, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldMetaDataValue">Value for MetaDataValue</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool Search(string fldMetaDataValue , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_Search]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataValue", fldMetaDataValue) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run CandidateMetaData_SelectAll, and return results as a list of CandidateMetaDataRow. /// </summary> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectAll() { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectAll]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run CandidateMetaData_SelectAll, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectAll]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run CandidateMetaData_SelectBy_CandidateMetaDataId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectBy_CandidateMetaDataId(int fldCandidateMetaDataId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectBy_CandidateMetaDataId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", fldCandidateMetaDataId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run CandidateMetaData_SelectBy_CandidateMetaDataId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldCandidateMetaDataId">Value for CandidateMetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectBy_CandidateMetaDataId(int fldCandidateMetaDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectBy_CandidateMetaDataId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateMetaDataId", fldCandidateMetaDataId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run CandidateMetaData_SelectBy_ContentInspectionId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectBy_ContentInspectionId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run CandidateMetaData_SelectBy_ContentInspectionId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldContentInspectionId">Value for ContentInspectionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectBy_ContentInspectionId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@ContentInspectionId", fldContentInspectionId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run CandidateMetaData_SelectBy_CandidateId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectBy_CandidateId(int fldCandidateId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectBy_CandidateId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run CandidateMetaData_SelectBy_CandidateId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldCandidateId">Value for CandidateId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectBy_CandidateId(int fldCandidateId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectBy_CandidateId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@CandidateId", fldCandidateId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run CandidateMetaData_SelectBy_MetaDataId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectBy_MetaDataId(int fldMetaDataId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectBy_MetaDataId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataId", fldMetaDataId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run CandidateMetaData_SelectBy_MetaDataId, and return results as a list of CandidateMetaDataRow. /// </summary> /// <param name="fldMetaDataId">Value for MetaDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of CandidateMetaDataRow.</returns> public virtual bool SelectBy_MetaDataId(int fldMetaDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[CandidateMetaData_SelectBy_MetaDataId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@MetaDataId", fldMetaDataId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Read all items into this collection /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadAll(SqlDataReader reader) { var canRead = ReadOne(reader); var result = canRead; while (canRead) canRead = ReadOne(reader); return result; } /// <summary> /// Read one item into Results /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadOne(SqlDataReader reader) { if (reader.Read()) { Results.Add( new CandidateMetaDataContract { CandidateMetaDataId = reader.GetInt32(0), ContentInspectionId = reader.GetInt32(1), CandidateId = reader.GetInt32(2), MetaDataId = reader.GetInt32(3), MetaDataValue = reader.GetString(4), }); return true; } return false; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public virtual int Save(CandidateMetaDataContract row) { if(row == null) return 0; if(row.CandidateMetaDataId != null) return Update(row); return Insert(row); } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Save(CandidateMetaDataContract row, SqlConnection connection, SqlTransaction transaction) { if(row == null) return 0; if(row.CandidateMetaDataId != null) return Update(row, connection, transaction); return Insert(row, connection, transaction); } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<CandidateMetaDataContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { foreach(var row in rows) rowCount += Save(row, x, null); }); return rowCount; } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<CandidateMetaDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Save(row, connection, transaction); return rowCount; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Security.Cryptography.Apple; namespace System.Security.Cryptography { internal static partial class ECDiffieHellmanImplementation { public sealed partial class ECDiffieHellmanSecurityTransforms : ECDiffieHellman { private readonly EccSecurityTransforms _ecc = new EccSecurityTransforms(nameof(ECDiffieHellman)); public ECDiffieHellmanSecurityTransforms() { base.KeySize = 521; } internal ECDiffieHellmanSecurityTransforms(SafeSecKeyRefHandle publicKey) { KeySizeValue = _ecc.SetKeyAndGetSize(SecKeyPair.PublicOnly(publicKey)); } internal ECDiffieHellmanSecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey) { KeySizeValue = _ecc.SetKeyAndGetSize(SecKeyPair.PublicPrivatePair(publicKey, privateKey)); } public override KeySizes[] LegalKeySizes { get { // Return the three sizes that can be explicitly set (for backwards compatibility) return new[] { new KeySizes(minSize: 256, maxSize: 384, skipSize: 128), new KeySizes(minSize: 521, maxSize: 521, skipSize: 0), }; } } public override int KeySize { get { return base.KeySize; } set { if (KeySize == value) return; // Set the KeySize before freeing the key so that an invalid value doesn't throw away the key base.KeySize = value; _ecc.DisposeKey(); } } private void ThrowIfDisposed() { _ecc.ThrowIfDisposed(); } protected override void Dispose(bool disposing) { if (disposing) { _ecc.Dispose(); } base.Dispose(disposing); } public override ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly); } public override ECParameters ExportParameters(bool includePrivateParameters) { return _ecc.ExportParameters(includePrivateParameters, KeySize); } public override void ImportParameters(ECParameters parameters) { KeySizeValue = _ecc.ImportParameters(parameters); } public override void ImportSubjectPublicKeyInfo( ReadOnlySpan<byte> source, out int bytesRead) { KeySizeValue = _ecc.ImportSubjectPublicKeyInfo(source, out bytesRead); } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead); } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead); } public override void GenerateKey(ECCurve curve) { KeySizeValue = _ecc.GenerateKey(curve); } private SecKeyPair GetKeys() { return _ecc.GetOrGenerateKeys(KeySize); } public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey) => DeriveKeyFromHash(otherPartyPublicKey, HashAlgorithmName.SHA256, null, null); public override byte[] DeriveKeyFromHash( ECDiffieHellmanPublicKey otherPartyPublicKey, HashAlgorithmName hashAlgorithm, byte[] secretPrepend, byte[] secretAppend) { if (otherPartyPublicKey == null) throw new ArgumentNullException(nameof(otherPartyPublicKey)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); ThrowIfDisposed(); return ECDiffieHellmanDerivation.DeriveKeyFromHash( otherPartyPublicKey, hashAlgorithm, secretPrepend, secretAppend, (pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher)); } public override byte[] DeriveKeyFromHmac( ECDiffieHellmanPublicKey otherPartyPublicKey, HashAlgorithmName hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend) { if (otherPartyPublicKey == null) throw new ArgumentNullException(nameof(otherPartyPublicKey)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm)); ThrowIfDisposed(); return ECDiffieHellmanDerivation.DeriveKeyFromHmac( otherPartyPublicKey, hashAlgorithm, hmacKey, secretPrepend, secretAppend, (pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher)); } public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) { if (otherPartyPublicKey == null) throw new ArgumentNullException(nameof(otherPartyPublicKey)); if (prfLabel == null) throw new ArgumentNullException(nameof(prfLabel)); if (prfSeed == null) throw new ArgumentNullException(nameof(prfSeed)); ThrowIfDisposed(); return ECDiffieHellmanDerivation.DeriveKeyTls( otherPartyPublicKey, prfLabel, prfSeed, (pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher)); } private byte[] DeriveSecretAgreement(ECDiffieHellmanPublicKey otherPartyPublicKey, IncrementalHash hasher) { if (!(otherPartyPublicKey is ECDiffieHellmanSecurityTransformsPublicKey secTransPubKey)) { secTransPubKey = new ECDiffieHellmanSecurityTransformsPublicKey(otherPartyPublicKey.ExportParameters()); } try { SafeSecKeyRefHandle otherPublic = secTransPubKey.KeyHandle; if (Interop.AppleCrypto.EccGetKeySizeInBits(otherPublic) != KeySize) { throw new ArgumentException( SR.Cryptography_ArgECDHKeySizeMismatch, nameof(otherPartyPublicKey)); } SafeSecKeyRefHandle thisPrivate = GetKeys().PrivateKey; if (thisPrivate == null) { throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); } // Since Apple only supports secp256r1, secp384r1, and secp521r1; and 521 fits in // 66 bytes ((521 + 7) / 8), the Span path will always succeed. Span<byte> secretSpan = stackalloc byte[66]; byte[] secret = Interop.AppleCrypto.EcdhKeyAgree( thisPrivate, otherPublic, secretSpan, out int bytesWritten); // Either we wrote to the span or we returned an array, but not both, and not neither. // ("neither" would have thrown) Debug.Assert( (bytesWritten == 0) != (secret == null), $"bytesWritten={bytesWritten}, (secret==null)={secret == null}"); if (hasher == null) { return secret ?? secretSpan.Slice(0, bytesWritten).ToArray(); } if (secret == null) { hasher.AppendData(secretSpan.Slice(0, bytesWritten)); } else { hasher.AppendData(secret); Array.Clear(secret, 0, secret.Length); } return null; } finally { if (!ReferenceEquals(otherPartyPublicKey, secTransPubKey)) { secTransPubKey.Dispose(); } } } public override ECDiffieHellmanPublicKey PublicKey => new ECDiffieHellmanSecurityTransformsPublicKey(ExportParameters(false)); private class ECDiffieHellmanSecurityTransformsPublicKey : ECDiffieHellmanPublicKey { private EccSecurityTransforms _ecc; public ECDiffieHellmanSecurityTransformsPublicKey(ECParameters ecParameters) { Debug.Assert(ecParameters.D == null); _ecc = new EccSecurityTransforms(nameof(ECDiffieHellmanPublicKey)); _ecc.ImportParameters(ecParameters); } public override string ToXmlString() { throw new PlatformNotSupportedException(); } /// <summary> /// There is no key blob format for OpenSSL ECDH like there is for Cng ECDH. Instead of allowing /// this to return a potentially confusing empty byte array, we opt to throw instead. /// </summary> public override byte[] ToByteArray() { throw new PlatformNotSupportedException(); } protected override void Dispose(bool disposing) { if (disposing) { _ecc.Dispose(); } base.Dispose(disposing); } public override ECParameters ExportExplicitParameters() => throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly); public override ECParameters ExportParameters() => _ecc.ExportParameters(includePrivateParameters: false, keySizeInBits: -1); internal SafeSecKeyRefHandle KeyHandle => _ecc.GetOrGenerateKeys(-1).PublicKey; } } } }
//----------------------------------------------------------------------- // Original work Copyright (c) 2011, Oliver M. Haynold // Modified work Copyright (c) 2013, Suraj Gupta // Modified work Copyright (c) 2015, Atif Aziz // All rights reserved. //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace RserveCLI2 { using System.Diagnostics; /// <summary> /// A connection to an R session /// </summary> public sealed class RConnection : IDisposable { #region Constants and Fields /// <summary> /// Assign a Sexp /// </summary> internal const int CmdAssignSexp = 0x021; /// <summary> /// Attach session /// </summary> internal const int CmdAttachSession = 0x032; /// <summary> /// Close a file /// </summary> internal const int CmdCloseFile = 0x012; /// <summary> /// Create a file for writing /// </summary> internal const int CmdCreateFile = 0x011; /// <summary> /// Control command Evaluate /// </summary> internal const int CmdCtrlEval = 0x42; /// <summary> /// Control command Shutdown /// </summary> internal const int CmdCtrlShutdown = 0x44; /// <summary> /// Control command Source /// </summary> internal const int CmdCtrlSource = 0x45; /// <summary> /// Detached evaluation without returning a result /// </summary> internal const int CmdDetachedVoidEval = 0x031; /// <summary> /// Detach session, but keep it around /// </summary> internal const int CmdDettachSession = 0x030; /// <summary> /// Evaluate a Sexp /// </summary> internal const int CmdEval = 0x003; /// <summary> /// Login with username and password /// </summary> internal const int CmdLogin = 0x001; /// <summary> /// Open a file for reading /// </summary> internal const int CmdOpenFile = 0x010; /// <summary> /// Read from an open file /// </summary> internal const int CmdReadFile = 0x013; /// <summary> /// Remove a file /// </summary> internal const int CmdRemoveFile = 0x015; /// <summary> /// Set buffer size /// </summary> internal const int CmdSetBufferSize = 0x081; /// <summary> /// Set Encoding (I recommend UTF8) /// </summary> internal const int CmdSetEncoding = 0x082; /// <summary> /// Set a Sexp /// </summary> internal const int CmdSetSexp = 0x020; /// <summary> /// Shut down the Server /// </summary> internal const int CmdShutdown = 0x004; /// <summary> /// Evaluate without returning a result /// </summary> internal const int CmdVoidEval = 0x002; /// <summary> /// Write to an open file /// </summary> internal const int CmdWriteFile = 0x014; /// <summary> /// The socket we use to talk to Rserve /// </summary> private Socket _socket; /// <summary> /// The connection parameters we received from Rserve /// </summary> private string[] _connectionParameters; /// <summary> /// The protocol that handles communication for us /// </summary> private Qap1 _protocol; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the RConnection class. /// </summary> /// <param name="hostname"> /// Hostname of the server /// </param> /// <param name="port"> /// Port on which Rserve listens /// </param> /// <param name="user"> /// User name for the user, or nothing for no authentication /// </param> /// <param name="password"> /// Password for the user, or nothing /// </param> [Obsolete("Use the static " + nameof(Connect) + " method instead.")] public RConnection( string hostname, int port = 6311 , string user = null , string password = null ) : this(Async.RunSynchronously(ConnectAsync(hostname, port, CreateNetworkCredential(user, password)))) { } /// <summary> /// Initializes a new instance of the RConnection class. /// </summary> /// <param name="addr"> /// Address of the Rserve server, or nothing for localhost /// </param> /// <param name="port"> /// Port on which Rserve listens /// </param> /// <param name="user"> /// User name for the user, or nothing for no authentication /// </param> /// <param name="password"> /// Password for the user, or nothing /// </param> [Obsolete("Use the static " + nameof(Connect) + " method instead.")] public RConnection(IPAddress addr = null, int port = 6311, string user = null, string password = null) : this(Async.RunSynchronously(ConnectAsync(addr, port, CreateNetworkCredential(user, password)))) {} static NetworkCredential CreateNetworkCredential(string user, string password) => user != null || password != null ? new NetworkCredential(user, password) : null; RConnection(ref Socket socket) { _socket = socket; socket = null; // Owned } RConnection(RConnection connection) : this(ref connection._socket) { _protocol = connection._protocol; _connectionParameters = connection._connectionParameters; } /// <summary> /// Connects to Rserve identified by host name. /// </summary> /// <param name="hostname"> /// Hostname of the server /// </param> /// <param name="port"> /// Port on which Rserve listens /// </param> /// <param name="credentials"> /// Credentials for authentication or <c>null</c> for anonymous /// </param> public static RConnection Connect(string hostname, int port = 6311, NetworkCredential credentials = null) => Async.RunSynchronously(ConnectAsync(hostname, port, credentials)); /// <summary> /// Asynchronously connects to Rserve identified by host name. /// </summary> /// <param name="hostname"> /// Hostname of the server /// </param> /// <param name="port"> /// Port on which Rserve listens /// </param> /// <param name="credentials"> /// Credentials for authentication or <c>null</c> for anonymous /// </param> public static async Task<RConnection> ConnectAsync(string hostname, int port = 6311, NetworkCredential credentials = null) { var ipe = await Dns.GetHostEntryAsync(hostname).ContinueContextFree(); foreach (var addr in ipe.AddressList) { var connection = await ConnectAsync(addr, port, credentials).ContinueContextFree(); if (connection != null) return connection; } return null; // unsuccessful } /// <summary> /// Connects to Rserve identified by an IP address. /// </summary> /// <param name="addr"> /// Address of the Rserve server, or nothing for localhost /// </param> /// <param name="port"> /// Port on which the server listens /// </param> /// <param name="credentials"> /// Credentials for authentication or <c>null</c> for anonymous /// </param> public static RConnection Connect(IPAddress addr = null, int port = 6311, NetworkCredential credentials = null) => Async.RunSynchronously(ConnectAsync(addr, port, credentials)); /// <summary> /// Asynchronously connects to Rserve identified by an IP address. /// </summary> /// <param name="addr"> /// Address of the Rserve server, or nothing for localhost /// </param> /// <param name="port"> /// Port on which the server listens /// </param> /// <param name="credentials"> /// Credentials for authentication or <c>null</c> for anonymous /// </param> public static async Task<RConnection> ConnectAsync(IPAddress addr = null, int port = 6311, NetworkCredential credentials = null) { var ipe = new IPEndPoint(addr ?? new IPAddress(new byte[] { 127, 0, 0, 1 }), port); Socket socket = null; try { socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Connect with a one-second timeout // From http://stackoverflow.com/questions/1062035/how-to-config-socket-connect-timeout-in-c-sharp var connectTask = socket.ConnectAsync(ipe); var timeoutTask = Task.Delay(TimeSpan.FromSeconds(1)); var completedTask = await Task.WhenAny(connectTask, timeoutTask) .ContinueContextFree(); if (completedTask == timeoutTask) { connectTask.IgnoreFault(); await timeoutTask.ContinueContextFree(); throw new SocketException((int)SocketError.TimedOut); } await connectTask.ContinueContextFree(); if (!socket.Connected) return null; var connection = new RConnection(ref socket); await connection.InitAsync(credentials?.UserName, credentials?.Password).ContinueContextFree(); return connection; } finally { socket?.Dispose(); } } #endregion #region Indexers /// <summary> /// Syntactic sugar for variable assignment and expression evaluation. /// </summary> /// <param name="s">The variable to be assigned to or the expression to be evaluated</param> /// <returns>The value of the expression</returns> public Sexp this[ string s ] { get { return Eval( s ); } set { Assign( s , value ); } } #endregion #region Public Methods /// <summary> /// Assign an R variable on the server. this[symbol] = value is syntactic sugar for this operation. /// </summary> /// <param name="symbol"> /// Variable name /// </param> /// <param name="val"> /// Sexp to be assigned to the variable /// </param> public void Assign( string symbol , Sexp val ) => Async.RunSynchronously( AssignAsync( symbol , val ) ); /// <summary> /// Asynchronously assign an R variable on the server. /// </summary> /// <param name="symbol"> /// Variable name /// </param> /// <param name="val"> /// Sexp to be assigned to the variable /// </param> public Task AssignAsync( string symbol , Sexp val ) => _protocol.CommandAsync( CmdAssignSexp , new object[] { symbol , val } ); /// <summary> /// Evaluate an R command and return the result. this[string] is syntactic sugar for the same operation. /// </summary> /// <param name="s"> /// Command to be evaluated /// </param> /// <returns> /// Sexp that resulted from the command /// </returns> public Sexp Eval( string s ) => Async.RunSynchronously( EvalAsync( s ) ); /// <summary> /// Asynchronously evaluate an R command and return the result. /// </summary> /// <param name="s"> /// Command to be evaluated /// </param> /// <returns> /// Sexp that resulted from the command /// </returns> public async Task<Sexp> EvalAsync( string s ) { var res = await _protocol.CommandAsync( CmdEval , new object[] { s } ) .ContinueContextFree(); return ( Sexp )res[ 0 ]; } /// <summary> /// Read a file from the server /// </summary> /// <param name="fileName"> /// Name of the file to be read. Avoid jumping across directories. /// </param> /// <returns> /// Stream with the file data. /// </returns> public Stream ReadFile( string fileName ) => Async.RunSynchronously( ReadFileAsync( fileName ) ); /// <summary> /// Asynchronously read a file from the server /// </summary> /// <param name="fileName"> /// Name of the file to be read. Avoid jumping across directories. /// </param> /// <returns> /// Stream with the file data. /// </returns> public async Task<Stream> ReadFileAsync( string fileName ) { await _protocol.CommandAsync( CmdOpenFile , new object[] { fileName } ) .ContinueContextFree(); var resList = new List<byte>(); while ( true ) { byte[] res = await _protocol.CommandReadStreamAsync( CmdReadFile , new object[] { } ) .ContinueContextFree(); if ( res.Length == 0 ) { break; } resList.AddRange( res ); } await _protocol.CommandAsync( CmdCloseFile , new object[] { } ).ContinueContextFree(); return new MemoryStream( resList.ToArray() ); } /// <summary> /// Delete a file from the server /// </summary> /// <param name="fileName"> /// Name of the file to be deleted /// </param> public void RemoveFile( string fileName ) => Async.RunSynchronously( RemoveFileAsync( fileName ) ); /// <summary> /// Asynchronously delete a file from the server /// </summary> /// <param name="fileName"> /// Name of the file to be deleted /// </param> public Task RemoveFileAsync( string fileName ) => _protocol.CommandAsync( CmdRemoveFile , new object[] { fileName } ); /// <summary> /// Evaluate an R command and don't return the result (for efficiency) /// </summary> /// <param name="s"> /// R command tp be evaluated /// </param> public void VoidEval( string s ) => Async.RunSynchronously( VoidEvalAsync( s ) ); /// <summary> /// Asynchronously evaluate an R command and don't return the result (for efficiency) /// </summary> /// <param name="s"> /// R command tp be evaluated /// </param> public Task VoidEvalAsync( string s ) => _protocol.CommandAsync( CmdVoidEval , new object[] { s } ); /// <summary> /// Write a file to the server. /// Note: It'd be better to return a Stream object to be written to, but Rserve doesn't seem to support an asynchronous connection /// for file reading and writing. /// </summary> /// <param name="fileName"> /// Name of the file to be written. Avoid jumping across directories. /// </param> /// <param name="data"> /// Data to be written to the file /// </param> public void WriteFile( string fileName , Stream data ) => Async.RunSynchronously(WriteFileAsync( fileName , data ) ); /// <summary> /// Asynchronously write a file to the server. /// Note: It'd be better to return a Stream object to be written to, but Rserve doesn't seem to support an asynchronous connection /// for file reading and writing. /// </summary> /// <param name="fileName"> /// Name of the file to be written. Avoid jumping across directories. /// </param> /// <param name="data"> /// Data to be written to the file /// </param> public async Task WriteFileAsync( string fileName , Stream data ) { var ms = new MemoryStream(); CopyTo( data , ms ); await _protocol.CommandAsync( CmdCreateFile , new object[] { fileName } ).ContinueContextFree(); await _protocol.CommandAsync( CmdWriteFile , new object[] { ms.ToArray() } ).ContinueContextFree(); await _protocol.CommandAsync( CmdCloseFile , new object[] { } ).ContinueContextFree(); } /// <summary> /// Attempt to shut down the server process cleanly. /// </summary> public void Shutdown() => Async.RunSynchronously( ShutdownAsync() ); /// <summary> /// Asynchronously attempt to shut down the server process cleanly. /// </summary> public Task ShutdownAsync() => _protocol.CommandAsync(CmdShutdown, new object[] { }); /// <summary> /// Attempt to shut down the server process cleanly. /// This command is asynchronous! /// </summary> public void ServerShutdown() => Async.RunSynchronously( ServerShutdownAsync() ); /// <summary> /// Attempt to shut down the server process cleanly. /// This command is asynchronous, including its transmission! /// </summary> public Task ServerShutdownAsync() => _protocol.CommandAsync(CmdCtrlShutdown, new object[] { }); #endregion #region Implemented Interfaces #region IDisposable /// <summary> /// Dispose of the connection /// </summary> public void Dispose() { if ( _socket != null ) { ( ( IDisposable )_socket ).Dispose(); } } #endregion #endregion #region Methods /// <summary> /// Common initialization routine called by the constructures /// </summary> /// <param name="user"> /// User name, or null for no authentication /// </param> /// <param name="password"> /// Password for the user, or null /// </param> async Task InitAsync(string user, string password) { var buf = new byte[ 32 ]; int received = await _socket.ReceiveAsync(buf).ContinueContextFree(); if ( received == 0 ) throw new RserveException( "Rserve connection was closed by the remote host" ); var parms = new List<string>(); for ( int i = 0 ; i < buf.Length ; i += 4 ) { var b = new byte[ 4 ]; Array.Copy( buf , i , b , 0 , 4 ); parms.Add( Encoding.ASCII.GetString( b ) ); } _connectionParameters = parms.ToArray(); if ( _connectionParameters[ 0 ] != "Rsrv" ) { throw new ProtocolViolationException("Did not receive Rserve ID signature."); } if (_connectionParameters[2] != "QAP1") { throw new NotSupportedException("Only QAP1 protocol is supported."); } _protocol = new Qap1(_socket); if (_connectionParameters.Contains("ARuc")) { string key = _connectionParameters.FirstOrDefault(x => !String.IsNullOrEmpty(x) && x[0] == 'K'); key = String.IsNullOrEmpty(key) ? "rs" : key.Substring(1, key.Length - 1); await LoginAsync(user, password, "uc", key).ContinueContextFree(); } else if (_connectionParameters.Contains("ARpt")) { await LoginAsync(user, password, "pt").ContinueContextFree(); } } /// <summary> /// Login to Rserver /// </summary> /// <param name="user"> /// User name for the user /// </param> /// <param name="password"> /// Password for the user /// </param> /// <param name="method"> /// pt for plain text /// </param> /// <param name="salt"> /// The salt to use to encrypt the password /// </param> async Task LoginAsync(string user, string password, string method, string salt = null) { if (user == null) throw new ArgumentNullException(nameof(user)); if (password == null) throw new ArgumentNullException(nameof(password)); switch (method) { case "pt": await _protocol.CommandAsync(CmdLogin, new object[] { user + "\n" + password }) .ContinueContextFree(); break; case "uc": password = new DES().Encrypt(password, salt); await _protocol.CommandAsync(CmdLogin, new object[] { user + "\n" + password }) .ContinueContextFree(); break; default: throw new ArgumentException("Could not interpret login method '" + method + "'"); } } /// <summary> /// Decompile of .NET 4's CopyTo /// </summary> public void CopyTo( Stream source , Stream destination ) { if ( destination != null ) { if ( source.CanRead || source.CanWrite ) { if ( destination.CanRead || destination.CanWrite ) { if ( source.CanRead ) { if ( destination.CanWrite ) { CopyTo( source , destination , 4096 ); return; } throw new NotSupportedException( "Stream does not support writing" ); } throw new NotSupportedException( "Stream does not support reading" ); } throw new ObjectDisposedException( "destination" , "Can not access a closed Stream." ); } throw new ObjectDisposedException( null , "Can not access a closed Stream." ); } throw new ArgumentNullException( "destination" ); } /// <summary> /// Decompile of .NET 4's InternalCopyTo /// </summary> private void CopyTo( Stream source , Stream destination , int bufferSize ) { byte[] numArray = new byte[ bufferSize ]; while ( true ) { int num = source.Read( numArray , 0 , ( int )numArray.Length ); int num1 = num; if ( num == 0 ) { break; } destination.Write( numArray , 0 , num1 ); } } #endregion } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors #if ENCODER namespace Iced.Intel { /// <summary> /// Memory operand /// </summary> public readonly struct MemoryOperand { /// <summary> /// Segment override or <see cref="Register.None"/> /// </summary> public readonly Register SegmentPrefix; /// <summary> /// Base register or <see cref="Register.None"/> /// </summary> public readonly Register Base; /// <summary> /// Index register or <see cref="Register.None"/> /// </summary> public readonly Register Index; /// <summary> /// Index register scale (1, 2, 4, or 8) /// </summary> public readonly int Scale; /// <summary> /// Memory displacement /// </summary> public readonly long Displacement; /// <summary> /// 0 (no displ), 1 (16/32/64-bit, but use 2/4/8 if it doesn't fit in a <see cref="sbyte"/>), 2 (16-bit), 4 (32-bit) or 8 (64-bit) /// </summary> public readonly int DisplSize; /// <summary> /// <see langword="true"/> if it's broadcasted memory (EVEX instructions) /// </summary> public readonly bool IsBroadcast; /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> /// <param name="index">Index register or <see cref="Register.None"/></param> /// <param name="scale">Index register scale (1, 2, 4, or 8)</param> /// <param name="displacement">Memory displacement</param> /// <param name="displSize">0 (no displ), 1 (16/32/64-bit, but use 2/4/8 if it doesn't fit in a <see cref="sbyte"/>), 2 (16-bit), 4 (32-bit) or 8 (64-bit)</param> /// <param name="isBroadcast"><see langword="true"/> if it's broadcasted memory (EVEX instructions)</param> /// <param name="segmentPrefix">Segment override or <see cref="Register.None"/></param> public MemoryOperand(Register @base, Register index, int scale, long displacement, int displSize, bool isBroadcast, Register segmentPrefix) { SegmentPrefix = segmentPrefix; Base = @base; Index = index; Scale = scale; Displacement = displacement; DisplSize = displSize; IsBroadcast = isBroadcast; } /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> /// <param name="index">Index register or <see cref="Register.None"/></param> /// <param name="scale">Index register scale (1, 2, 4, or 8)</param> /// <param name="isBroadcast"><see langword="true"/> if it's broadcasted memory (EVEX instructions)</param> /// <param name="segmentPrefix">Segment override or <see cref="Register.None"/></param> public MemoryOperand(Register @base, Register index, int scale, bool isBroadcast, Register segmentPrefix) { SegmentPrefix = segmentPrefix; Base = @base; Index = index; Scale = scale; Displacement = 0; DisplSize = 0; IsBroadcast = isBroadcast; } /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> /// <param name="displacement">Memory displacement</param> /// <param name="displSize">0 (no displ), 1 (16/32/64-bit, but use 2/4/8 if it doesn't fit in a <see cref="sbyte"/>), 2 (16-bit), 4 (32-bit) or 8 (64-bit)</param> /// <param name="isBroadcast"><see langword="true"/> if it's broadcasted memory (EVEX instructions)</param> /// <param name="segmentPrefix">Segment override or <see cref="Register.None"/></param> public MemoryOperand(Register @base, long displacement, int displSize, bool isBroadcast, Register segmentPrefix) { SegmentPrefix = segmentPrefix; Base = @base; Index = Register.None; Scale = 1; Displacement = displacement; DisplSize = displSize; IsBroadcast = isBroadcast; } /// <summary> /// Constructor /// </summary> /// <param name="index">Index register or <see cref="Register.None"/></param> /// <param name="scale">Index register scale (1, 2, 4, or 8)</param> /// <param name="displacement">Memory displacement</param> /// <param name="displSize">0 (no displ), 1 (16/32/64-bit, but use 2/4/8 if it doesn't fit in a <see cref="sbyte"/>), 2 (16-bit), 4 (32-bit) or 8 (64-bit)</param> /// <param name="isBroadcast"><see langword="true"/> if it's broadcasted memory (EVEX instructions)</param> /// <param name="segmentPrefix">Segment override or <see cref="Register.None"/></param> public MemoryOperand(Register index, int scale, long displacement, int displSize, bool isBroadcast, Register segmentPrefix) { SegmentPrefix = segmentPrefix; Base = Register.None; Index = index; Scale = scale; Displacement = displacement; DisplSize = displSize; IsBroadcast = isBroadcast; } /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> /// <param name="displacement">Memory displacement</param> /// <param name="isBroadcast"><see langword="true"/> if it's broadcasted memory (EVEX instructions)</param> /// <param name="segmentPrefix">Segment override or <see cref="Register.None"/></param> public MemoryOperand(Register @base, long displacement, bool isBroadcast, Register segmentPrefix) { SegmentPrefix = segmentPrefix; Base = @base; Index = Register.None; Scale = 1; Displacement = displacement; DisplSize = 1; IsBroadcast = isBroadcast; } /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> /// <param name="index">Index register or <see cref="Register.None"/></param> /// <param name="scale">Index register scale (1, 2, 4, or 8)</param> /// <param name="displacement">Memory displacement</param> /// <param name="displSize">0 (no displ), 1 (16/32/64-bit, but use 2/4/8 if it doesn't fit in a <see cref="sbyte"/>), 2 (16-bit), 4 (32-bit) or 8 (64-bit)</param> public MemoryOperand(Register @base, Register index, int scale, long displacement, int displSize) { SegmentPrefix = Register.None; Base = @base; Index = index; Scale = scale; Displacement = displacement; DisplSize = displSize; IsBroadcast = false; } /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> /// <param name="index">Index register or <see cref="Register.None"/></param> /// <param name="scale">Index register scale (1, 2, 4, or 8)</param> public MemoryOperand(Register @base, Register index, int scale) { SegmentPrefix = Register.None; Base = @base; Index = index; Scale = scale; Displacement = 0; DisplSize = 0; IsBroadcast = false; } /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> /// <param name="index">Index register or <see cref="Register.None"/></param> public MemoryOperand(Register @base, Register index) { SegmentPrefix = Register.None; Base = @base; Index = index; Scale = 1; Displacement = 0; DisplSize = 0; IsBroadcast = false; } /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> /// <param name="displacement">Memory displacement</param> /// <param name="displSize">0 (no displ), 1 (16/32/64-bit, but use 2/4/8 if it doesn't fit in a <see cref="sbyte"/>), 2 (16-bit), 4 (32-bit) or 8 (64-bit)</param> public MemoryOperand(Register @base, long displacement, int displSize) { SegmentPrefix = Register.None; Base = @base; Index = Register.None; Scale = 1; Displacement = displacement; DisplSize = displSize; IsBroadcast = false; } /// <summary> /// Constructor /// </summary> /// <param name="index">Index register or <see cref="Register.None"/></param> /// <param name="scale">Index register scale (1, 2, 4, or 8)</param> /// <param name="displacement">Memory displacement</param> /// <param name="displSize">0 (no displ), 1 (16/32/64-bit, but use 2/4/8 if it doesn't fit in a <see cref="sbyte"/>), 2 (16-bit), 4 (32-bit) or 8 (64-bit)</param> public MemoryOperand(Register index, int scale, long displacement, int displSize) { SegmentPrefix = Register.None; Base = Register.None; Index = index; Scale = scale; Displacement = displacement; DisplSize = displSize; IsBroadcast = false; } /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> /// <param name="displacement">Memory displacement</param> public MemoryOperand(Register @base, long displacement) { SegmentPrefix = Register.None; Base = @base; Index = Register.None; Scale = 1; Displacement = displacement; DisplSize = 1; IsBroadcast = false; } /// <summary> /// Constructor /// </summary> /// <param name="base">Base register or <see cref="Register.None"/></param> public MemoryOperand(Register @base) { SegmentPrefix = Register.None; Base = @base; Index = Register.None; Scale = 1; Displacement = 0; DisplSize = 0; IsBroadcast = false; } } } #endif
// 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.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ResourceGroupsOperations operations. /// </summary> internal partial class ResourceGroupsOperations : Microsoft.Rest.IServiceOperations<ResourceManagementClient>, IResourceGroupsOperations { /// <summary> /// Initializes a new instance of the ResourceGroupsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ResourceGroupsOperations(ResourceManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ResourceManagementClient /// </summary> public ResourceManagementClient Client { get; private set; } /// <summary> /// Checks whether a resource group exists. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to check. The name is case insensitive. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool>> CheckExistenceWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CheckExistence", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("HEAD"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 404) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<bool>(); _result.Request = _httpRequest; _result.Response = _httpResponse; _result.Body = (_statusCode == System.Net.HttpStatusCode.NoContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to create or update. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update a resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, ResourceGroup parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ResourceGroup>(); _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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceGroup>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceGroup>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a resource group. /// </summary> /// <remarks> /// When you delete a resource group, all of its resources are also deleted. /// Deleting a resource group deletes all of its template deployments and /// currently stored operations. /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group to delete. The name is case insensitive. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Send request Microsoft.Rest.Azure.AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync( resourceGroupName, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// Gets a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceGroup>> GetWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ResourceGroup>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceGroup>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates a resource group. /// </summary> /// <remarks> /// Resource groups can be updated through a simple PATCH operation to a group /// address. The format of the request is the same as that for creating a /// resource group. If a field is unspecified, the current value is retained. /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group to update. The name is case insensitive. /// </param> /// <param name='parameters'> /// Parameters supplied to update a resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceGroup>> UpdateWithHttpMessagesAsync(string resourceGroupName, ResourceGroupPatchable parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ResourceGroup>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceGroup>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Captures the specified resource group as a template. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group to export as a template. /// </param> /// <param name='parameters'> /// Parameters for exporting the template. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceGroupExportResult>> ExportTemplateWithHttpMessagesAsync(string resourceGroupName, ExportTemplateRequest parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ExportTemplate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/exportTemplate").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ResourceGroupExportResult>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceGroupExportResult>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the resource groups for a subscription. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<ResourceGroup>>> ListWithHttpMessagesAsync(Microsoft.Rest.Azure.OData.ODataQuery<ResourceGroupFilter> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<ResourceGroupFilter>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<ResourceGroup>>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceGroup>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a resource group. /// </summary> /// <remarks> /// When you delete a resource group, all of its resources are also deleted. /// Deleting a resource group deletes all of its template deployments and /// currently stored operations. /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group to delete. The name is case insensitive. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.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) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the resource groups for a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<ResourceGroup>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<ResourceGroup>>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceGroup>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using Xunit; namespace Moq.Tests { public class TimesFixture { [Theory] [InlineData(0, false)] [InlineData(1, true)] [InlineData(int.MaxValue, true)] public void default_ranges_between_one_and_MaxValue(int count, bool verifies) { Assert.Equal(verifies, default(Times).Verify(count)); } [Fact] public void AtLeastOnceRangesBetweenOneAndMaxValue() { var target = Times.AtLeastOnce(); Assert.False(target.Verify(-1)); Assert.False(target.Verify(0)); Assert.True(target.Verify(1)); Assert.True(target.Verify(5)); Assert.True(target.Verify(int.MaxValue)); } [Fact] public void AtLeastThrowsIfTimesLessThanOne() { Assert.Throws<ArgumentOutOfRangeException>(() => Times.AtLeast(0)); Assert.Throws<ArgumentOutOfRangeException>(() => Times.AtLeast(-1)); } [Fact] public void AtLeastRangesBetweenTimesAndMaxValue() { var target = Times.AtLeast(10); Assert.False(target.Verify(-1)); Assert.False(target.Verify(0)); Assert.False(target.Verify(9)); Assert.True(target.Verify(10)); Assert.True(target.Verify(int.MaxValue)); } [Fact] public void AtMostOnceRangesBetweenZeroAndOne() { var target = Times.AtMostOnce(); Assert.False(target.Verify(-1)); Assert.True(target.Verify(0)); Assert.True(target.Verify(1)); Assert.False(target.Verify(5)); Assert.False(target.Verify(int.MaxValue)); } [Fact] public void AtMostThrowsIfTimesLessThanZero() { Assert.Throws<ArgumentOutOfRangeException>(() => Times.AtMost(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => Times.AtMost(-2)); } [Fact] public void AtMostRangesBetweenZeroAndTimes() { var target = Times.AtMost(10); Assert.False(target.Verify(-1)); Assert.True(target.Verify(0)); Assert.True(target.Verify(6)); Assert.True(target.Verify(10)); Assert.False(target.Verify(11)); Assert.False(target.Verify(int.MaxValue)); } [Fact] public void BetweenInclusiveThrowsIfFromLessThanZero() { Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(-1, 10, Range.Inclusive)); Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(-2, 3, Range.Inclusive)); } [Fact] public void BetweenInclusiveThrowsIfFromGreaterThanTo() { Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(3, 2, Range.Inclusive)); Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(-3, -2, Range.Inclusive)); Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(0, -2, Range.Inclusive)); } [Fact] public void BetweenInclusiveRangesBetweenFromAndTo() { var target = Times.Between(10, 20, Range.Inclusive); Assert.False(target.Verify(0)); Assert.False(target.Verify(9)); Assert.True(target.Verify(10)); Assert.True(target.Verify(14)); Assert.True(target.Verify(20)); Assert.False(target.Verify(21)); Assert.False(target.Verify(int.MaxValue)); } [Fact] public void BetweenExclusiveThrowsIfFromLessThanZero() { Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(-1, 10, Range.Exclusive)); Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(-2, 3, Range.Exclusive)); } [Fact] public void BetweenExclusiveThrowsIfFromPlusOneGreaterThanToMinusOne() { Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(2, 3, Range.Exclusive)); Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(3, 2, Range.Exclusive)); Assert.Throws<ArgumentOutOfRangeException>(() => Times.Between(0, -2, Range.Exclusive)); } [Fact] public void BetweenExclusiveRangesBetweenFromPlusOneAndToMinusOne() { var target = Times.Between(10, 20, Range.Exclusive); Assert.False(target.Verify(0)); Assert.False(target.Verify(10)); Assert.True(target.Verify(11)); Assert.True(target.Verify(14)); Assert.True(target.Verify(19)); Assert.False(target.Verify(20)); Assert.False(target.Verify(int.MaxValue)); } [Fact] public void ExactlyThrowsIfTimesLessThanZero() { Assert.Throws<ArgumentOutOfRangeException>(() => Times.Exactly(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => Times.Exactly(-2)); } [Fact] public void ExactlyCheckExactTimes() { var target = Times.Exactly(10); Assert.False(target.Verify(-1)); Assert.False(target.Verify(0)); Assert.False(target.Verify(9)); Assert.True(target.Verify(10)); Assert.False(target.Verify(11)); Assert.False(target.Verify(int.MaxValue)); } [Fact] public void NeverChecksZeroTimes() { var target = Times.Never(); Assert.False(target.Verify(-1)); Assert.True(target.Verify(0)); Assert.False(target.Verify(1)); Assert.False(target.Verify(int.MaxValue)); } [Fact] public void OnceChecksOneTime() { var target = Times.Once(); Assert.False(target.Verify(-1)); Assert.False(target.Verify(0)); Assert.True(target.Verify(1)); Assert.False(target.Verify(int.MaxValue)); } public class Deconstruction { [Fact] public void AtLeast_n_deconstructs_to_n_MaxValue() { const int n = 42; var (from, to) = Times.AtLeast(n); Assert.Equal(n, from); Assert.Equal(int.MaxValue, to); } [Fact] public void AtLeastOnce_deconstructs_to_1_MaxValue() { var (from, to) = Times.AtLeastOnce(); Assert.Equal(1, from); Assert.Equal(int.MaxValue, to); } [Fact] public void AtMost_n_deconstructs_to_0_n() { const int n = 42; var (from, to) = Times.AtMost(n); Assert.Equal(0, from); Assert.Equal(n, to); } [Fact] public void AtMostOnce_deconstructs_to_0_1() { var (from, to) = Times.AtMostOnce(); Assert.Equal(0, from); Assert.Equal(1, to); } [Fact] public void BetweenExclusive_n_m_deconstructs_to__n_plus_1__m_minus_1() { const int n = 13; const int m = 42; var (from, to) = Times.Between(n, m, Range.Exclusive); Assert.Equal(n + 1, from); Assert.Equal(m - 1, to); } [Fact] public void BetweenInclusive_n_m_deconstructs_to_n_m() { const int n = 13; const int m = 42; var (from, to) = Times.Between(n, m, Range.Inclusive); Assert.Equal(n, from); Assert.Equal(m, to); } [Fact] public void Exactly_n_deconstructs_to_n_n() { const int n = 42; var (from, to) = Times.Exactly(n); Assert.Equal(n, from); Assert.Equal(n, to); } [Fact] public void Once_deconstructs_to_1_1() { var (from, to) = Times.Once(); Assert.Equal(1, from); Assert.Equal(1, to); } [Fact] public void Never_deconstructs_to_0_0() { var (from, to) = Times.Never(); Assert.Equal(0, from); Assert.Equal(0, to); } } public class Equality { #pragma warning disable xUnit2000 // Constants and literals should be the expected argument [Fact] public void default_Equals_AtLeastOnce() { Assert.Equal(Times.AtLeastOnce(), default(Times)); } #pragma warning restore xUnit2000 [Fact] public void default_GetHashCode_equals_AtLeastOnce_GetHashCode() { Assert.Equal(Times.AtLeastOnce().GetHashCode(), default(Times).GetHashCode()); } [Fact] public void AtMostOnce_equals_Between_0_1_inclusive() { Assert.Equal(Times.AtMostOnce(), Times.Between(0, 1, Range.Inclusive)); } [Fact] public void Between_1_2_inclusive_equals_Between_0_3_exclusive() { Assert.Equal(Times.Between(2, 3, Range.Inclusive), Times.Between(1, 4, Range.Exclusive)); } [Fact] public void Once_equals_Once() { Assert.Equal(Times.Once(), Times.Once()); } [Fact] public void Once_equals_Exactly_1() { Assert.Equal(Times.Once(), Times.Exactly(1)); } [Fact] public void Between_x_y_inclusive_does_not_equal_Between_x_y_exclusive() { const int x = 1; const int y = 10; Assert.NotEqual(Times.Between(x, y, Range.Inclusive), Times.Between(x, y, Range.Exclusive)); } } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.Protocol.cs // // 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. #pragma warning disable 1717 namespace Org.Apache.Http.Client.Protocol { /// <java-name> /// org/apache/http/client/protocol/ClientContextConfigurer /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ClientContextConfigurer", AccessFlags = 33)] public partial class ClientContextConfigurer : global::Org.Apache.Http.Client.Protocol.IClientContext /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public ClientContextConfigurer(global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } /// <java-name> /// setCookieSpecRegistry /// </java-name> [Dot42.DexImport("setCookieSpecRegistry", "(Lorg/apache/http/cookie/CookieSpecRegistry;)V", AccessFlags = 1)] public virtual void SetCookieSpecRegistry(global::Org.Apache.Http.Cookie.CookieSpecRegistry registry) /* MethodBuilder.Create */ { } /// <java-name> /// setAuthSchemeRegistry /// </java-name> [Dot42.DexImport("setAuthSchemeRegistry", "(Lorg/apache/http/auth/AuthSchemeRegistry;)V", AccessFlags = 1)] public virtual void SetAuthSchemeRegistry(global::Org.Apache.Http.Auth.AuthSchemeRegistry registry) /* MethodBuilder.Create */ { } /// <java-name> /// setCookieStore /// </java-name> [Dot42.DexImport("setCookieStore", "(Lorg/apache/http/client/CookieStore;)V", AccessFlags = 1)] public virtual void SetCookieStore(global::Org.Apache.Http.Client.ICookieStore store) /* MethodBuilder.Create */ { } /// <java-name> /// setCredentialsProvider /// </java-name> [Dot42.DexImport("setCredentialsProvider", "(Lorg/apache/http/client/CredentialsProvider;)V", AccessFlags = 1)] public virtual void SetCredentialsProvider(global::Org.Apache.Http.Client.ICredentialsProvider provider) /* MethodBuilder.Create */ { } /// <java-name> /// setAuthSchemePref /// </java-name> [Dot42.DexImport("setAuthSchemePref", "(Ljava/util/List;)V", AccessFlags = 1, Signature = "(Ljava/util/List<Ljava/lang/String;>;)V")] public virtual void SetAuthSchemePref(global::Java.Util.IList<string> list) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ClientContextConfigurer() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Response interceptor that populates the current CookieStore with data contained in response cookies received in the given the HTTP response.</para><para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/ResponseProcessCookies /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ResponseProcessCookies", AccessFlags = 33)] public partial class ResponseProcessCookies : global::Org.Apache.Http.IHttpResponseInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ResponseProcessCookies() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestTargetAuthentication /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestTargetAuthentication", AccessFlags = 33)] public partial class RequestTargetAuthentication : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestTargetAuthentication() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestProxyAuthentication /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestProxyAuthentication", AccessFlags = 33)] public partial class RequestProxyAuthentication : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestProxyAuthentication() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Request interceptor that adds default request headers.</para><para><para></para><para></para><title>Revision:</title><para>653041 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestDefaultHeaders /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestDefaultHeaders", AccessFlags = 33)] public partial class RequestDefaultHeaders : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestDefaultHeaders() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Context attribute names for client. </para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/ClientContext /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ClientContext", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IClientContextConstants /* scope: __dot42__ */ { /// <java-name> /// COOKIESPEC_REGISTRY /// </java-name> [Dot42.DexImport("COOKIESPEC_REGISTRY", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIESPEC_REGISTRY = "http.cookiespec-registry"; /// <java-name> /// AUTHSCHEME_REGISTRY /// </java-name> [Dot42.DexImport("AUTHSCHEME_REGISTRY", "Ljava/lang/String;", AccessFlags = 25)] public const string AUTHSCHEME_REGISTRY = "http.authscheme-registry"; /// <java-name> /// COOKIE_STORE /// </java-name> [Dot42.DexImport("COOKIE_STORE", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_STORE = "http.cookie-store"; /// <java-name> /// COOKIE_SPEC /// </java-name> [Dot42.DexImport("COOKIE_SPEC", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_SPEC = "http.cookie-spec"; /// <java-name> /// COOKIE_ORIGIN /// </java-name> [Dot42.DexImport("COOKIE_ORIGIN", "Ljava/lang/String;", AccessFlags = 25)] public const string COOKIE_ORIGIN = "http.cookie-origin"; /// <java-name> /// CREDS_PROVIDER /// </java-name> [Dot42.DexImport("CREDS_PROVIDER", "Ljava/lang/String;", AccessFlags = 25)] public const string CREDS_PROVIDER = "http.auth.credentials-provider"; /// <java-name> /// TARGET_AUTH_STATE /// </java-name> [Dot42.DexImport("TARGET_AUTH_STATE", "Ljava/lang/String;", AccessFlags = 25)] public const string TARGET_AUTH_STATE = "http.auth.target-scope"; /// <java-name> /// PROXY_AUTH_STATE /// </java-name> [Dot42.DexImport("PROXY_AUTH_STATE", "Ljava/lang/String;", AccessFlags = 25)] public const string PROXY_AUTH_STATE = "http.auth.proxy-scope"; /// <java-name> /// AUTH_SCHEME_PREF /// </java-name> [Dot42.DexImport("AUTH_SCHEME_PREF", "Ljava/lang/String;", AccessFlags = 25)] public const string AUTH_SCHEME_PREF = "http.auth.scheme-pref"; /// <java-name> /// USER_TOKEN /// </java-name> [Dot42.DexImport("USER_TOKEN", "Ljava/lang/String;", AccessFlags = 25)] public const string USER_TOKEN = "http.user-token"; } /// <summary> /// <para>Context attribute names for client. </para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/ClientContext /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/ClientContext", AccessFlags = 1537)] public partial interface IClientContext /* scope: __dot42__ */ { } /// <summary> /// <para>Request interceptor that matches cookies available in the current CookieStore to the request being executed and generates corresponding cookierequest headers.</para><para><para></para><para></para><title>Revision:</title><para>673450 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/protocol/RequestAddCookies /// </java-name> [Dot42.DexImport("org/apache/http/client/protocol/RequestAddCookies", AccessFlags = 33)] public partial class RequestAddCookies : global::Org.Apache.Http.IHttpRequestInterceptor /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RequestAddCookies() /* MethodBuilder.Create */ { } /// <java-name> /// process /// </java-name> [Dot42.DexImport("process", "(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpContext;)V", AccessFlags = 1)] public virtual void Process(global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ { } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using ServiceStack.Text.Common; using ServiceStack.Text.Json; using ServiceStack.Text.Jsv; #if WINDOWS_PHONE && !WP8 using ServiceStack.Text.WP; #endif namespace ServiceStack.Text { public static class JsConfig { static JsConfig() { //In-built default serialization, to Deserialize Color struct do: //JsConfig<System.Drawing.Color>.SerializeFn = c => c.ToString().Replace("Color ", "").Replace("[", "").Replace("]", ""); //JsConfig<System.Drawing.Color>.DeSerializeFn = System.Drawing.Color.FromName; Reset(); } public static JsConfigScope BeginScope() { return new JsConfigScope(); } public static JsConfigScope With( bool? convertObjectTypesIntoStringDictionary = null, bool? tryToParsePrimitiveTypeValues = null, bool? tryToParseNumericType = null, bool? includeNullValues = null, bool? excludeTypeInfo = null, bool? includeTypeInfo = null, bool? emitCamelCaseNames = null, bool? emitLowercaseUnderscoreNames = null, JsonDateHandler? dateHandler = null, JsonTimeSpanHandler? timeSpanHandler = null, bool? preferInterfaces = null, bool? throwOnDeserializationError = null, string typeAttr = null, Func<Type, string> typeWriter = null, Func<string, Type> typeFinder = null, bool? treatEnumAsInteger = null, bool? alwaysUseUtc = null, bool? assumeUtc = null, bool? appendUtcOffset = null, bool? escapeUnicode = null, bool? includePublicFields = null, int? maxDepth = null, EmptyCtorFactoryDelegate modelFactory = null, string[] excludePropertyReferences = null) { return new JsConfigScope { ConvertObjectTypesIntoStringDictionary = convertObjectTypesIntoStringDictionary ?? sConvertObjectTypesIntoStringDictionary, TryToParsePrimitiveTypeValues = tryToParsePrimitiveTypeValues ?? sTryToParsePrimitiveTypeValues, TryToParseNumericType = tryToParseNumericType ?? sTryToParseNumericType, IncludeNullValues = includeNullValues ?? sIncludeNullValues, ExcludeTypeInfo = excludeTypeInfo ?? sExcludeTypeInfo, IncludeTypeInfo = includeTypeInfo ?? sIncludeTypeInfo, EmitCamelCaseNames = emitCamelCaseNames ?? sEmitCamelCaseNames, EmitLowercaseUnderscoreNames = emitLowercaseUnderscoreNames ?? sEmitLowercaseUnderscoreNames, DateHandler = dateHandler ?? sDateHandler, TimeSpanHandler = timeSpanHandler ?? sTimeSpanHandler, PreferInterfaces = preferInterfaces ?? sPreferInterfaces, ThrowOnDeserializationError = throwOnDeserializationError ?? sThrowOnDeserializationError, TypeAttr = typeAttr ?? sTypeAttr, TypeWriter = typeWriter ?? sTypeWriter, TypeFinder = typeFinder ?? sTypeFinder, TreatEnumAsInteger = treatEnumAsInteger ?? sTreatEnumAsInteger, AlwaysUseUtc = alwaysUseUtc ?? sAlwaysUseUtc, AssumeUtc = assumeUtc ?? sAssumeUtc, AppendUtcOffset = appendUtcOffset ?? sAppendUtcOffset, EscapeUnicode = escapeUnicode ?? sEscapeUnicode, IncludePublicFields = includePublicFields ?? sIncludePublicFields, MaxDepth = maxDepth ?? sMaxDepth, ModelFactory = modelFactory ?? ModelFactory, ExcludePropertyReferences = excludePropertyReferences ?? sExcludePropertyReferences }; } private static bool? sConvertObjectTypesIntoStringDictionary; public static bool ConvertObjectTypesIntoStringDictionary { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.ConvertObjectTypesIntoStringDictionary: null) ?? sConvertObjectTypesIntoStringDictionary ?? false; } set { if (!sConvertObjectTypesIntoStringDictionary.HasValue) sConvertObjectTypesIntoStringDictionary = value; } } private static bool? sTryToParsePrimitiveTypeValues; public static bool TryToParsePrimitiveTypeValues { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.TryToParsePrimitiveTypeValues: null) ?? sTryToParsePrimitiveTypeValues ?? false; } set { if (!sTryToParsePrimitiveTypeValues.HasValue) sTryToParsePrimitiveTypeValues = value; } } private static bool? sTryToParseNumericType; public static bool TryToParseNumericType { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.TryToParseNumericType : null) ?? sTryToParseNumericType ?? false; } set { if (!sTryToParseNumericType.HasValue) sTryToParseNumericType = value; } } private static bool? sIncludeNullValues; public static bool IncludeNullValues { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.IncludeNullValues: null) ?? sIncludeNullValues ?? false; } set { if (!sIncludeNullValues.HasValue) sIncludeNullValues = value; } } private static bool? sTreatEnumAsInteger; public static bool TreatEnumAsInteger { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.TreatEnumAsInteger: null) ?? sTreatEnumAsInteger ?? false; } set { if (!sTreatEnumAsInteger.HasValue) sTreatEnumAsInteger = value; } } private static bool? sExcludeTypeInfo; public static bool ExcludeTypeInfo { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.ExcludeTypeInfo: null) ?? sExcludeTypeInfo ?? false; } set { if (!sExcludeTypeInfo.HasValue) sExcludeTypeInfo = value; } } private static bool? sIncludeTypeInfo; public static bool IncludeTypeInfo { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.IncludeTypeInfo: null) ?? sIncludeTypeInfo ?? false; } set { if (!sIncludeTypeInfo.HasValue) sIncludeTypeInfo = value; } } private static string sTypeAttr; public static string TypeAttr { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.TypeAttr: null) ?? sTypeAttr ?? JsWriter.TypeAttr; } set { if (sTypeAttr == null) sTypeAttr = value; JsonTypeAttrInObject = JsonTypeSerializer.GetTypeAttrInObject(value); JsvTypeAttrInObject = JsvTypeSerializer.GetTypeAttrInObject(value); } } private static string sJsonTypeAttrInObject; private static readonly string defaultJsonTypeAttrInObject = JsonTypeSerializer.GetTypeAttrInObject(TypeAttr); internal static string JsonTypeAttrInObject { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.JsonTypeAttrInObject: null) ?? sJsonTypeAttrInObject ?? defaultJsonTypeAttrInObject; } set { if (sJsonTypeAttrInObject == null) sJsonTypeAttrInObject = value; } } private static string sJsvTypeAttrInObject; private static readonly string defaultJsvTypeAttrInObject = JsvTypeSerializer.GetTypeAttrInObject(TypeAttr); internal static string JsvTypeAttrInObject { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.JsvTypeAttrInObject: null) ?? sJsvTypeAttrInObject ?? defaultJsvTypeAttrInObject; } set { if (sJsvTypeAttrInObject == null) sJsvTypeAttrInObject = value; } } private static Func<Type, string> sTypeWriter; public static Func<Type, string> TypeWriter { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.TypeWriter: null) ?? sTypeWriter ?? AssemblyUtils.WriteType; } set { if (sTypeWriter == null) sTypeWriter = value; } } private static Func<string, Type> sTypeFinder; public static Func<string, Type> TypeFinder { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.TypeFinder: null) ?? sTypeFinder ?? AssemblyUtils.FindType; } set { if (sTypeFinder == null) sTypeFinder = value; } } private static JsonDateHandler? sDateHandler; public static JsonDateHandler DateHandler { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.DateHandler: null) ?? sDateHandler ?? JsonDateHandler.TimestampOffset; } set { if (!sDateHandler.HasValue) sDateHandler = value; } } /// <summary> /// Sets which format to use when serializing TimeSpans /// </summary> private static JsonTimeSpanHandler? sTimeSpanHandler; public static JsonTimeSpanHandler TimeSpanHandler { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.TimeSpanHandler : null) ?? sTimeSpanHandler ?? JsonTimeSpanHandler.DurationFormat; } set { if (!sTimeSpanHandler.HasValue) sTimeSpanHandler = value; } } /// <summary> /// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured /// to take advantage of <see cref="CLSCompliantAttribute"/> specification, /// to support user-friendly serialized formats, ie emitting camelCasing for JSON /// and parsing member names and enum values in a case-insensitive manner. /// </summary> private static bool? sEmitCamelCaseNames; public static bool EmitCamelCaseNames { // obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case get { return (JsConfigScope.Current != null ? JsConfigScope.Current.EmitCamelCaseNames: null) ?? sEmitCamelCaseNames ?? false; } set { if (!sEmitCamelCaseNames.HasValue) sEmitCamelCaseNames = value; } } /// <summary> /// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured /// to support web-friendly serialized formats, ie emitting lowercase_underscore_casing for JSON /// </summary> private static bool? sEmitLowercaseUnderscoreNames; public static bool EmitLowercaseUnderscoreNames { // obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case get { return (JsConfigScope.Current != null ? JsConfigScope.Current.EmitLowercaseUnderscoreNames: null) ?? sEmitLowercaseUnderscoreNames ?? false; } set { if (!sEmitLowercaseUnderscoreNames.HasValue) sEmitLowercaseUnderscoreNames = value; } } /// <summary> /// Define how property names are mapped during deserialization /// </summary> private static JsonPropertyConvention propertyConvention; public static JsonPropertyConvention PropertyConvention { get { return propertyConvention; } set { propertyConvention = value; switch (propertyConvention) { case JsonPropertyConvention.ExactMatch: DeserializeTypeRefJson.PropertyNameResolver = DeserializeTypeRefJson.DefaultPropertyNameResolver; break; case JsonPropertyConvention.Lenient: DeserializeTypeRefJson.PropertyNameResolver = DeserializeTypeRefJson.LenientPropertyNameResolver; break; } } } /// <summary> /// Gets or sets a value indicating if the framework should throw serialization exceptions /// or continue regardless of deserialization errors. If <see langword="true"/> the framework /// will throw; otherwise, it will parse as many fields as possible. The default is <see langword="false"/>. /// </summary> private static bool? sThrowOnDeserializationError; public static bool ThrowOnDeserializationError { // obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case get { return (JsConfigScope.Current != null ? JsConfigScope.Current.ThrowOnDeserializationError: null) ?? sThrowOnDeserializationError ?? false; } set { if (!sThrowOnDeserializationError.HasValue) sThrowOnDeserializationError = value; } } /// <summary> /// Gets or sets a value indicating if the framework should always convert <see cref="DateTime"/> to UTC format instead of local time. /// </summary> private static bool? sAlwaysUseUtc; public static bool AlwaysUseUtc { // obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case get { return (JsConfigScope.Current != null ? JsConfigScope.Current.AlwaysUseUtc: null) ?? sAlwaysUseUtc ?? false; } set { if (!sAlwaysUseUtc.HasValue) sAlwaysUseUtc = value; } } /// <summary> /// Gets or sets a value indicating if the framework should always assume <see cref="DateTime"/> is in UTC format if Kind is Unspecified. /// </summary> private static bool? sAssumeUtc; public static bool AssumeUtc { // obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case get { return (JsConfigScope.Current != null ? JsConfigScope.Current.AssumeUtc : null) ?? sAssumeUtc ?? false; } set { if (!sAssumeUtc.HasValue) sAssumeUtc = value; } } /// <summary> /// Gets or sets whether we should append the Utc offset when we serialize Utc dates. Defaults to no. /// Only supported for when the JsConfig.DateHandler == JsonDateHandler.TimestampOffset /// </summary> private static bool? sAppendUtcOffset; public static bool? AppendUtcOffset { // obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case get { return (JsConfigScope.Current != null ? JsConfigScope.Current.AppendUtcOffset : null) ?? sAppendUtcOffset ?? null; } set { if (sAppendUtcOffset == null) sAppendUtcOffset = value; } } /// <summary> /// Gets or sets a value indicating if unicode symbols should be serialized as "\uXXXX". /// </summary> private static bool? sEscapeUnicode; public static bool EscapeUnicode { // obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case get { return (JsConfigScope.Current != null ? JsConfigScope.Current.EscapeUnicode : null) ?? sEscapeUnicode ?? false; } set { if (!sEscapeUnicode.HasValue) sEscapeUnicode = value; } } internal static HashSet<Type> HasSerializeFn = new HashSet<Type>(); public static HashSet<Type> TreatValueAsRefTypes = new HashSet<Type>(); private static bool? sPreferInterfaces; /// <summary> /// If set to true, Interface types will be prefered over concrete types when serializing. /// </summary> public static bool PreferInterfaces { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.PreferInterfaces: null) ?? sPreferInterfaces ?? false; } set { if (!sPreferInterfaces.HasValue) sPreferInterfaces = value; } } internal static bool TreatAsRefType(Type valueType) { return TreatValueAsRefTypes.Contains(valueType.IsGeneric() ? valueType.GenericTypeDefinition() : valueType); } /// <summary> /// If set to true, Interface types will be prefered over concrete types when serializing. /// </summary> private static bool? sIncludePublicFields; public static bool IncludePublicFields { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.IncludePublicFields : null) ?? sIncludePublicFields ?? false; } set { if (!sIncludePublicFields.HasValue) sIncludePublicFields = value; } } /// <summary> /// Sets the maximum depth to avoid circular dependencies /// </summary> private static int? sMaxDepth; public static int MaxDepth { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.MaxDepth : null) ?? sMaxDepth ?? int.MaxValue; } set { if (!sMaxDepth.HasValue) sMaxDepth = value; } } /// <summary> /// Set this to enable your own type construction provider. /// This is helpful for integration with IoC containers where you need to call the container constructor. /// Return null if you don't know how to construct the type and the parameterless constructor will be used. /// </summary> private static EmptyCtorFactoryDelegate sModelFactory; public static EmptyCtorFactoryDelegate ModelFactory { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.ModelFactory : null) ?? sModelFactory ?? null; } set { if (sModelFactory != null) sModelFactory = value; } } private static string[] sExcludePropertyReferences; public static string[] ExcludePropertyReferences { get { return (JsConfigScope.Current != null ? JsConfigScope.Current.ExcludePropertyReferences : null) ?? sExcludePropertyReferences; } set { if (sExcludePropertyReferences != null) sExcludePropertyReferences = value; } } public static void Reset() { foreach (var rawSerializeType in HasSerializeFn.ToArray()) { Reset(rawSerializeType); } sModelFactory = ReflectionExtensions.GetConstructorMethodToCache; sTryToParsePrimitiveTypeValues = null; sTryToParseNumericType = null; sConvertObjectTypesIntoStringDictionary = null; sIncludeNullValues = null; sExcludeTypeInfo = null; sEmitCamelCaseNames = null; sEmitLowercaseUnderscoreNames = null; sDateHandler = null; sTimeSpanHandler = null; sPreferInterfaces = null; sThrowOnDeserializationError = null; sTypeAttr = null; sJsonTypeAttrInObject = null; sJsvTypeAttrInObject = null; sTypeWriter = null; sTypeFinder = null; sTreatEnumAsInteger = null; sAlwaysUseUtc = null; sAssumeUtc = null; sAppendUtcOffset = null; sEscapeUnicode = null; sIncludePublicFields = null; HasSerializeFn = new HashSet<Type>(); TreatValueAsRefTypes = new HashSet<Type> { typeof(KeyValuePair<,>) }; PropertyConvention = JsonPropertyConvention.ExactMatch; sExcludePropertyReferences = null; } public static void Reset(Type cachesForType) { typeof(JsConfig<>).MakeGenericType(new[] { cachesForType }).InvokeReset(); } internal static void InvokeReset(this Type genericType) { #if NETFX_CORE MethodInfo methodInfo = genericType.GetTypeInfo().GetType().GetMethodInfo("Reset"); methodInfo.Invoke(null, null); #else var methodInfo = genericType.GetMethod("Reset", BindingFlags.Static | BindingFlags.Public); methodInfo.Invoke(null, null); #endif } #if MONOTOUCH /// <summary> /// Provide hint to MonoTouch AOT compiler to pre-compile generic classes for all your DTOs. /// Just needs to be called once in a static constructor. /// </summary> [MonoTouch.Foundation.Preserve] public static void InitForAot() { } [MonoTouch.Foundation.Preserve] public static void RegisterForAot() { #if false RegisterTypeForAot<Poco>(); RegisterElement<Poco, string>(); RegisterElement<Poco, bool>(); RegisterElement<Poco, char>(); RegisterElement<Poco, byte>(); RegisterElement<Poco, sbyte>(); RegisterElement<Poco, short>(); RegisterElement<Poco, ushort>(); RegisterElement<Poco, int>(); RegisterElement<Poco, uint>(); RegisterElement<Poco, long>(); RegisterElement<Poco, ulong>(); RegisterElement<Poco, float>(); RegisterElement<Poco, double>(); RegisterElement<Poco, decimal>(); RegisterElement<Poco, bool?>(); RegisterElement<Poco, char?>(); RegisterElement<Poco, byte?>(); RegisterElement<Poco, sbyte?>(); RegisterElement<Poco, short?>(); RegisterElement<Poco, ushort?>(); RegisterElement<Poco, int?>(); RegisterElement<Poco, uint?>(); RegisterElement<Poco, long?>(); RegisterElement<Poco, ulong?>(); RegisterElement<Poco, float?>(); RegisterElement<Poco, double?>(); RegisterElement<Poco, decimal?>(); //RegisterElement<Poco, JsonValue>(); RegisterTypeForAot<DayOfWeek>(); // used by DateTime // register built in structs RegisterTypeForAot<Guid>(); RegisterTypeForAot<TimeSpan>(); RegisterTypeForAot<DateTime>(); RegisterTypeForAot<DateTime?>(); RegisterTypeForAot<TimeSpan?>(); RegisterTypeForAot<Guid?>(); #endif } //always false static bool falseVar; [MonoTouch.Foundation.Preserve] public static void RegisterTypeForAot<T>() { AotConfig.RegisterSerializers<T>(); // Linker trick: to include the linked stuff if (falseVar) { new JsonArrayObjects (); new JsonValue (); } } [MonoTouch.Foundation.Preserve] static void RegisterQueryStringWriter() { var i = 0; if (QueryStringWriter<Poco>.WriteFn() != null) i++; } [MonoTouch.Foundation.Preserve] internal static int RegisterElement<T, TElement>() { var i = 0; i += AotConfig.RegisterSerializers<TElement>(); AotConfig.RegisterElement<T, TElement, JsonTypeSerializer>(); AotConfig.RegisterElement<T, TElement, JsvTypeSerializer>(); return i; } ///<summary> /// Class contains Ahead-of-Time (AOT) explicit class declarations which is used only to workaround "-aot-only" exceptions occured on device only. /// </summary> [MonoTouch.Foundation.Preserve(AllMembers=true)] internal class AotConfig { internal static JsReader<JsonTypeSerializer> jsonReader; internal static JsWriter<JsonTypeSerializer> jsonWriter; internal static JsReader<JsvTypeSerializer> jsvReader; internal static JsWriter<JsvTypeSerializer> jsvWriter; internal static JsonTypeSerializer jsonSerializer; internal static JsvTypeSerializer jsvSerializer; static AotConfig() { jsonSerializer = new JsonTypeSerializer(); jsvSerializer = new JsvTypeSerializer(); jsonReader = new JsReader<JsonTypeSerializer>(); jsonWriter = new JsWriter<JsonTypeSerializer>(); jsvReader = new JsReader<JsvTypeSerializer>(); jsvWriter = new JsWriter<JsvTypeSerializer>(); } internal static int RegisterSerializers<T>() { var i = 0; i += Register<T, JsonTypeSerializer>(); if (jsonSerializer.GetParseFn<T>() != null) i++; if (jsonSerializer.GetWriteFn<T>() != null) i++; if (jsonReader.GetParseFn<T>() != null) i++; if (jsonWriter.GetWriteFn<T>() != null) i++; i += Register<T, JsvTypeSerializer>(); if (jsvSerializer.GetParseFn<T>() != null) i++; if (jsvSerializer.GetWriteFn<T>() != null) i++; if (jsvReader.GetParseFn<T>() != null) i++; if (jsvWriter.GetWriteFn<T>() != null) i++; //RegisterCsvSerializer<T>(); RegisterQueryStringWriter(); return i; } internal static void RegisterCsvSerializer<T>() { CsvSerializer<T>.WriteFn(); CsvSerializer<T>.WriteObject(null, null); CsvWriter<T>.Write(null, default(IEnumerable<T>)); CsvWriter<T>.WriteRow(null, default(T)); } public static ParseStringDelegate GetParseFn(Type type) { var parseFn = JsonTypeSerializer.Instance.GetParseFn(type); return parseFn; } internal static int Register<T, TSerializer>() where TSerializer : ITypeSerializer { var i = 0; if (JsonWriter<T>.WriteFn() != null) i++; if (JsonWriter.Instance.GetWriteFn<T>() != null) i++; if (JsonReader.Instance.GetParseFn<T>() != null) i++; if (JsonReader<T>.Parse(null) != null) i++; if (JsonReader<T>.GetParseFn() != null) i++; //if (JsWriter.GetTypeSerializer<JsonTypeSerializer>().GetWriteFn<T>() != null) i++; if (new List<T>() != null) i++; if (new T[0] != null) i++; JsConfig<T>.ExcludeTypeInfo = false; if (JsConfig<T>.OnDeserializedFn != null) i++; if (JsConfig<T>.HasDeserializeFn) i++; if (JsConfig<T>.SerializeFn != null) i++; if (JsConfig<T>.DeSerializeFn != null) i++; //JsConfig<T>.SerializeFn = arg => ""; //JsConfig<T>.DeSerializeFn = arg => default(T); if (TypeConfig<T>.Properties != null) i++; /* if (WriteType<T, TSerializer>.Write != null) i++; if (WriteType<object, TSerializer>.Write != null) i++; if (DeserializeBuiltin<T>.Parse != null) i++; if (DeserializeArray<T[], TSerializer>.Parse != null) i++; DeserializeType<TSerializer>.ExtractType(null); DeserializeArrayWithElements<T, TSerializer>.ParseGenericArray(null, null); DeserializeCollection<TSerializer>.ParseCollection<T>(null, null, null); DeserializeListWithElements<T, TSerializer>.ParseGenericList(null, null, null); SpecializedQueueElements<T>.ConvertToQueue(null); SpecializedQueueElements<T>.ConvertToStack(null); */ WriteListsOfElements<T, TSerializer>.WriteList(null, null); WriteListsOfElements<T, TSerializer>.WriteIList(null, null); WriteListsOfElements<T, TSerializer>.WriteEnumerable(null, null); WriteListsOfElements<T, TSerializer>.WriteListValueType(null, null); WriteListsOfElements<T, TSerializer>.WriteIListValueType(null, null); WriteListsOfElements<T, TSerializer>.WriteGenericArrayValueType(null, null); WriteListsOfElements<T, TSerializer>.WriteArray(null, null); TranslateListWithElements<T>.LateBoundTranslateToGenericICollection(null, null); TranslateListWithConvertibleElements<T, T>.LateBoundTranslateToGenericICollection(null, null); QueryStringWriter<T>.WriteObject(null, null); return i; } internal static void RegisterElement<T, TElement, TSerializer>() where TSerializer : ITypeSerializer { DeserializeDictionary<TSerializer>.ParseDictionary<T, TElement>(null, null, null, null); DeserializeDictionary<TSerializer>.ParseDictionary<TElement, T>(null, null, null, null); ToStringDictionaryMethods<T, TElement, TSerializer>.WriteIDictionary(null, null, null, null); ToStringDictionaryMethods<TElement, T, TSerializer>.WriteIDictionary(null, null, null, null); // Include List deserialisations from the Register<> method above. This solves issue where List<Guid> properties on responses deserialise to null. // No idea why this is happening because there is no visible exception raised. Suspect MonoTouch is swallowing an AOT exception somewhere. DeserializeArrayWithElements<TElement, TSerializer>.ParseGenericArray(null, null); DeserializeListWithElements<TElement, TSerializer>.ParseGenericList(null, null, null); // Cannot use the line below for some unknown reason - when trying to compile to run on device, mtouch bombs during native code compile. // Something about this line or its inner workings is offensive to mtouch. Luckily this was not needed for my List<Guide> issue. // DeserializeCollection<JsonTypeSerializer>.ParseCollection<TElement>(null, null, null); TranslateListWithElements<TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>)); TranslateListWithConvertibleElements<TElement, TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>)); } } #endif } #if MONOTOUCH [MonoTouch.Foundation.Preserve(AllMembers=true)] internal class Poco { public string Dummy { get; set; } } #endif public class JsConfig<T> { /// <summary> /// Always emit type info for this type. Takes precedence over ExcludeTypeInfo /// </summary> public static bool IncludeTypeInfo = false; /// <summary> /// Never emit type info for this type /// </summary> public static bool ExcludeTypeInfo = false; /// <summary> /// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured /// to take advantage of <see cref="CLSCompliantAttribute"/> specification, /// to support user-friendly serialized formats, ie emitting camelCasing for JSON /// and parsing member names and enum values in a case-insensitive manner. /// </summary> public static bool EmitCamelCaseNames = false; public static bool EmitLowercaseUnderscoreNames = false; /// <summary> /// Define custom serialization fn for BCL Structs /// </summary> private static Func<T, string> serializeFn; public static Func<T, string> SerializeFn { get { return serializeFn; } set { serializeFn = value; if (value != null) JsConfig.HasSerializeFn.Add(typeof(T)); else JsConfig.HasSerializeFn.Remove(typeof(T)); ClearFnCaches(); } } /// <summary> /// Opt-in flag to set some Value Types to be treated as a Ref Type /// </summary> public static bool TreatValueAsRefType { get { return JsConfig.TreatValueAsRefTypes.Contains(typeof(T)); } set { if (value) JsConfig.TreatValueAsRefTypes.Add(typeof(T)); else JsConfig.TreatValueAsRefTypes.Remove(typeof(T)); } } /// <summary> /// Whether there is a fn (raw or otherwise) /// </summary> public static bool HasSerializeFn { get { return serializeFn != null || rawSerializeFn != null; } } /// <summary> /// Define custom raw serialization fn /// </summary> private static Func<T, string> rawSerializeFn; public static Func<T, string> RawSerializeFn { get { return rawSerializeFn; } set { rawSerializeFn = value; if (value != null) JsConfig.HasSerializeFn.Add(typeof(T)); else JsConfig.HasSerializeFn.Remove(typeof(T)); ClearFnCaches(); } } /// <summary> /// Define custom serialization hook /// </summary> private static Func<T, T> onSerializingFn; public static Func<T, T> OnSerializingFn { get { return onSerializingFn; } set { onSerializingFn = value; } } /// <summary> /// Define custom deserialization fn for BCL Structs /// </summary> public static Func<string, T> DeSerializeFn; /// <summary> /// Define custom raw deserialization fn for objects /// </summary> public static Func<string, T> RawDeserializeFn; public static bool HasDeserializeFn { get { return DeSerializeFn != null || RawDeserializeFn != null; } } private static Func<T, T> onDeserializedFn; public static Func<T, T> OnDeserializedFn { get { return onDeserializedFn; } set { onDeserializedFn = value; } } /// <summary> /// Exclude specific properties of this type from being serialized /// </summary> public static string[] ExcludePropertyNames; public static void WriteFn<TSerializer>(TextWriter writer, object obj) { if (RawSerializeFn != null) { writer.Write(RawSerializeFn((T)obj)); } else if (SerializeFn != null) { var serializer = JsWriter.GetTypeSerializer<TSerializer>(); serializer.WriteString(writer, SerializeFn((T) obj)); } else { var writerFn = JsonWriter.Instance.GetWriteFn<T>(); writerFn(writer, obj); } } public static object ParseFn(string str) { return DeSerializeFn(str); } internal static object ParseFn(ITypeSerializer serializer, string str) { if (RawDeserializeFn != null) { return RawDeserializeFn(str); } else { return DeSerializeFn(serializer.UnescapeString(str)); } } internal static void ClearFnCaches() { typeof(JsonWriter<>).MakeGenericType(new[] { typeof(T) }).InvokeReset(); typeof(JsvWriter<>).MakeGenericType(new[] { typeof(T) }).InvokeReset(); } public static void Reset() { RawSerializeFn = null; DeSerializeFn = null; } } public enum JsonPropertyConvention { /// <summary> /// The property names on target types must match property names in the JSON source /// </summary> ExactMatch, /// <summary> /// The property names on target types may not match the property names in the JSON source /// </summary> Lenient } public enum JsonDateHandler { TimestampOffset, DCJSCompatible, ISO8601 } public enum JsonTimeSpanHandler { /// <summary> /// Uses the xsd format like PT15H10M20S /// </summary> DurationFormat, /// <summary> /// Uses the standard .net ToString method of the TimeSpan class /// </summary> StandardFormat } }
// Copyright 2022 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 gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>UserLocationView</c> resource.</summary> public sealed partial class UserLocationViewName : gax::IResourceName, sys::IEquatable<UserLocationViewName> { /// <summary>The possible contents of <see cref="UserLocationViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c>. /// </summary> CustomerCountryCriterionIsTargetingLocation = 1, } private static gax::PathTemplate s_customerCountryCriterionIsTargetingLocation = new gax::PathTemplate("customers/{customer_id}/userLocationViews/{country_criterion_id_is_targeting_location}"); /// <summary>Creates a <see cref="UserLocationViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="UserLocationViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static UserLocationViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new UserLocationViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="UserLocationViewName"/> with the pattern /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="countryCriterionId">The <c>CountryCriterion</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="isTargetingLocationId"> /// The <c>IsTargetingLocation</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns>A new instance of <see cref="UserLocationViewName"/> constructed from the provided ids.</returns> public static UserLocationViewName FromCustomerCountryCriterionIsTargetingLocation(string customerId, string countryCriterionId, string isTargetingLocationId) => new UserLocationViewName(ResourceNameType.CustomerCountryCriterionIsTargetingLocation, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), countryCriterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(countryCriterionId, nameof(countryCriterionId)), isTargetingLocationId: gax::GaxPreconditions.CheckNotNullOrEmpty(isTargetingLocationId, nameof(isTargetingLocationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="UserLocationViewName"/> with pattern /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="countryCriterionId">The <c>CountryCriterion</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="isTargetingLocationId"> /// The <c>IsTargetingLocation</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="UserLocationViewName"/> with pattern /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c>. /// </returns> public static string Format(string customerId, string countryCriterionId, string isTargetingLocationId) => FormatCustomerCountryCriterionIsTargetingLocation(customerId, countryCriterionId, isTargetingLocationId); /// <summary> /// Formats the IDs into the string representation of this <see cref="UserLocationViewName"/> with pattern /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="countryCriterionId">The <c>CountryCriterion</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="isTargetingLocationId"> /// The <c>IsTargetingLocation</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="UserLocationViewName"/> with pattern /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c>. /// </returns> public static string FormatCustomerCountryCriterionIsTargetingLocation(string customerId, string countryCriterionId, string isTargetingLocationId) => s_customerCountryCriterionIsTargetingLocation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(countryCriterionId, nameof(countryCriterionId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(isTargetingLocationId, nameof(isTargetingLocationId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="UserLocationViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="userLocationViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="UserLocationViewName"/> if successful.</returns> public static UserLocationViewName Parse(string userLocationViewName) => Parse(userLocationViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="UserLocationViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="userLocationViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="UserLocationViewName"/> if successful.</returns> public static UserLocationViewName Parse(string userLocationViewName, bool allowUnparsed) => TryParse(userLocationViewName, allowUnparsed, out UserLocationViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="UserLocationViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="userLocationViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="UserLocationViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string userLocationViewName, out UserLocationViewName result) => TryParse(userLocationViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="UserLocationViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="userLocationViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="UserLocationViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string userLocationViewName, bool allowUnparsed, out UserLocationViewName result) { gax::GaxPreconditions.CheckNotNull(userLocationViewName, nameof(userLocationViewName)); gax::TemplatedResourceName resourceName; if (s_customerCountryCriterionIsTargetingLocation.TryParseName(userLocationViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerCountryCriterionIsTargetingLocation(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(userLocationViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private UserLocationViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string countryCriterionId = null, string customerId = null, string isTargetingLocationId = null) { Type = type; UnparsedResource = unparsedResourceName; CountryCriterionId = countryCriterionId; CustomerId = customerId; IsTargetingLocationId = isTargetingLocationId; } /// <summary> /// Constructs a new instance of a <see cref="UserLocationViewName"/> class from the component parts of pattern /// <c>customers/{customer_id}/userLocationViews/{country_criterion_id}~{is_targeting_location}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="countryCriterionId">The <c>CountryCriterion</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="isTargetingLocationId"> /// The <c>IsTargetingLocation</c> ID. Must not be <c>null</c> or empty. /// </param> public UserLocationViewName(string customerId, string countryCriterionId, string isTargetingLocationId) : this(ResourceNameType.CustomerCountryCriterionIsTargetingLocation, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), countryCriterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(countryCriterionId, nameof(countryCriterionId)), isTargetingLocationId: gax::GaxPreconditions.CheckNotNullOrEmpty(isTargetingLocationId, nameof(isTargetingLocationId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>CountryCriterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string CountryCriterionId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>IsTargetingLocation</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string IsTargetingLocationId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCountryCriterionIsTargetingLocation: return s_customerCountryCriterionIsTargetingLocation.Expand(CustomerId, $"{CountryCriterionId}~{IsTargetingLocationId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as UserLocationViewName); /// <inheritdoc/> public bool Equals(UserLocationViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(UserLocationViewName a, UserLocationViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(UserLocationViewName a, UserLocationViewName b) => !(a == b); } public partial class UserLocationView { /// <summary> /// <see cref="UserLocationViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal UserLocationViewName ResourceNameAsUserLocationViewName { get => string.IsNullOrEmpty(ResourceName) ? null : UserLocationViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Detective.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using Juhta.Net.WebApi.Exceptions.ClientErrors; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using System; using System.Net; namespace Juhta.Net.WebApi.Exceptions.Tests.ClientErrors { [TestClass] public class BadRequestExceptionTests : WebApiExceptionTests { #region Test Methods [TestMethod] public void ThrowAndSerialize_BadRequestException1_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException(); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException1_ShouldReturn", null, "Exception of type 'Juhta.Net.WebApi.Exceptions.ClientErrors.BadRequestException' was thrown.", HttpStatusCode.BadRequest ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException2_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException(ErrorCode.InvalidOrderNumber); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException2_ShouldReturn", ErrorCode.InvalidOrderNumber.ToString(), "Exception of type 'Juhta.Net.WebApi.Exceptions.ClientErrors.BadRequestException' was thrown.", HttpStatusCode.BadRequest ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException3_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException("BadRequestException Specified order number is invalid."); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException3_ShouldReturn", null, "BadRequestException Specified order number is invalid.", HttpStatusCode.BadRequest ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException4_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException(ErrorCode.InvalidOrderNumber, "BadRequestException Specified order number is invalid."); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException4_ShouldReturn", ErrorCode.InvalidOrderNumber.ToString(), "BadRequestException Specified order number is invalid.", HttpStatusCode.BadRequest ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException5_ShouldReturn() { ClientError clientError; ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { clientError = new ClientError{Code = "MyApiErrorCode.XYZ", Message = "Error XYZ occurred.", Field = "FormX.FieldY", HelpUrl = "http://juhta.net"}; throw new BadRequestException(clientError); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException5_ShouldReturn", HttpStatusCode.BadRequest, "MyApiErrorCode.XYZ", "Error XYZ occurred.", "FormX.FieldY", "http://juhta.net" ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException6_ShouldReturn() { ClientError clientError1, clientError2; ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { clientError1 = new ClientError{Code = "MyApiErrorCode.XYZ1", Message = "Error XYZ1 occurred.", Field = "FormX.FieldY1", HelpUrl = "http://juhta.net/errorxyz1"}; clientError2 = new ClientError{Code = "MyApiErrorCode.XYZ2", Message = "Error XYZ2 occurred.", Field = "FormX.FieldY2", HelpUrl = "http://juhta.net/errorxyz2"}; throw new BadRequestException(new ClientError[]{clientError1, clientError2}); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException6_ShouldReturn", HttpStatusCode.BadRequest, "MyApiErrorCode.XYZ1", "Error XYZ1 occurred.", "FormX.FieldY1", "http://juhta.net/errorxyz1", "MyApiErrorCode.XYZ2", "Error XYZ2 occurred.", "FormX.FieldY2", "http://juhta.net/errorxyz2" ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException7_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException(ErrorCode.InvalidOrderNumber, Field.CustomerName); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException7_ShouldReturn", HttpStatusCode.BadRequest, ErrorCode.InvalidOrderNumber.ToString(), null, Field.CustomerName.ToString(), null ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException8_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException("This is an error, please consult the help URL.", "http://juhta.net/helpurls/353353"); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException8_ShouldReturn", HttpStatusCode.BadRequest, null, "This is an error, please consult the help URL.", null, "http://juhta.net/helpurls/353353" ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException9_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException(ErrorCode.InvalidOrderNumber, Field.CustomerName, "The field content is not allowed at all. Please do better."); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException9_ShouldReturn", HttpStatusCode.BadRequest, ErrorCode.InvalidOrderNumber.ToString(), "The field content is not allowed at all. Please do better.", Field.CustomerName.ToString(), null ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException10_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException(ErrorCode.InvalidOrderNumber, "BadRequestExceptionField", "The field content is not allowed at all. Please do better. At least check out the help URL!"); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException10_ShouldReturn", HttpStatusCode.BadRequest, ErrorCode.InvalidOrderNumber.ToString(), "The field content is not allowed at all. Please do better. At least check out the help URL!", "BadRequestExceptionField", null ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException11_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException(ErrorCode.InvalidOrderNumber, Field.CustomerName, "The field content is not valid. Please consult the help URL!", "http://juhta.net/helpurls/125533"); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException11_ShouldReturn", HttpStatusCode.BadRequest, ErrorCode.InvalidOrderNumber.ToString(), "The field content is not valid. Please consult the help URL!", Field.CustomerName.ToString(), "http://juhta.net/helpurls/125533" ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ThrowAndSerialize_BadRequestException12_ShouldReturn() { ClientErrorResponse clientErrorResponse1, clientErrorResponse2; BadRequestException exception1 = null, exception2 = null; try { throw new BadRequestException(ErrorCode.InvalidOrderNumber, "Field.CustomerName", "The field content is not valid. Please consult the help URL!", "http://juhta.net/helpurls/125533"); } catch (BadRequestException ex) { AssertException( ex, "ThrowAndSerialize_BadRequestException11_ShouldReturn", HttpStatusCode.BadRequest, ErrorCode.InvalidOrderNumber.ToString(), "The field content is not valid. Please consult the help URL!", "Field.CustomerName", "http://juhta.net/helpurls/125533" ); clientErrorResponse1 = ex.ToClientErrorResponse(); exception1 = ex; } clientErrorResponse2 = JsonConvert.DeserializeObject<ClientErrorResponse>(JsonConvert.SerializeObject(clientErrorResponse1)); try { clientErrorResponse2.Throw(); } catch (BadRequestException ex) { exception2 = ex; } AssertExceptions(exception1, exception2); } [TestMethod] public void ToString_ClientErrorArrayConstructor_ShouldReturn() { ClientError[] clientErrors; string[] lines; try { clientErrors = new ClientError[]{new ClientError(), new ClientError {Code = "CodeValue", Field = "FieldValue", HelpUrl = "HelpUrlValue", Message = "MessageValue"}}; throw new BadRequestException(clientErrors); } catch (BadRequestException ex) { lines = ex.ToString().Split(Environment.NewLine); Assert.AreEqual<string>(" --- ClientErrorException properties ---", lines[lines.Length - 15]); Assert.AreEqual<string>(" \"Errors\": [", lines[lines.Length - 14]); Assert.AreEqual<string>(" {", lines[lines.Length - 13]); Assert.AreEqual<string>(" \"Code\": null,", lines[lines.Length - 12]); Assert.AreEqual<string>(" \"Field\": null,", lines[lines.Length - 11]); Assert.AreEqual<string>(" \"Message\": null,", lines[lines.Length - 10]); Assert.AreEqual<string>(" \"HelpUrl\": null", lines[lines.Length - 9]); Assert.AreEqual<string>(" },", lines[lines.Length - 8]); Assert.AreEqual<string>(" {", lines[lines.Length - 7]); Assert.AreEqual<string>(" \"Code\": \"CodeValue\",", lines[lines.Length - 6]); Assert.AreEqual<string>(" \"Field\": \"FieldValue\",", lines[lines.Length - 5]); Assert.AreEqual<string>(" \"Message\": \"MessageValue\",", lines[lines.Length - 4]); Assert.AreEqual<string>(" \"HelpUrl\": \"HelpUrlValue\"", lines[lines.Length - 3]); Assert.AreEqual<string>(" }", lines[lines.Length - 2]); Assert.AreEqual<string>(" ]", lines[lines.Length - 1]); } } [TestMethod] public void ToString_DefaultConstructor_ShouldReturn() { string[] lines; try { throw new BadRequestException(); } catch (BadRequestException ex) { lines = ex.ToString().Split(Environment.NewLine); Assert.AreEqual<string>(" --- ClientErrorException properties ---", lines[lines.Length - 2]); Assert.AreEqual<string>(" \"Errors\": null", lines[lines.Length - 1]); } } [TestMethod] public void ToString_NullClientErrorConstructor_ShouldReturn() { ClientError clientError = null; string[] lines; try { throw new BadRequestException(clientError); } catch (BadRequestException ex) { lines = ex.ToString().Split(Environment.NewLine); Assert.AreEqual<string>(" --- ClientErrorException properties ---", lines[lines.Length - 4]); Assert.AreEqual<string>(" \"Errors\": [", lines[lines.Length - 3]); Assert.AreEqual<string>(" null", lines[lines.Length - 2]); Assert.AreEqual<string>(" ]", lines[lines.Length - 1]); } } [TestMethod] public void ToString_SimpleClientErrorConstructor_ShouldReturn() { ClientError clientError = new ClientError(); string[] lines; try { throw new BadRequestException(clientError); } catch (BadRequestException ex) { lines = ex.ToString().Split(Environment.NewLine); Assert.AreEqual<string>(" --- ClientErrorException properties ---", lines[lines.Length - 9]); Assert.AreEqual<string>(" \"Errors\": [", lines[lines.Length - 8]); Assert.AreEqual<string>(" {", lines[lines.Length - 7]); Assert.AreEqual<string>(" \"Code\": null,", lines[lines.Length - 6]); Assert.AreEqual<string>(" \"Field\": null,", lines[lines.Length - 5]); Assert.AreEqual<string>(" \"Message\": null,", lines[lines.Length - 4]); Assert.AreEqual<string>(" \"HelpUrl\": null", lines[lines.Length - 3]); Assert.AreEqual<string>(" }", lines[lines.Length - 2]); Assert.AreEqual<string>(" ]", lines[lines.Length - 1]); } } #endregion } }
using UnityEngine; using UnityEditor; using UnityEditor.Sprites; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Reflection; using TriangleNet.Geometry; namespace Anima2D { public class SpriteMeshUtils { static Material m_DefaultMaterial = null; public static Material defaultMaterial { get { if(!m_DefaultMaterial) { GameObject go = new GameObject(); SpriteRenderer sr = go.AddComponent<SpriteRenderer>(); m_DefaultMaterial = sr.sharedMaterial; GameObject.DestroyImmediate(go); } return m_DefaultMaterial; } } public class WeightedTriangle { int m_P1; int m_P2; int m_P3; float m_W1; float m_W2; float m_W3; float m_Weight; public int p1 { get { return m_P1; } } public int p2 { get { return m_P2; } } public int p3 { get { return m_P3; } } public float w1 { get { return m_W1; } } public float w2 { get { return m_W2; } } public float w3 { get { return m_W3; } } public float weight { get { return m_Weight; } } public WeightedTriangle(int _p1, int _p2, int _p3, float _w1, float _w2, float _w3) { m_P1 = _p1; m_P2 = _p2; m_P3 = _p3; m_W1 = _w1; m_W2 = _w2; m_W3 = _w3; m_Weight = (w1 + w2 + w3) / 3f; } } public static SpriteMesh CreateSpriteMesh(Sprite sprite) { SpriteMesh spriteMesh = SpriteMeshPostprocessor.GetSpriteMeshFromSprite(sprite); SpriteMeshData spriteMeshData = null; if(!spriteMesh && sprite) { string spritePath = AssetDatabase.GetAssetPath(sprite); string directory = Path.GetDirectoryName(spritePath); string assetPath = AssetDatabase.GenerateUniqueAssetPath(directory + Path.DirectorySeparatorChar + sprite.name + ".asset"); spriteMesh = ScriptableObject.CreateInstance<SpriteMesh>(); InitFromSprite(spriteMesh,sprite); AssetDatabase.CreateAsset(spriteMesh,assetPath); spriteMeshData = ScriptableObject.CreateInstance<SpriteMeshData>(); spriteMeshData.name = spriteMesh.name + "_Data"; spriteMeshData.hideFlags = HideFlags.HideInHierarchy; InitFromSprite(spriteMeshData,sprite); AssetDatabase.AddObjectToAsset(spriteMeshData,assetPath); UpdateAssets(spriteMesh,spriteMeshData); AssetDatabase.SaveAssets(); AssetDatabase.ImportAsset(assetPath); Selection.activeObject = spriteMesh; } return spriteMesh; } public static void CreateSpriteMesh(Texture2D texture) { if(texture) { Object[] objects = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(texture)); for (int i = 0; i < objects.Length; i++) { Object o = objects [i]; Sprite sprite = o as Sprite; if (sprite) { EditorUtility.DisplayProgressBar ("Processing " + texture.name, sprite.name, (i+1) / (float)objects.Length); CreateSpriteMesh(sprite); } } EditorUtility.ClearProgressBar(); } } public static SpriteMeshData LoadSpriteMeshData(SpriteMesh spriteMesh) { if(spriteMesh) { UnityEngine.Object[] assets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(spriteMesh)); foreach(UnityEngine.Object asset in assets) { SpriteMeshData data = asset as SpriteMeshData; if(data) { return data; } } } return null; } public static void UpdateAssets(SpriteMesh spriteMesh) { UpdateAssets(spriteMesh, SpriteMeshUtils.LoadSpriteMeshData(spriteMesh)); } public static void UpdateAssets(SpriteMesh spriteMesh, SpriteMeshData spriteMeshData) { if(spriteMesh && spriteMeshData) { string spriteMeshPath = AssetDatabase.GetAssetPath(spriteMesh); SerializedObject spriteMeshSO = new SerializedObject(spriteMesh); SerializedProperty sharedMeshProp = spriteMeshSO.FindProperty("m_SharedMesh"); if(!spriteMesh.sharedMesh) { Mesh mesh = new Mesh(); mesh.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(mesh,spriteMeshPath); spriteMeshSO.Update(); sharedMeshProp.objectReferenceValue = mesh; spriteMeshSO.ApplyModifiedProperties(); EditorUtility.SetDirty(mesh); } spriteMesh.sharedMesh.name = spriteMesh.name; spriteMeshData.hideFlags = HideFlags.HideInHierarchy; EditorUtility.SetDirty(spriteMeshData); int width = 0; int height = 0; GetSpriteTextureSize(spriteMesh.sprite,ref width,ref height); Vector3[] vertices = GetMeshVertices(spriteMesh.sprite, spriteMeshData); Vector2 textureWidthHeightInv = new Vector2(1f/width,1f/height); Vector2[] uvs = (new List<Vector2>(spriteMeshData.vertices)).ConvertAll( v => Vector2.Scale(v,textureWidthHeightInv)).ToArray(); Vector3[] normals = (new List<Vector3>(vertices)).ConvertAll( v => Vector3.back ).ToArray(); BoneWeight[] boneWeightsData = spriteMeshData.boneWeights; if(boneWeightsData.Length != spriteMeshData.vertices.Length) { boneWeightsData = new BoneWeight[spriteMeshData.vertices.Length]; } List<UnityEngine.BoneWeight> boneWeights = new List<UnityEngine.BoneWeight>(boneWeightsData.Length); List<float> verticesOrder = new List<float>(spriteMeshData.vertices.Length); for (int i = 0; i < boneWeightsData.Length; i++) { BoneWeight boneWeight = boneWeightsData[i]; List< KeyValuePair<int,float> > pairs = new List<KeyValuePair<int, float>>(); pairs.Add(new KeyValuePair<int, float>(boneWeight.boneIndex0,boneWeight.weight0)); pairs.Add(new KeyValuePair<int, float>(boneWeight.boneIndex1,boneWeight.weight1)); pairs.Add(new KeyValuePair<int, float>(boneWeight.boneIndex2,boneWeight.weight2)); pairs.Add(new KeyValuePair<int, float>(boneWeight.boneIndex3,boneWeight.weight3)); pairs = pairs.OrderByDescending(s=>s.Value).ToList(); UnityEngine.BoneWeight boneWeight2 = new UnityEngine.BoneWeight(); boneWeight2.boneIndex0 = Mathf.Max(0,pairs[0].Key); boneWeight2.boneIndex1 = Mathf.Max(0,pairs[1].Key); boneWeight2.boneIndex2 = Mathf.Max(0,pairs[2].Key); boneWeight2.boneIndex3 = Mathf.Max(0,pairs[3].Key); boneWeight2.weight0 = pairs[0].Value; boneWeight2.weight1 = pairs[1].Value; boneWeight2.weight2 = pairs[2].Value; boneWeight2.weight3 = pairs[3].Value; boneWeights.Add(boneWeight2); float vertexOrder = i; if(spriteMeshData.bindPoses.Length > 0) { vertexOrder = spriteMeshData.bindPoses[boneWeight2.boneIndex0].zOrder * boneWeight2.weight0 + spriteMeshData.bindPoses[boneWeight2.boneIndex1].zOrder * boneWeight2.weight1 + spriteMeshData.bindPoses[boneWeight2.boneIndex2].zOrder * boneWeight2.weight2 + spriteMeshData.bindPoses[boneWeight2.boneIndex3].zOrder * boneWeight2.weight3; } verticesOrder.Add(vertexOrder); } List<WeightedTriangle> weightedTriangles = new List<WeightedTriangle>(spriteMeshData.indices.Length / 3); for(int i = 0; i < spriteMeshData.indices.Length; i+=3) { int p1 = spriteMeshData.indices[i]; int p2 = spriteMeshData.indices[i+1]; int p3 = spriteMeshData.indices[i+2]; weightedTriangles.Add(new WeightedTriangle(p1,p2,p3, verticesOrder[p1], verticesOrder[p2], verticesOrder[p3])); } weightedTriangles = weightedTriangles.OrderBy( t => t.weight ).ToList(); List<int> indices = new List<int>(spriteMeshData.indices.Length); for(int i = 0; i < weightedTriangles.Count; ++i) { WeightedTriangle t = weightedTriangles[i]; indices.Add(t.p1); indices.Add(t.p2); indices.Add(t.p3); } List<Matrix4x4> bindposes = (new List<BindInfo>(spriteMeshData.bindPoses)).ConvertAll( p => p.bindPose ); for (int i = 0; i < bindposes.Count; i++) { Matrix4x4 bindpose = bindposes [i]; bindpose.m23 = 0f; bindposes[i] = bindpose; } spriteMesh.sharedMesh.Clear(); spriteMesh.sharedMesh.vertices = vertices; spriteMesh.sharedMesh.uv = uvs; spriteMesh.sharedMesh.triangles = indices.ToArray(); spriteMesh.sharedMesh.normals = normals; spriteMesh.sharedMesh.boneWeights = boneWeights.ToArray(); spriteMesh.sharedMesh.bindposes = bindposes.ToArray(); spriteMesh.sharedMesh.RecalculateBounds(); #if UNITY_5_6_OR_NEWER spriteMesh.sharedMesh.RecalculateTangents(); #endif RebuildBlendShapes(spriteMesh); } } public static Vector3[] GetMeshVertices(SpriteMesh spriteMesh) { return GetMeshVertices(spriteMesh.sprite, LoadSpriteMeshData(spriteMesh)); } public static Vector3[] GetMeshVertices(Sprite sprite, SpriteMeshData spriteMeshData) { float pixelsPerUnit = GetSpritePixelsPerUnit(sprite); return (new List<Vector2>(spriteMeshData.vertices)).ConvertAll( v => TexCoordToVertex(spriteMeshData.pivotPoint,v,pixelsPerUnit)).ToArray(); } public static void GetSpriteTextureSize(Sprite sprite, ref int width, ref int height) { if(sprite) { Texture2D texture = SpriteUtility.GetSpriteTexture(sprite,false); TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter; GetWidthAndHeight(textureImporter,ref width, ref height); } } public static void GetWidthAndHeight(TextureImporter textureImporter, ref int width, ref int height) { MethodInfo methodInfo = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.Instance | BindingFlags.NonPublic); if(methodInfo != null) { object[] parameters = new object[] { null, null }; methodInfo.Invoke(textureImporter,parameters); width = (int)parameters[0]; height = (int)parameters[1]; } } public static float GetSpritePixelsPerUnit(Sprite sprite) { TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(sprite)) as TextureImporter; return textureImporter.spritePixelsPerUnit; } static void InitFromSprite(SpriteMesh spriteMesh, Sprite sprite) { SerializedObject spriteMeshSO = new SerializedObject(spriteMesh); SerializedProperty spriteProp = spriteMeshSO.FindProperty("m_Sprite"); SerializedProperty apiProp = spriteMeshSO.FindProperty("m_ApiVersion"); spriteMeshSO.Update(); apiProp.intValue = SpriteMesh.api_version; spriteProp.objectReferenceValue = sprite; spriteMeshSO.ApplyModifiedProperties(); } static void InitFromSprite(SpriteMeshData spriteMeshData, Sprite sprite) { Vector2[] vertices; IndexedEdge[] edges; int[] indices; Vector2 pivotPoint; if(sprite) { GetSpriteData(sprite, out vertices, out edges, out indices, out pivotPoint); spriteMeshData.vertices = vertices; spriteMeshData.edges = edges; spriteMeshData.indices = indices; spriteMeshData.pivotPoint = pivotPoint; } } public static void GetSpriteData(Sprite sprite, out Vector2[] vertices, out IndexedEdge[] edges, out int[] indices, out Vector2 pivotPoint) { int width = 0; int height = 0; GetSpriteTextureSize(sprite,ref width,ref height); pivotPoint = Vector2.zero; Vector2[] uvs = SpriteUtility.GetSpriteUVs(sprite,false); vertices = new Vector2[uvs.Length]; for(int i = 0; i < uvs.Length; ++i) { vertices[i] = new Vector2(uvs[i].x * width, uvs[i].y * height); } ushort[] l_indices = sprite.triangles; indices = new int[l_indices.Length]; for(int i = 0; i < l_indices.Length; ++i) { indices[i] = (int)l_indices[i]; } HashSet<IndexedEdge> edgesSet = new HashSet<IndexedEdge>(); for(int i = 0; i < indices.Length; i += 3) { int index1 = indices[i]; int index2 = indices[i+1]; int index3 = indices[i+2]; IndexedEdge edge1 = new IndexedEdge(index1,index2); IndexedEdge edge2 = new IndexedEdge(index2,index3); IndexedEdge edge3 = new IndexedEdge(index1,index3); if(edgesSet.Contains(edge1)) { edgesSet.Remove(edge1); }else{ edgesSet.Add(edge1); } if(edgesSet.Contains(edge2)) { edgesSet.Remove(edge2); }else{ edgesSet.Add(edge2); } if(edgesSet.Contains(edge3)) { edgesSet.Remove(edge3); }else{ edgesSet.Add(edge3); } } edges = new IndexedEdge[edgesSet.Count]; int edgeIndex = 0; foreach(IndexedEdge edge in edgesSet) { edges[edgeIndex] = edge; ++edgeIndex; } pivotPoint = GetPivotPoint(sprite); } public static void InitFromOutline(Texture2D texture, Rect rect, float detail, float alphaTolerance, bool holeDetection, out List<Vector2> vertices, out List<IndexedEdge> indexedEdges, out List<int> indices) { vertices = new List<Vector2>(); indexedEdges = new List<IndexedEdge>(); indices = new List<int>(); if(texture) { Vector2[][] paths = GenerateOutline(texture,rect,detail,(byte)(alphaTolerance * 255f),holeDetection); int startIndex = 0; for (int i = 0; i < paths.Length; i++) { Vector2[] path = paths [i]; for (int j = 0; j < path.Length; j++) { vertices.Add(path[j] + rect.center); indexedEdges.Add(new IndexedEdge(startIndex + j,startIndex + ((j+1) % path.Length))); } startIndex += path.Length; } List<Hole> holes = new List<Hole>(); Triangulate(vertices,indexedEdges,holes,ref indices); } } static Vector2[][] GenerateOutline(Texture2D texture, Rect rect, float detail, byte alphaTolerance, bool holeDetection) { Vector2[][] paths = null; MethodInfo methodInfo = typeof(SpriteUtility).GetMethod("GenerateOutline", BindingFlags.Static | BindingFlags.NonPublic); if(methodInfo != null) { object[] parameters = new object[] { texture,rect,detail,alphaTolerance,holeDetection,null }; methodInfo.Invoke(null,parameters); paths = (Vector2[][]) parameters[5]; } return paths; } public static void Triangulate(List<Vector2> vertices, List<IndexedEdge> edges, List<Hole> holes,ref List<int> indices) { indices.Clear(); if(vertices.Count >= 3) { InputGeometry inputGeometry = new InputGeometry(vertices.Count); for(int i = 0; i < vertices.Count; ++i) { Vector2 position = vertices[i]; inputGeometry.AddPoint(position.x,position.y); } for(int i = 0; i < edges.Count; ++i) { IndexedEdge edge = edges[i]; inputGeometry.AddSegment(edge.index1,edge.index2); } for(int i = 0; i < holes.Count; ++i) { Vector2 hole = holes[i].vertex; inputGeometry.AddHole(hole.x,hole.y); } TriangleNet.Mesh triangleMesh = new TriangleNet.Mesh(); triangleMesh.Triangulate(inputGeometry); foreach (TriangleNet.Data.Triangle triangle in triangleMesh.Triangles) { if(triangle.P0 >= 0 && triangle.P0 < vertices.Count && triangle.P0 >= 0 && triangle.P1 < vertices.Count && triangle.P0 >= 0 && triangle.P2 < vertices.Count) { indices.Add(triangle.P0); indices.Add(triangle.P2); indices.Add(triangle.P1); } } } } public static void Tessellate(List<Vector2> vertices, List<IndexedEdge> indexedEdges, List<Hole> holes, List<int> indices, float tessellationAmount) { if(tessellationAmount <= 0f) { return; } indices.Clear(); if(vertices.Count >= 3) { InputGeometry inputGeometry = new InputGeometry(vertices.Count); for(int i = 0; i < vertices.Count; ++i) { Vector2 vertex = vertices[i]; inputGeometry.AddPoint(vertex.x,vertex.y); } for(int i = 0; i < indexedEdges.Count; ++i) { IndexedEdge edge = indexedEdges[i]; inputGeometry.AddSegment(edge.index1,edge.index2); } for(int i = 0; i < holes.Count; ++i) { Vector2 hole = holes[i].vertex; inputGeometry.AddHole(hole.x,hole.y); } TriangleNet.Mesh triangleMesh = new TriangleNet.Mesh(); TriangleNet.Tools.Statistic statistic = new TriangleNet.Tools.Statistic(); triangleMesh.Triangulate(inputGeometry); triangleMesh.Behavior.MinAngle = 20.0; triangleMesh.Behavior.SteinerPoints = -1; triangleMesh.Refine(true); statistic.Update(triangleMesh,1); triangleMesh.Refine(statistic.LargestArea / tessellationAmount); triangleMesh.Renumber(); vertices.Clear(); indexedEdges.Clear(); foreach(TriangleNet.Data.Vertex vertex in triangleMesh.Vertices) { vertices.Add(new Vector2((float)vertex.X,(float)vertex.Y)); } foreach(TriangleNet.Data.Segment segment in triangleMesh.Segments) { indexedEdges.Add(new IndexedEdge(segment.P0,segment.P1)); } foreach (TriangleNet.Data.Triangle triangle in triangleMesh.Triangles) { if(triangle.P0 >= 0 && triangle.P0 < vertices.Count && triangle.P0 >= 0 && triangle.P1 < vertices.Count && triangle.P0 >= 0 && triangle.P2 < vertices.Count) { indices.Add(triangle.P0); indices.Add(triangle.P2); indices.Add(triangle.P1); } } } } public static Vector3 TexCoordToVertex(Vector2 pivotPoint, Vector2 vertex, float pixelsPerUnit) { return (Vector3)(vertex - pivotPoint) / pixelsPerUnit; } public static Vector2 VertexToTexCoord(SpriteMesh spriteMesh, Vector2 pivotPoint, Vector3 vertex, float pixelsPerUnit) { Vector2 texCoord = Vector3.zero; if(spriteMesh != null) { texCoord = (Vector2)vertex * pixelsPerUnit + pivotPoint; } return texCoord; } public static Rect GetRect(Sprite sprite) { float pixelsPerUnit = GetSpritePixelsPerUnit(sprite); float factor = pixelsPerUnit / sprite.pixelsPerUnit; Vector2 position = sprite.rect.position * factor; Vector2 size = sprite.rect.size * factor; return new Rect(position.x,position.y,size.x,size.y); } public static Vector2 GetPivotPoint(Sprite sprite) { float pixelsPerUnit = GetSpritePixelsPerUnit(sprite); return (sprite.pivot + sprite.rect.position) * pixelsPerUnit / sprite.pixelsPerUnit; } public static Rect CalculateSpriteRect(SpriteMesh spriteMesh, int padding) { int width = 0; int height = 0; GetSpriteTextureSize(spriteMesh.sprite,ref width,ref height); SpriteMeshData spriteMeshData = LoadSpriteMeshData(spriteMesh); Rect rect = spriteMesh.sprite.rect; if(spriteMeshData) { Vector2 min = new Vector2(float.MaxValue,float.MaxValue); Vector2 max = new Vector2(float.MinValue,float.MinValue); for (int i = 0; i < spriteMeshData.vertices.Length; i++) { Vector2 v = spriteMeshData.vertices[i]; if(v.x < min.x) min.x = v.x; if(v.y < min.y) min.y = v.y; if(v.x > max.x) max.x = v.x; if(v.y > max.y) max.y = v.y; } rect.position = min - Vector2.one * padding; rect.size = (max - min) + Vector2.one * padding * 2f; rect = MathUtils.ClampRect(rect,new Rect(0f,0f,width,height)); } return rect; } public static SpriteMeshInstance CreateSpriteMeshInstance(SpriteMesh spriteMesh, bool undo = true) { if(spriteMesh) { GameObject gameObject = new GameObject(spriteMesh.name); if(undo) { Undo.RegisterCreatedObjectUndo(gameObject,Undo.GetCurrentGroupName()); } return CreateSpriteMeshInstance(spriteMesh, gameObject, undo); } return null; } public static SpriteMeshInstance CreateSpriteMeshInstance(SpriteMesh spriteMesh, GameObject gameObject, bool undo = true) { SpriteMeshInstance spriteMeshInstance = null; if(spriteMesh && gameObject) { if(undo) { spriteMeshInstance = Undo.AddComponent<SpriteMeshInstance>(gameObject); }else{ spriteMeshInstance = gameObject.AddComponent<SpriteMeshInstance>(); } spriteMeshInstance.spriteMesh = spriteMesh; spriteMeshInstance.sharedMaterial = defaultMaterial; SpriteMeshData spriteMeshData = SpriteMeshUtils.LoadSpriteMeshData(spriteMesh); List<Bone2D> bones = new List<Bone2D>(); List<string> paths = new List<string>(); Vector4 zero = new Vector4 (0f, 0f, 0f, 1f); foreach(BindInfo bindInfo in spriteMeshData.bindPoses) { Matrix4x4 m = spriteMeshInstance.transform.localToWorldMatrix * bindInfo.bindPose.inverse; GameObject bone = new GameObject(bindInfo.name); if(undo) { Undo.RegisterCreatedObjectUndo(bone,Undo.GetCurrentGroupName()); } Bone2D boneComponent = bone.AddComponent<Bone2D>(); boneComponent.localLength = bindInfo.boneLength; bone.transform.position = m * zero; bone.transform.rotation = m.GetRotation(); bone.transform.parent = gameObject.transform; bones.Add(boneComponent); paths.Add(bindInfo.path); } BoneUtils.ReconstructHierarchy(bones,paths); spriteMeshInstance.bones = bones; SpriteMeshUtils.UpdateRenderer(spriteMeshInstance, undo); EditorUtility.SetDirty(spriteMeshInstance); } return spriteMeshInstance; } public static bool HasNullBones(SpriteMeshInstance spriteMeshInstance) { if(spriteMeshInstance) { return spriteMeshInstance.bones.Contains(null); } return false; } public static bool CanEnableSkinning(SpriteMeshInstance spriteMeshInstance) { return spriteMeshInstance.spriteMesh && !HasNullBones(spriteMeshInstance) && spriteMeshInstance.bones.Count > 0 && (spriteMeshInstance.spriteMesh.sharedMesh.bindposes.Length == spriteMeshInstance.bones.Count); } public static void UpdateRenderer(SpriteMeshInstance spriteMeshInstance, bool undo = true) { if(!spriteMeshInstance) { return; } SerializedObject spriteMeshInstaceSO = new SerializedObject(spriteMeshInstance); SpriteMesh spriteMesh = spriteMeshInstaceSO.FindProperty("m_SpriteMesh").objectReferenceValue as SpriteMesh; if(spriteMesh) { Mesh sharedMesh = spriteMesh.sharedMesh; if(sharedMesh.bindposes.Length > 0 && spriteMeshInstance.bones.Count > sharedMesh.bindposes.Length) { spriteMeshInstance.bones = spriteMeshInstance.bones.GetRange(0,sharedMesh.bindposes.Length); } if(CanEnableSkinning(spriteMeshInstance)) { MeshFilter meshFilter = spriteMeshInstance.cachedMeshFilter; MeshRenderer meshRenderer = spriteMeshInstance.cachedRenderer as MeshRenderer; if(meshFilter) { if(undo) { Undo.DestroyObjectImmediate(meshFilter); }else{ GameObject.DestroyImmediate(meshFilter); } } if(meshRenderer) { if(undo) { Undo.DestroyObjectImmediate(meshRenderer); }else{ GameObject.DestroyImmediate(meshRenderer); } } SkinnedMeshRenderer skinnedMeshRenderer = spriteMeshInstance.cachedSkinnedRenderer; if(!skinnedMeshRenderer) { if(undo) { skinnedMeshRenderer = Undo.AddComponent<SkinnedMeshRenderer>(spriteMeshInstance.gameObject); }else{ skinnedMeshRenderer = spriteMeshInstance.gameObject.AddComponent<SkinnedMeshRenderer>(); } } skinnedMeshRenderer.bones = spriteMeshInstance.bones.ConvertAll( bone => bone.transform ).ToArray(); if(spriteMeshInstance.bones.Count > 0) { skinnedMeshRenderer.rootBone = spriteMeshInstance.bones[0].transform; } EditorUtility.SetDirty(skinnedMeshRenderer); }else{ SkinnedMeshRenderer skinnedMeshRenderer = spriteMeshInstance.cachedSkinnedRenderer; MeshFilter meshFilter = spriteMeshInstance.cachedMeshFilter; MeshRenderer meshRenderer = spriteMeshInstance.cachedRenderer as MeshRenderer; if(skinnedMeshRenderer) { if(undo) { Undo.DestroyObjectImmediate(skinnedMeshRenderer); }else{ GameObject.DestroyImmediate(skinnedMeshRenderer); } } if(!meshFilter) { if(undo) { meshFilter = Undo.AddComponent<MeshFilter>(spriteMeshInstance.gameObject); }else{ meshFilter = spriteMeshInstance.gameObject.AddComponent<MeshFilter>(); } EditorUtility.SetDirty(meshFilter); } if(!meshRenderer) { if(undo) { meshRenderer = Undo.AddComponent<MeshRenderer>(spriteMeshInstance.gameObject); }else{ meshRenderer = spriteMeshInstance.gameObject.AddComponent<MeshRenderer>(); } EditorUtility.SetDirty(meshRenderer); } } } } public static bool NeedsOverride(SpriteMesh spriteMesh) { if(!spriteMesh || !spriteMesh.sprite) return false; SpriteMeshData spriteMeshData = LoadSpriteMeshData(spriteMesh); if(!spriteMeshData) return false; ushort[] triangles = spriteMesh.sprite.triangles; if(triangles.Length != spriteMeshData.indices.Length) return true; for(int i = 0; i < triangles.Length; i++) { if(spriteMeshData.indices[i] != triangles[i]) { return true; } } return false; } public static BlendShape CreateBlendShape(SpriteMesh spriteMesh, string blendshapeName) { BlendShape l_blendshape = null; SpriteMeshData spriteMeshData = LoadSpriteMeshData(spriteMesh); if(spriteMeshData) { l_blendshape = BlendShape.Create(blendshapeName); l_blendshape.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(l_blendshape,spriteMeshData); List<BlendShape> l_blendshapes = new List<BlendShape>(spriteMeshData.blendshapes); l_blendshapes.Add(l_blendshape); spriteMeshData.blendshapes = l_blendshapes.ToArray(); EditorUtility.SetDirty(spriteMeshData); EditorUtility.SetDirty(l_blendshape); } return l_blendshape; } public static BlendShapeFrame CreateBlendShapeFrame(BlendShape blendshape, float weight, Vector3[] vertices) { BlendShapeFrame l_blendshapeFrame = null; if(blendshape && vertices != null) { l_blendshapeFrame = BlendShapeFrame.Create(weight,vertices); l_blendshapeFrame.hideFlags = HideFlags.HideInHierarchy; AssetDatabase.AddObjectToAsset(l_blendshapeFrame,blendshape); List<BlendShapeFrame> l_blendshapeFrames = new List<BlendShapeFrame>(blendshape.frames); l_blendshapeFrames.Add(l_blendshapeFrame); l_blendshapeFrames.Sort( (a,b) => { return a.weight.CompareTo(b.weight); } ); blendshape.frames = l_blendshapeFrames.ToArray(); EditorUtility.SetDirty(blendshape); EditorUtility.SetDirty(l_blendshapeFrame); } return l_blendshapeFrame; } public static void DestroyBlendShapes(SpriteMesh spriteMesh) { DestroyBlendShapes(spriteMesh, false, ""); } public static void DestroyBlendShapes(SpriteMesh spriteMesh, bool undo, string undoName) { DestroyBlendShapes(LoadSpriteMeshData(spriteMesh), false, ""); } public static void DestroyBlendShapes(SpriteMeshData spriteMeshData, bool undo, string undoName) { if(spriteMeshData) { if(undo && !string.IsNullOrEmpty(undoName)) { Undo.RegisterCompleteObjectUndo(spriteMeshData,undoName); } foreach(BlendShape blendShape in spriteMeshData.blendshapes) { foreach(BlendShapeFrame frame in blendShape.frames) { if(undo) { Undo.DestroyObjectImmediate(frame); }else{ GameObject.DestroyImmediate(frame,true); } } if(undo) { Undo.DestroyObjectImmediate(blendShape); }else{ GameObject.DestroyImmediate(blendShape,true); } } spriteMeshData.blendshapes = new BlendShape[0]; } } public static void RebuildBlendShapes(SpriteMesh spriteMesh) { RebuildBlendShapes(spriteMesh,spriteMesh.sharedMesh); } public static void RebuildBlendShapes(SpriteMesh spriteMesh, Mesh mesh) { if(!mesh) return; if(!spriteMesh) return; BlendShape[] blendShapes = null; SpriteMeshData spriteMeshData = LoadSpriteMeshData(spriteMesh); if(spriteMeshData) { blendShapes = spriteMeshData.blendshapes; } if(spriteMesh.sharedMesh.vertexCount != mesh.vertexCount) { return; } if(blendShapes != null) { #if !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2) List<string> blendShapeNames = new List<string>(); mesh.ClearBlendShapes(); Vector3[] from = mesh.vertices; for (int i = 0; i < blendShapes.Length; i++) { BlendShape blendshape = blendShapes[i]; if(blendshape) { string blendShapeName = blendshape.name; if(blendShapeNames.Contains(blendShapeName)) { Debug.LogWarning("Found repeated BlendShape name '" + blendShapeName + "' in SpriteMesh: " + spriteMesh.name); }else{ blendShapeNames.Add(blendShapeName); for(int j = 0; j < blendshape.frames.Length; j++) { BlendShapeFrame l_blendshapeFrame = blendshape.frames[j]; if(l_blendshapeFrame && from.Length == l_blendshapeFrame.vertices.Length) { Vector3[] deltaVertices = GetDeltaVertices(from, l_blendshapeFrame.vertices); mesh.AddBlendShapeFrame(blendShapeName, l_blendshapeFrame.weight, deltaVertices, null, null); } } } } } mesh.UploadMeshData(false); EditorUtility.SetDirty(mesh); #endif } } static Vector3[] GetDeltaVertices(Vector3[] from, Vector3[] to) { Vector3[] result = new Vector3[from.Length]; for (int i = 0; i < to.Length; i++) { result[i] = to[i] - from[i]; } return result; } } }
//------------------------------------------------------------------------------ // <copyright file="DataGridViewAccessibleObject.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; using System.Drawing; namespace System.Windows.Forms { public partial class DataGridView { [ System.Runtime.InteropServices.ComVisible(true) ] /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridView.DataGridViewAccessibleObject"]/*' /> protected class DataGridViewAccessibleObject : ControlAccessibleObject { DataGridView owner; DataGridViewTopRowAccessibleObject topRowAccessibilityObject = null; DataGridViewSelectedCellsAccessibleObject selectedCellsAccessibilityObject = null; /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridViewAccessibleObject.DataGridViewAccessibleObject"]/*' /> public DataGridViewAccessibleObject(DataGridView owner) : base(owner) { this.owner = owner; } /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridViewAccessibleObject.Name"]/*' /> public override string Name { [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // Don't localize string "DataGridView". get { string name = this.Owner.AccessibleName; if (!String.IsNullOrEmpty(name)) { return name; } else { // The default name should not be localized. return "DataGridView"; } } } /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridViewAccessibleObject.Role"]/*' /> public override AccessibleRole Role { get { AccessibleRole role = owner.AccessibleRole; if (role != AccessibleRole.Default) { return role; } // the Default AccessibleRole is Table return AccessibleRole.Table; } } private AccessibleObject TopRowAccessibilityObject { get { if (this.topRowAccessibilityObject == null) { this.topRowAccessibilityObject = new DataGridViewTopRowAccessibleObject(this.owner); } return this.topRowAccessibilityObject; } } private AccessibleObject SelectedCellsAccessibilityObject { get { if (this.selectedCellsAccessibilityObject == null) { this.selectedCellsAccessibilityObject = new DataGridViewSelectedCellsAccessibleObject(this.owner); } return this.selectedCellsAccessibilityObject; } } /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridViewAccessibleObject.GetChild"]/*' /> public override AccessibleObject GetChild(int index) { if (this.owner.Columns.Count == 0) { System.Diagnostics.Debug.Assert(this.GetChildCount() == 0); return null; } if (index < 1 && this.owner.ColumnHeadersVisible) { return this.TopRowAccessibilityObject; } if (this.owner.ColumnHeadersVisible) { index--; } if (index < this.owner.Rows.GetRowCount(DataGridViewElementStates.Visible)) { int actualRowIndex = this.owner.Rows.DisplayIndexToRowIndex(index); return this.owner.Rows[actualRowIndex].AccessibilityObject; } index -= this.owner.Rows.GetRowCount(DataGridViewElementStates.Visible); if (this.owner.horizScrollBar.Visible) { if (index == 0) { return this.owner.horizScrollBar.AccessibilityObject; } else { index--; } } if (this.owner.vertScrollBar.Visible) { if (index == 0) { return this.owner.vertScrollBar.AccessibilityObject; } } return null; } /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridViewAccessibleObject.GetChildCount"]/*' /> public override int GetChildCount() { if (this.owner.Columns.Count == 0) { return 0; } int childCount = this.owner.Rows.GetRowCount(DataGridViewElementStates.Visible); // the column header collection Accessible Object if (this.owner.ColumnHeadersVisible) { childCount++; } if (this.owner.horizScrollBar.Visible) { childCount++; } if (this.owner.vertScrollBar.Visible) { childCount++; } return childCount; } /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridViewAccessibleObject.GetFocused"]/*' /> public override AccessibleObject GetFocused() { if (this.owner.Focused && this.owner.CurrentCell != null) { return this.owner.CurrentCell.AccessibilityObject; } else { return null; } } /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridViewAccessibleObject.GetSelected"]/*' /> public override AccessibleObject GetSelected() { return this.SelectedCellsAccessibilityObject; } /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridViewAccessibleObject.HitTest"]/*' /> public override AccessibleObject HitTest(int x, int y) { Point pt = this.owner.PointToClient(new Point(x, y)); HitTestInfo hti = this.owner.HitTest(pt.X, pt.Y); switch (hti.Type) { case DataGridViewHitTestType.Cell: return this.owner.Rows[hti.RowIndex].Cells[hti.ColumnIndex].AccessibilityObject; case DataGridViewHitTestType.ColumnHeader: // map the column index to the actual display index int actualDisplayIndex = this.owner.Columns.ColumnIndexToActualDisplayIndex(hti.ColumnIndex, DataGridViewElementStates.Visible); if (this.owner.RowHeadersVisible) { // increment the childIndex because the first child in the TopRowAccessibleObject is the TopLeftHeaderCellAccObj return this.TopRowAccessibilityObject.GetChild(actualDisplayIndex + 1); } else { return this.TopRowAccessibilityObject.GetChild(actualDisplayIndex); } case DataGridViewHitTestType.RowHeader: return this.owner.Rows[hti.RowIndex].AccessibilityObject; case DataGridViewHitTestType.TopLeftHeader: return this.owner.TopLeftHeaderCell.AccessibilityObject; case DataGridViewHitTestType.VerticalScrollBar: return this.owner.VerticalScrollBar.AccessibilityObject; case DataGridViewHitTestType.HorizontalScrollBar: return this.owner.HorizontalScrollBar.AccessibilityObject; default: return null; } } /// <include file='doc\DataGridViewAccessibleObject.uex' path='docs/doc[@for="DataGridViewAccessibleObject.Navigate"]/*' /> [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public override AccessibleObject Navigate(AccessibleNavigation navigationDirection) { switch (navigationDirection) { case AccessibleNavigation.FirstChild: return this.GetChild(0); case AccessibleNavigation.LastChild: return this.GetChild(this.GetChildCount() - 1); default: return null; } } /* [....]: why is this method defined and not used? // this method is called when the accessible object needs to be reset // Example: when the user changes the display index on a column or when the user modifies the column collection internal void Reset() { this.NotifyClients(AccessibleEvents.Reorder); } */ } } }
namespace Microsoft.Protocols.TestSuites.MS_MEETS { using System; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// Scenario 4 Test Cases. Test recurring meeting related requirements. /// Add recurring meeting to a workspace. /// </summary> [TestClass] public class S04_RecurringMeeting : TestClassBase { #region Variables /// <summary> /// An instance of IMEETSAdapter. /// </summary> private IMS_MEETSAdapter meetsAdapter; /// <summary> /// An instance of IMS_MEETSSUTControlAdapter. /// </summary> private IMS_MEETSSUTControlAdapter sutControlAdapter; #endregion #region Test suite initialization and cleanup /// <summary> /// Initialize the test suite. /// </summary> /// <param name="context">The test context instance</param> [ClassInitialize] public static void ClassInitialize(TestContext context) { // Setup test site TestClassBase.Initialize(context); } /// <summary> /// Reset the test environment. /// </summary> [ClassCleanup] public static void ClassCleanup() { // Cleanup test site, must be called to ensure closing of logs. TestClassBase.Cleanup(); } #endregion #region Test Cases /// <summary> /// This test case is used to verify the recurring meeting related requirements. /// </summary> [TestCategory("MSMEETS"), TestMethod()] public void MSMEETS_S04_TC01_RecurringMeetingOperations() { // Create 3 workspaces. string emptyWorkspaceTitle = TestSuiteBase.GetUniqueWorkspaceTitle(); SoapResult<CreateWorkspaceResponseCreateWorkspaceResult> createWorkspaceResult = this.meetsAdapter.CreateWorkspace(emptyWorkspaceTitle, null, null, null); Site.Assert.IsNull(createWorkspaceResult.Exception, "Create workspace should succeed"); string emptyWorkspaceUrl = createWorkspaceResult.Result.CreateWorkspace.Url; string singleWorkspaceTitle = TestSuiteBase.GetUniqueWorkspaceTitle(); createWorkspaceResult = this.meetsAdapter.CreateWorkspace(singleWorkspaceTitle, null, null, null); Site.Assert.IsNull(createWorkspaceResult.Exception, "Create workspace should succeed"); string singleMeetingWorkspaceUrl = createWorkspaceResult.Result.CreateWorkspace.Url; string recurringWorkspaceTitle = TestSuiteBase.GetUniqueWorkspaceTitle(); createWorkspaceResult = this.meetsAdapter.CreateWorkspace(recurringWorkspaceTitle, null, null, null); Site.Assert.IsNull(createWorkspaceResult.Exception, "Create workspace should succeed"); string recurringMeetingWorkspaceUrl = createWorkspaceResult.Result.CreateWorkspace.Url; // Add a single instance meeting in the single meeting workspace. this.meetsAdapter.Url = singleMeetingWorkspaceUrl + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); string organizerEmail = Common.GetConfigurationPropertyValue("OrganizerEmail", this.Site); string meetingTitle = TestSuiteBase.GetUniqueMeetingTitle(); string meetingLocation = TestSuiteBase.GetUniqueMeetingLocation(); SoapResult<AddMeetingResponseAddMeetingResult> addMeeting = this.meetsAdapter.AddMeeting(organizerEmail, Guid.NewGuid().ToString(), null, DateTime.Now, meetingTitle, meetingLocation, DateTime.Now, DateTime.Now.AddHours(1), null); Site.Assert.IsNull(addMeeting.Exception, "AddMeeting should succeed"); // Add a recurring meeting in the recurring meeting workspace. this.meetsAdapter.Url = recurringMeetingWorkspaceUrl + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); string icalendar = TestSuiteBase.GetICalendar(Guid.NewGuid().ToString(), true); SoapResult<AddMeetingFromICalResponseAddMeetingFromICalResult> addMeetingFromICalResult = this.meetsAdapter.AddMeetingFromICal(organizerEmail, icalendar); Site.Assert.IsNull(addMeetingFromICalResult.Exception, "AddMeetingFromICal should succeed"); // Send GetMeetingsInformation to the empty workspace. this.meetsAdapter.Url = emptyWorkspaceUrl + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); SoapResult<GetMeetingsInformationResponseGetMeetingsInformationResult> emptyInfoResult = this.meetsAdapter.GetMeetingsInformation(MeetingInfoTypes.QueryOthers, null); Site.Assert.IsNull(emptyInfoResult.Exception, "GetMeetingsInformation should succeed"); Site.Assert.AreEqual<string>("0", emptyInfoResult.Result.MeetingsInformation.WorkspaceStatus.MeetingCount, "Workspace should not contain meeting instance."); // Send GetMeetingsInformation to the single meeting workspace. this.meetsAdapter.Url = singleMeetingWorkspaceUrl + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); SoapResult<GetMeetingsInformationResponseGetMeetingsInformationResult> singleInfoResult = this.meetsAdapter.GetMeetingsInformation(MeetingInfoTypes.QueryOthers, null); Site.Assert.IsNull(singleInfoResult.Exception, "GetMeetingsInformation should succeed"); Site.Assert.AreEqual<string>("1", singleInfoResult.Result.MeetingsInformation.WorkspaceStatus.MeetingCount, "Workspace should contain only 1 meeting instance."); // Send GetMeetingsInformation to the recurring meeting workspace. this.meetsAdapter.Url = recurringMeetingWorkspaceUrl + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); SoapResult<GetMeetingsInformationResponseGetMeetingsInformationResult> recurringInfoResult = this.meetsAdapter.GetMeetingsInformation(MeetingInfoTypes.QueryOthers, null); Site.Assert.IsNull(recurringInfoResult.Exception, "GetMeetingsInformation should succeed"); // If the MeetingCount that server returns is -1, MS-MEETS_R215 is verified. Site.CaptureRequirementIfAreEqual<string>( "-1", recurringInfoResult.Result.MeetingsInformation.WorkspaceStatus.MeetingCount, 215, @"[In GetMeetingsInformationResponse]This [MeetingCount]MUST be set to -1 if the meeting workspace subsite has a recurring meeting."); // Send GetMeetingWorkspaces to the parent web site. this.meetsAdapter.Url = Common.GetConfigurationPropertyValue("TargetServiceUrl", this.Site); // Get available workspace for non-recurring meeting, server should return the first and second workspaces. SoapResult<GetMeetingWorkspacesResponseGetMeetingWorkspacesResult> getMeetingWorkspacesResult = this.meetsAdapter.GetMeetingWorkspaces(false); Site.Assert.IsNull(getMeetingWorkspacesResult.Exception, "GetMeetingWorkspaces should succeed"); // If only empty workspaces and single instance workspaces are returned, MS-MEETS_R230 is verified. Site.CaptureRequirementIfAreEqual<int>( 2, getMeetingWorkspacesResult.Result.MeetingWorkspaces.Length, 230, @"[In GetMeetingWorkspaces][If the value [of recurring]is false], empty workspaces and single instance workspaces are returned."); // If only workspaces to which the protocol client can add meetings are returned, MS-MEETS_R224 is verified. Site.CaptureRequirementIfAreEqual<int>( 2, getMeetingWorkspacesResult.Result.MeetingWorkspaces.Length, 224, @"[In GetMeetingWorkspacesSoapOut]The protocol server MUST return only workspaces to which the protocol client can add meetings."); getMeetingWorkspacesResult = this.meetsAdapter.GetMeetingWorkspaces(null); Site.Assert.IsNull(getMeetingWorkspacesResult.Exception, "GetMeetingWorkspaces should succeed"); // If only empty workspaces and single instance workspaces are returned, MS-MEETS_R2311 is verified. Site.CaptureRequirementIfAreEqual<int>( 2, getMeetingWorkspacesResult.Result.MeetingWorkspaces.Length, 2311, @"[In GetMeetingWorkspaces]If [the value of recurring is] not specified, the server will treat it as false."); // Get available workspace for recurring meeting, server should only return the first workspace getMeetingWorkspacesResult = this.meetsAdapter.GetMeetingWorkspaces(true); Site.Assert.IsNull(getMeetingWorkspacesResult.Exception, "GetMeetingWorkspaces should succeed"); // If only empty workspaces are returned, MS-MEETS_R231 is verified. Site.CaptureRequirementIfAreEqual<int>( 1, getMeetingWorkspacesResult.Result.MeetingWorkspaces.Length, 231, @"[In GetMeetingWorkspaces]If [the value of recurring is]true, only empty workspaces are returned."); // Clean up the SUT. this.meetsAdapter.Url = emptyWorkspaceUrl + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); SoapResult<Null> deleteResult = this.meetsAdapter.DeleteWorkspace(); Site.Assert.IsNull(deleteResult.Exception, "DeleteWorkspace should succeed"); this.meetsAdapter.Url = singleMeetingWorkspaceUrl + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); deleteResult = this.meetsAdapter.DeleteWorkspace(); Site.Assert.IsNull(deleteResult.Exception, "DeleteWorkspace should succeed"); this.meetsAdapter.Url = recurringMeetingWorkspaceUrl + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); deleteResult = this.meetsAdapter.DeleteWorkspace(); Site.Assert.IsNull(deleteResult.Exception, "DeleteWorkspace should succeed"); } /// <summary> /// This test case is used to verify the error code when adding recurring meeting to a non-empty workspace. /// </summary> [TestCategory("MSMEETS"), TestMethod()] public void MSMEETS_S04_TC02_RecurringMeetingError() { // Create a workspace. string workspaceTitle = TestSuiteBase.GetUniqueWorkspaceTitle(); SoapResult<CreateWorkspaceResponseCreateWorkspaceResult> createWorkspaceResult = this.meetsAdapter.CreateWorkspace(workspaceTitle, null, null, null); Site.Assert.IsNull(createWorkspaceResult.Exception, "Create workspace should succeed"); // Add a single instance meeting in the workspace. this.meetsAdapter.Url = createWorkspaceResult.Result.CreateWorkspace.Url + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); string organizerEmail = Common.GetConfigurationPropertyValue("OrganizerEmail", this.Site); string meetingTitle = TestSuiteBase.GetUniqueMeetingTitle(); string meetingLocation = TestSuiteBase.GetUniqueMeetingLocation(); SoapResult<AddMeetingResponseAddMeetingResult> addMeetingResult = this.meetsAdapter.AddMeeting(organizerEmail, Guid.NewGuid().ToString(), null, DateTime.Now, meetingTitle, meetingLocation, DateTime.Now, DateTime.Now.AddHours(1), false); Site.Assert.IsNull(addMeetingResult.Exception, "AddMeeting should succeed"); // Add a recurring meeting in the same workspace. string icalendar = TestSuiteBase.GetICalendar(Guid.NewGuid().ToString(), true); SoapResult<AddMeetingFromICalResponseAddMeetingFromICalResult> addMeetingFromICalResult = this.meetsAdapter.AddMeetingFromICal(organizerEmail, icalendar); // Add the log information. Site.Log.Add(Microsoft.Protocols.TestTools.LogEntryKind.Comment, "Verify MS-MEETS_R89: The response when a client tries to add a recurring meeting to a workspace is: {0}", addMeetingFromICalResult.Exception.Detail.InnerText); // If a SOAP fault with SOAP fault code "0x00000003" is returned, MS-MEETS_R89 is captured. Site.CaptureRequirementIfAreEqual<string>( "0x00000003", addMeetingFromICalResult.GetErrorCode(), 89, @"[In AddMeetingFromICalResponse]If the protocol client tries to add a recurring meeting to a workspace that already contains a meeting, the response MUST be a SOAP fault with SOAP fault code ""0x00000003""."); // Clean up the SUT. this.meetsAdapter.Url = createWorkspaceResult.Result.CreateWorkspace.Url + Common.GetConfigurationPropertyValue("EntryUrl", this.Site); SoapResult<Null> deleteResult = this.meetsAdapter.DeleteWorkspace(); Site.Assert.IsNull(deleteResult.Exception, "DeleteWorkspace should succeed"); } #endregion #region Test case initialization and cleanup /// <summary> /// Test case initialize method. /// </summary> [TestInitialize] public void TestCaseInitialize() { this.meetsAdapter = this.Site.GetAdapter<IMS_MEETSAdapter>(); Common.CheckCommonProperties(this.Site, true); this.meetsAdapter.Url = Common.GetConfigurationPropertyValue("TargetServiceUrl", this.Site); this.sutControlAdapter = Site.GetAdapter<IMS_MEETSSUTControlAdapter>(); // Make sure the test environment is clean before test case run. bool isClean = this.sutControlAdapter.PrepareTestEnvironment(this.meetsAdapter.Url); this.Site.Assert.IsTrue(isClean, "The specified site should not have meeting workspaces."); // Initialize the TestSuiteBase TestSuiteBase.Initialize(this.Site); } /// <summary> /// Test case cleanup method. /// </summary> [TestCleanup] public void TestCaseCleanup() { this.meetsAdapter.Reset(); } #endregion } }
using System; using System.Collections.Generic; using Csla; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERLevel; namespace ParentLoadSoftDelete.Business.ERLevel { /// <summary> /// E05_CountryColl (editable child list).<br/> /// This is a generated base class of <see cref="E05_CountryColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="E04_SubContinent"/> editable child object.<br/> /// The items of the collection are <see cref="E06_Country"/> objects. /// </remarks> [Serializable] public partial class E05_CountryColl : BusinessListBase<E05_CountryColl, E06_Country> { #region Collection Business Methods /// <summary> /// Removes a <see cref="E06_Country"/> item from the collection. /// </summary> /// <param name="country_ID">The Country_ID of the item to be removed.</param> public void Remove(int country_ID) { foreach (var e06_Country in this) { if (e06_Country.Country_ID == country_ID) { Remove(e06_Country); break; } } } /// <summary> /// Determines whether a <see cref="E06_Country"/> item is in the collection. /// </summary> /// <param name="country_ID">The Country_ID of the item to search for.</param> /// <returns><c>true</c> if the E06_Country is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int country_ID) { foreach (var e06_Country in this) { if (e06_Country.Country_ID == country_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="E06_Country"/> item is in the collection's DeletedList. /// </summary> /// <param name="country_ID">The Country_ID of the item to search for.</param> /// <returns><c>true</c> if the E06_Country is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int country_ID) { foreach (var e06_Country in DeletedList) { if (e06_Country.Country_ID == country_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="E06_Country"/> item of the <see cref="E05_CountryColl"/> collection, based on item key properties. /// </summary> /// <param name="country_ID">The Country_ID.</param> /// <returns>A <see cref="E06_Country"/> object.</returns> public E06_Country FindE06_CountryByParentProperties(int country_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Country_ID.Equals(country_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="E05_CountryColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="E05_CountryColl"/> collection.</returns> internal static E05_CountryColl NewE05_CountryColl() { return DataPortal.CreateChild<E05_CountryColl>(); } /// <summary> /// Factory method. Loads a <see cref="E05_CountryColl"/> object from the given list of E06_CountryDto. /// </summary> /// <param name="data">The list of <see cref="E06_CountryDto"/>.</param> /// <returns>A reference to the fetched <see cref="E05_CountryColl"/> object.</returns> internal static E05_CountryColl GetE05_CountryColl(List<E06_CountryDto> data) { E05_CountryColl obj = new E05_CountryColl(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="E05_CountryColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public E05_CountryColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads all <see cref="E05_CountryColl"/> collection items from the given list of E06_CountryDto. /// </summary> /// <param name="data">The list of <see cref="E06_CountryDto"/>.</param> private void Fetch(List<E06_CountryDto> data) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; var args = new DataPortalHookArgs(data); OnFetchPre(args); foreach (var dto in data) { Add(E06_Country.GetE06_Country(dto)); } OnFetchPost(args); RaiseListChangedEvents = rlce; } /// <summary> /// Loads <see cref="E06_Country"/> items on the E05_CountryObjects collection. /// </summary> /// <param name="collection">The grand parent <see cref="E03_SubContinentColl"/> collection.</param> internal void LoadItems(E03_SubContinentColl collection) { foreach (var item in this) { var obj = collection.FindE04_SubContinentByParentProperties(item.parent_SubContinent_ID); var rlce = obj.E05_CountryObjects.RaiseListChangedEvents; obj.E05_CountryObjects.RaiseListChangedEvents = false; obj.E05_CountryObjects.Add(item); obj.E05_CountryObjects.RaiseListChangedEvents = rlce; } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Cryptography; using Microsoft.AspNetCore.Cryptography.Cng; using Microsoft.AspNetCore.Cryptography.SafeHandles; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption; using Microsoft.AspNetCore.DataProtection.Cng.Internal; using Microsoft.AspNetCore.DataProtection.SP800_108; namespace Microsoft.AspNetCore.DataProtection.Cng { // GCM is defined in NIST SP 800-38D (http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf). // Heed closely the uniqueness requirements called out in Sec. 8: the probability that the GCM encryption // routine is ever invoked on two or more distinct sets of input data with the same (key, IV) shall not // exceed 2^-32. If we fix the key and use a random 96-bit IV for each invocation, this means that after // 2^32 encryption operations the odds of reusing any (key, IV) pair is 2^-32 (see Sec. 8.3). This won't // work for our use since a high-traffic web server can go through 2^32 requests in mere days. Instead, // we'll use 224 bits of entropy for each operation, with 128 bits going to the KDF and 96 bits // going to the IV. This means that we'll only hit the 2^-32 probability limit after 2^96 encryption // operations, which will realistically never happen. (At the absurd rate of one encryption operation // per nanosecond, it would still take 180 times the age of the universe to hit 2^96 operations.) internal sealed unsafe class CngGcmAuthenticatedEncryptor : CngAuthenticatedEncryptorBase { // Having a key modifier ensures with overwhelming probability that no two encryption operations // will ever derive the same (encryption subkey, MAC subkey) pair. This limits an attacker's // ability to mount a key-dependent chosen ciphertext attack. See also the class-level comment // for how this is used to overcome GCM's IV limitations. private const uint KEY_MODIFIER_SIZE_IN_BYTES = 128 / 8; private const uint NONCE_SIZE_IN_BYTES = 96 / 8; // GCM has a fixed 96-bit IV private const uint TAG_SIZE_IN_BYTES = 128 / 8; // we're hardcoding a 128-bit authentication tag size private readonly byte[] _contextHeader; private readonly IBCryptGenRandom _genRandom; private readonly ISP800_108_CTR_HMACSHA512Provider _sp800_108_ctr_hmac_provider; private readonly BCryptAlgorithmHandle _symmetricAlgorithmHandle; private readonly uint _symmetricAlgorithmSubkeyLengthInBytes; public CngGcmAuthenticatedEncryptor(Secret keyDerivationKey, BCryptAlgorithmHandle symmetricAlgorithmHandle, uint symmetricAlgorithmKeySizeInBytes, IBCryptGenRandom? genRandom = null) { // Is the key size appropriate? AlgorithmAssert.IsAllowableSymmetricAlgorithmKeySize(checked(symmetricAlgorithmKeySizeInBytes * 8)); CryptoUtil.Assert(symmetricAlgorithmHandle.GetCipherBlockLength() == 128 / 8, "GCM requires a block cipher algorithm with a 128-bit block size."); _genRandom = genRandom ?? BCryptGenRandomImpl.Instance; _sp800_108_ctr_hmac_provider = SP800_108_CTR_HMACSHA512Util.CreateProvider(keyDerivationKey); _symmetricAlgorithmHandle = symmetricAlgorithmHandle; _symmetricAlgorithmSubkeyLengthInBytes = symmetricAlgorithmKeySizeInBytes; _contextHeader = CreateContextHeader(); } private byte[] CreateContextHeader() { var retVal = new byte[checked( 1 /* KDF alg */ + 1 /* chaining mode */ + sizeof(uint) /* sym alg key size */ + sizeof(uint) /* GCM nonce size */ + sizeof(uint) /* sym alg block size */ + sizeof(uint) /* GCM tag size */ + TAG_SIZE_IN_BYTES /* tag of GCM-encrypted empty string */)]; fixed (byte* pbRetVal = retVal) { byte* ptr = pbRetVal; // First is the two-byte header *(ptr++) = 0; // 0x00 = SP800-108 CTR KDF w/ HMACSHA512 PRF *(ptr++) = 1; // 0x01 = GCM encryption + authentication // Next is information about the symmetric algorithm (key size, nonce size, block size, tag size) BitHelpers.WriteTo(ref ptr, _symmetricAlgorithmSubkeyLengthInBytes); BitHelpers.WriteTo(ref ptr, NONCE_SIZE_IN_BYTES); BitHelpers.WriteTo(ref ptr, TAG_SIZE_IN_BYTES); // block size = tag size BitHelpers.WriteTo(ref ptr, TAG_SIZE_IN_BYTES); // See the design document for an explanation of the following code. var tempKeys = new byte[_symmetricAlgorithmSubkeyLengthInBytes]; fixed (byte* pbTempKeys = tempKeys) { byte dummy; // Derive temporary key for encryption. using (var provider = SP800_108_CTR_HMACSHA512Util.CreateEmptyProvider()) { provider.DeriveKey( pbLabel: &dummy, cbLabel: 0, pbContext: &dummy, cbContext: 0, pbDerivedKey: pbTempKeys, cbDerivedKey: (uint)tempKeys.Length); } // Encrypt a zero-length input string with an all-zero nonce and copy the tag to the return buffer. byte* pbNonce = stackalloc byte[(int)NONCE_SIZE_IN_BYTES]; UnsafeBufferUtil.SecureZeroMemory(pbNonce, NONCE_SIZE_IN_BYTES); DoGcmEncrypt( pbKey: pbTempKeys, cbKey: _symmetricAlgorithmSubkeyLengthInBytes, pbNonce: pbNonce, pbPlaintextData: &dummy, cbPlaintextData: 0, pbEncryptedData: &dummy, pbTag: ptr); } ptr += TAG_SIZE_IN_BYTES; CryptoUtil.Assert(ptr - pbRetVal == retVal.Length, "ptr - pbRetVal == retVal.Length"); } // retVal := { version || chainingMode || symAlgKeySize || nonceSize || symAlgBlockSize || symAlgTagSize || TAG-of-E("") }. return retVal; } protected override byte[] DecryptImpl(byte* pbCiphertext, uint cbCiphertext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData) { // Argument checking: input must at the absolute minimum contain a key modifier, nonce, and tag if (cbCiphertext < KEY_MODIFIER_SIZE_IN_BYTES + NONCE_SIZE_IN_BYTES + TAG_SIZE_IN_BYTES) { throw Error.CryptCommon_PayloadInvalid(); } // Assumption: pbCipherText := { keyModifier || nonce || encryptedData || authenticationTag } var cbPlaintext = checked(cbCiphertext - (KEY_MODIFIER_SIZE_IN_BYTES + NONCE_SIZE_IN_BYTES + TAG_SIZE_IN_BYTES)); var retVal = new byte[cbPlaintext]; fixed (byte* pbRetVal = retVal) { // Calculate offsets byte* pbKeyModifier = pbCiphertext; byte* pbNonce = &pbKeyModifier[KEY_MODIFIER_SIZE_IN_BYTES]; byte* pbEncryptedData = &pbNonce[NONCE_SIZE_IN_BYTES]; byte* pbAuthTag = &pbEncryptedData[cbPlaintext]; // Use the KDF to recreate the symmetric block cipher key // We'll need a temporary buffer to hold the symmetric encryption subkey byte* pbSymmetricDecryptionSubkey = stackalloc byte[checked((int)_symmetricAlgorithmSubkeyLengthInBytes)]; try { _sp800_108_ctr_hmac_provider.DeriveKeyWithContextHeader( pbLabel: pbAdditionalAuthenticatedData, cbLabel: cbAdditionalAuthenticatedData, contextHeader: _contextHeader, pbContext: pbKeyModifier, cbContext: KEY_MODIFIER_SIZE_IN_BYTES, pbDerivedKey: pbSymmetricDecryptionSubkey, cbDerivedKey: _symmetricAlgorithmSubkeyLengthInBytes); // Perform the decryption operation using (var decryptionSubkeyHandle = _symmetricAlgorithmHandle.GenerateSymmetricKey(pbSymmetricDecryptionSubkey, _symmetricAlgorithmSubkeyLengthInBytes)) { byte dummy; byte* pbPlaintext = (pbRetVal != null) ? pbRetVal : &dummy; // CLR doesn't like pinning empty buffers BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authInfo; BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO.Init(out authInfo); authInfo.pbNonce = pbNonce; authInfo.cbNonce = NONCE_SIZE_IN_BYTES; authInfo.pbTag = pbAuthTag; authInfo.cbTag = TAG_SIZE_IN_BYTES; // The call to BCryptDecrypt will also validate the authentication tag uint cbDecryptedBytesWritten; var ntstatus = UnsafeNativeMethods.BCryptDecrypt( hKey: decryptionSubkeyHandle, pbInput: pbEncryptedData, cbInput: cbPlaintext, pPaddingInfo: &authInfo, pbIV: null, // IV not used; nonce provided in pPaddingInfo cbIV: 0, pbOutput: pbPlaintext, cbOutput: cbPlaintext, pcbResult: out cbDecryptedBytesWritten, dwFlags: 0); UnsafeNativeMethods.ThrowExceptionForBCryptStatus(ntstatus); CryptoUtil.Assert(cbDecryptedBytesWritten == cbPlaintext, "cbDecryptedBytesWritten == cbPlaintext"); // At this point, retVal := { decryptedPayload } // And we're done! return retVal; } } finally { // The buffer contains key material, so delete it. UnsafeBufferUtil.SecureZeroMemory(pbSymmetricDecryptionSubkey, _symmetricAlgorithmSubkeyLengthInBytes); } } } public override void Dispose() { _sp800_108_ctr_hmac_provider.Dispose(); // We don't want to dispose of the underlying algorithm instances because they // might be reused. } // 'pbNonce' must point to a 96-bit buffer. // 'pbTag' must point to a 128-bit buffer. // 'pbEncryptedData' must point to a buffer the same length as 'pbPlaintextData'. private void DoGcmEncrypt(byte* pbKey, uint cbKey, byte* pbNonce, byte* pbPlaintextData, uint cbPlaintextData, byte* pbEncryptedData, byte* pbTag) { BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authCipherInfo; BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO.Init(out authCipherInfo); authCipherInfo.pbNonce = pbNonce; authCipherInfo.cbNonce = NONCE_SIZE_IN_BYTES; authCipherInfo.pbTag = pbTag; authCipherInfo.cbTag = TAG_SIZE_IN_BYTES; using (var keyHandle = _symmetricAlgorithmHandle.GenerateSymmetricKey(pbKey, cbKey)) { uint cbResult; var ntstatus = UnsafeNativeMethods.BCryptEncrypt( hKey: keyHandle, pbInput: pbPlaintextData, cbInput: cbPlaintextData, pPaddingInfo: &authCipherInfo, pbIV: null, cbIV: 0, pbOutput: pbEncryptedData, cbOutput: cbPlaintextData, pcbResult: out cbResult, dwFlags: 0); UnsafeNativeMethods.ThrowExceptionForBCryptStatus(ntstatus); CryptoUtil.Assert(cbResult == cbPlaintextData, "cbResult == cbPlaintextData"); } } protected override byte[] EncryptImpl(byte* pbPlaintext, uint cbPlaintext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer) { // Allocate a buffer to hold the key modifier, nonce, encrypted data, and tag. // In GCM, the encrypted output will be the same length as the plaintext input. var retVal = new byte[checked(cbPreBuffer + KEY_MODIFIER_SIZE_IN_BYTES + NONCE_SIZE_IN_BYTES + cbPlaintext + TAG_SIZE_IN_BYTES + cbPostBuffer)]; fixed (byte* pbRetVal = retVal) { // Calculate offsets byte* pbKeyModifier = &pbRetVal[cbPreBuffer]; byte* pbNonce = &pbKeyModifier[KEY_MODIFIER_SIZE_IN_BYTES]; byte* pbEncryptedData = &pbNonce[NONCE_SIZE_IN_BYTES]; byte* pbAuthTag = &pbEncryptedData[cbPlaintext]; // Randomly generate the key modifier and nonce _genRandom.GenRandom(pbKeyModifier, KEY_MODIFIER_SIZE_IN_BYTES + NONCE_SIZE_IN_BYTES); // At this point, retVal := { preBuffer | keyModifier | nonce | _____ | _____ | postBuffer } // Use the KDF to generate a new symmetric block cipher key // We'll need a temporary buffer to hold the symmetric encryption subkey byte* pbSymmetricEncryptionSubkey = stackalloc byte[checked((int)_symmetricAlgorithmSubkeyLengthInBytes)]; try { _sp800_108_ctr_hmac_provider.DeriveKeyWithContextHeader( pbLabel: pbAdditionalAuthenticatedData, cbLabel: cbAdditionalAuthenticatedData, contextHeader: _contextHeader, pbContext: pbKeyModifier, cbContext: KEY_MODIFIER_SIZE_IN_BYTES, pbDerivedKey: pbSymmetricEncryptionSubkey, cbDerivedKey: _symmetricAlgorithmSubkeyLengthInBytes); // Perform the encryption operation DoGcmEncrypt( pbKey: pbSymmetricEncryptionSubkey, cbKey: _symmetricAlgorithmSubkeyLengthInBytes, pbNonce: pbNonce, pbPlaintextData: pbPlaintext, cbPlaintextData: cbPlaintext, pbEncryptedData: pbEncryptedData, pbTag: pbAuthTag); // At this point, retVal := { preBuffer | keyModifier | nonce | encryptedData | authenticationTag | postBuffer } // And we're done! return retVal; } finally { // The buffer contains key material, so delete it. UnsafeBufferUtil.SecureZeroMemory(pbSymmetricEncryptionSubkey, _symmetricAlgorithmSubkeyLengthInBytes); } } } } }
// 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.Diagnostics; using System.Collections.Generic; using Xunit; #pragma warning disable 0649 // Yes, we know - test class have fields we don't assign to. namespace System.Reflection.Tests { public static class MemberInfoNetCoreAppTests { [Fact] public static void HasSameMetadataDefinitionAs_GenericClassMembers() { Type tGeneric = typeof(GenericTestClass<>); IEnumerable<MethodInfo> methodsOnGeneric = tGeneric.GetTypeInfo().GetDeclaredMethods(nameof(GenericTestClass<object>.Foo)); List<Type> typeInsts = new List<Type>(); foreach (MethodInfo method in methodsOnGeneric) { Debug.Assert(method.GetParameters().Length == 1); Type parameterType = method.GetParameters()[0].ParameterType; typeInsts.Add(tGeneric.MakeGenericType(parameterType)); } typeInsts.Add(tGeneric); CrossTestHasSameMethodDefinitionAs(typeInsts.ToArray()); } private static void CrossTestHasSameMethodDefinitionAs(params Type[] types) { Assert.All(types, delegate (Type type1) { Assert.All(type1.GenerateTestMemberList(), delegate (MemberInfo m1) { MarkerAttribute mark1 = m1.GetCustomAttribute<MarkerAttribute>(); if (mark1 == null) return; Assert.All(types, delegate (Type type2) { Assert.All(type2.GenerateTestMemberList(), delegate (MemberInfo m2) { MarkerAttribute mark2 = m2.GetCustomAttribute<MarkerAttribute>(); if (mark2 == null) return; bool hasSameMetadata = m1.HasSameMetadataDefinitionAs(m2); Assert.Equal(hasSameMetadata, m2.HasSameMetadataDefinitionAs(m1)); if (hasSameMetadata) { Assert.Equal(mark1.Mark, mark2.Mark); } else { Assert.NotEqual(mark1.Mark, mark2.Mark); } } ); } ); } ); } ); } [Fact] public static void HasSameMetadataDefinitionAs_ReflectedTypeNotPartOfComparison() { Type tBase = typeof(GenericTestClass<>); Type tDerived = typeof(DerivedFromGenericTestClass<int>); BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; IEnumerable<MemberInfo> baseMembers = tBase.GetMembers(bf).Where(m => m.IsDefined(typeof(MarkerAttribute))); baseMembers = baseMembers.Where(bm => !(bm is ConstructorInfo)); // Constructors cannot be seen from derived types. IEnumerable<MemberInfo> derivedMembers = tDerived.GetMembers(bf).Where(m => m.IsDefined(typeof(MarkerAttribute))); Assert.All(baseMembers, delegate (MemberInfo baseMember) { MemberInfo matchingDerivedMember = derivedMembers.Single(dm => dm.HasSameMarkAs(baseMember)); Assert.True(baseMember.HasSameMetadataDefinitionAs(matchingDerivedMember)); Assert.True(matchingDerivedMember.HasSameMetadataDefinitionAs(matchingDerivedMember)); } ); } [Fact] public static void HasSameMetadataDefinitionAs_ConstructedGenericMethods() { Type t1 = typeof(TestClassWithGenericMethod<>); Type theT = t1.GetTypeInfo().GenericTypeParameters[0]; MethodInfo mooNormal = t1.GetConfirmedMethod(nameof(TestClassWithGenericMethod<object>.Moo), theT); MethodInfo mooGeneric = t1.GetTypeInfo().GetDeclaredMethods("Moo").Single(m => m.IsGenericMethod); MethodInfo mooInst = mooGeneric.MakeGenericMethod(typeof(int)); Assert.True(mooGeneric.HasSameMetadataDefinitionAs(mooInst)); Assert.True(mooInst.HasSameMetadataDefinitionAs(mooGeneric)); MethodInfo mooInst2 = mooGeneric.MakeGenericMethod(typeof(double)); Assert.True(mooInst2.HasSameMetadataDefinitionAs(mooInst)); Assert.True(mooInst.HasSameMetadataDefinitionAs(mooInst2)); Type t2 = typeof(TestClassWithGenericMethod<int>); MethodInfo mooNormalOnT2 = t2.GetConfirmedMethod(nameof(TestClassWithGenericMethod<object>.Moo), typeof(int)); Assert.False(mooInst.HasSameMetadataDefinitionAs(mooNormalOnT2)); } [Fact] public static void HasSameMetadataDefinitionAs_NamedAndGenericTypes() { Type tnong = typeof(TestClass); Type tnong2 = typeof(TestClass2); Type tg = typeof(GenericTestClass<>); Type tginst1 = typeof(GenericTestClass<int>); Type tginst2 = typeof(GenericTestClass<string>); Assert.True(tnong.HasSameMetadataDefinitionAs(tnong)); Assert.True(tnong2.HasSameMetadataDefinitionAs(tnong2)); Assert.True(tg.HasSameMetadataDefinitionAs(tg)); Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst1)); Assert.True(tginst2.HasSameMetadataDefinitionAs(tginst2)); Assert.True(tg.HasSameMetadataDefinitionAs(tginst1)); Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst1)); Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst2)); Assert.False(tnong.HasSameMetadataDefinitionAs(tnong2)); Assert.False(tnong.HasSameMetadataDefinitionAs(tg)); Assert.False(tg.HasSameMetadataDefinitionAs(tnong)); Assert.False(tnong.HasSameMetadataDefinitionAs(tginst1)); Assert.False(tginst1.HasSameMetadataDefinitionAs(tnong)); } [Fact] public static void HasSameMetadataDefinitionAs_GenericTypeParameters() { Type theT = typeof(GenericTestClass<>).GetTypeInfo().GenericTypeParameters[0]; Type theT2 = typeof(TestClassWithGenericMethod<>).GetTypeInfo().GenericTypeParameters[0]; BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding; MethodInfo mooNong = theT2.GetMethod("Moo", bf, null, new Type[] { theT2 }, null); MethodInfo mooGeneric = typeof(TestClassWithGenericMethod<>).GetTypeInfo().GetDeclaredMethods("Moo").Single(m => m.IsGenericMethod); Type theM = mooGeneric.GetGenericArguments()[0]; Assert.True(theT.HasSameMetadataDefinitionAs(theT)); Assert.False(theT2.HasSameMetadataDefinitionAs(theT)); Assert.False(theT.HasSameMetadataDefinitionAs(theT2)); Assert.False(theM.HasSameMetadataDefinitionAs(theT)); Assert.False(theM.HasSameMetadataDefinitionAs(theT2)); Assert.False(theT2.HasSameMetadataDefinitionAs(theM)); Assert.False(theT.HasSameMetadataDefinitionAs(theM)); } [Fact] public static void HasSameMetadataDefinitionAs_Twins() { // This situation is particularly treacherous for CoreRT as the .Net Native toolchain can and does assign // the same native metadata tokens to identically structured members in unrelated types. Type twin1 = typeof(Twin1); Type twin2 = typeof(Twin2); Assert.All(twin1.GenerateTestMemberList(), delegate (MemberInfo m1) { Assert.All(twin2.GenerateTestMemberList(), delegate (MemberInfo m2) { Assert.False(m1.HasSameMetadataDefinitionAs(m2)); } ); } ); } private class Twin1 { public Twin1() { } public int Field1; public Action Event1; public void Method1() { } public int Property1 { get; set; } } private class Twin2 { public Twin2() { } public int Field1; public Action Event1; public void Method1() { } public int Property1 { get; set; } } [Fact] [OuterLoop] // Time-consuming. public static void HasSameMetadataDefinitionAs_CrossAssembly() { // Make sure that identical tokens in different assemblies don't confuse the api. foreach (Type t1 in typeof(object).Assembly.DefinedTypes) { foreach (Type t2 in typeof(MemberInfoNetCoreAppTests).Assembly.DefinedTypes) { Assert.False(t1.HasSameMetadataDefinitionAs(t2)); } } } [Theory] [MemberData(nameof(NegativeTypeData))] public static void HasSameMetadataDefinitionAs_Negative_NonRuntimeType(Type type) { Type mockType = new MockType(); Assert.False(type.HasSameMetadataDefinitionAs(mockType)); Assert.All(type.GenerateTestMemberList(), delegate (MemberInfo member) { Assert.False(member.HasSameMetadataDefinitionAs(mockType)); } ); } [Theory] [MemberData(nameof(NegativeTypeData))] public static void HasSameMetadataDefinitionAs_Negative_Null(Type type) { AssertExtensions.Throws<ArgumentNullException>("other", () => type.HasSameMetadataDefinitionAs(null)); Assert.All(type.GenerateTestMemberList(), delegate (MemberInfo member) { AssertExtensions.Throws<ArgumentNullException>("other", () => member.HasSameMetadataDefinitionAs(null)); } ); } public static IEnumerable<object[]> NegativeTypeData => NegativeTypeDataRaw.Select(t => new object[] { t }); private static IEnumerable<Type> NegativeTypeDataRaw { get { yield return typeof(TestClass); yield return typeof(GenericTestClass<>); yield return typeof(GenericTestClass<int>); yield return typeof(int[]); yield return typeof(int).MakeArrayType(1); yield return typeof(int[,]); yield return typeof(int).MakeByRefType(); yield return typeof(int).MakePointerType(); yield return typeof(GenericTestClass<>).GetTypeInfo().GenericTypeParameters[0]; if (PlatformDetection.IsWindows) yield return Type.GetTypeFromCLSID(new Guid("DCA66D18-E253-4695-9E08-35B54420AFA2")); } } [Fact] public static void HasSameMetadataDefinitionAs__CornerCase_HasElementTypes() { // HasSameMetadataDefinitionAs on a array/byref/pointer type is uninteresting (they'll never be an actual member of a type) // but for future compat, we'll establish their known behavior here. Since these types all return a MetadataToken of 0x02000000, // they'll all "match" each other. Type[] types = { typeof(int[]), typeof(double[]), typeof(int).MakeArrayType(1), typeof(double).MakeArrayType(1), typeof(int[,]), typeof(double[,]), typeof(int).MakeByRefType(), typeof(double).MakeByRefType(), typeof(int).MakePointerType(), typeof(double).MakePointerType(), }; Assert.All(types, delegate (Type t1) { Assert.All(types, t2 => Assert.True(t1.HasSameMetadataDefinitionAs(t2))); } ); } [Fact] public static void HasSameMetadataDefinitionAs_CornerCase_ArrayMethods() { // The magic methods and constructors exposed on array types do not have metadata backing and report a MetadataToken of 0x06000000 // and hence compare identically with each other. This may be surprising but this test records that fact for future compat. // Type[] arrayTypes = { typeof(int[]), typeof(double[]), typeof(int).MakeArrayType(1), typeof(double).MakeArrayType(1), typeof(int[,]), typeof(double[,]), }; List<MemberInfo> members = new List<MemberInfo>(); foreach (Type arrayType in arrayTypes) { foreach (MemberInfo member in arrayType.GetMembers(BindingFlags.Public|BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if (member is MethodBase) { members.Add(member); } } } Assert.All(members, delegate (MemberInfo member1) { Assert.All(members, delegate (MemberInfo member2) { if (member1.MemberType == member2.MemberType) Assert.True(member1.HasSameMetadataDefinitionAs(member2)); else Assert.False(member1.HasSameMetadataDefinitionAs(member2)); } ); } ); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsWindows))] public static void HasSameMetadataDefinitionAs_CornerCase_CLSIDConstructor() { // HasSameMetadataDefinitionAs on a GetTypeFromCLSID type is uninteresting (they'll never be an actual member of a type) // but for future compat, we'll establish their known behavior here. Since these types and their constructors all return the same // MetadataToken, they'll all "match" each other. Type t1 = Type.GetTypeFromCLSID(new Guid("23A54889-7738-4F16-8AB2-CB23F8E756BE")); Type t2 = Type.GetTypeFromCLSID(new Guid("DCA66D18-E253-4695-9E08-35B54420AFA2")); Assert.True(t1.HasSameMetadataDefinitionAs(t2)); ConstructorInfo c1 = t1.GetConfirmedConstructor(); ConstructorInfo c2 = t2.GetConfirmedConstructor(); Assert.True(c1.HasSameMetadataDefinitionAs(c2)); } private static bool HasSameMarkAs(this MemberInfo m1, MemberInfo m2) { MarkerAttribute marker1 = m1.GetCustomAttribute<MarkerAttribute>(); Assert.NotNull(marker1); MarkerAttribute marker2 = m2.GetCustomAttribute<MarkerAttribute>(); Assert.NotNull(marker2); return marker1.Mark == marker2.Mark; } private static MethodInfo GetConfirmedMethod(this Type t, string name, params Type[] parameterTypes) { BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.ExactBinding; MethodInfo method = t.GetMethod(name, bf, null, parameterTypes, null); Assert.NotNull(method); return method; } private static ConstructorInfo GetConfirmedConstructor(this Type t, params Type[] parameterTypes) { BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.ExactBinding; ConstructorInfo ctor = t.GetConstructor(bf, null, parameterTypes, null); Assert.NotNull(ctor); return ctor; } private static IEnumerable<MemberInfo> GenerateTestMemberList(this Type t) { if (t.IsGenericTypeDefinition) { foreach (Type gp in t.GetTypeInfo().GenericTypeParameters) { yield return gp; } } foreach (MemberInfo m in t.GetTypeInfo().DeclaredMembers) { yield return m; MethodInfo method = m as MethodInfo; if (method != null && method.IsGenericMethodDefinition) { foreach (Type mgp in method.GetGenericArguments()) { yield return mgp; } yield return method.MakeGenericMethod(method.GetGenericArguments().Select(ga => typeof(object)).ToArray()); } } } private class TestClassWithGenericMethod<T> { public void Moo(T t) { } public void Moo<M>(M m) { } } private class TestClass { public void Foo() { } public void Foo(object o) { } public void Foo(string s) { } public void Bar() { } } private class TestClass2 { } private class GenericTestClass<T> { [Marker(1)] public void Foo(object o) { } [Marker(2)] public void Foo(int i) { } [Marker(3)] public void Foo(T t) { } [Marker(4)] public void Foo(double d) { } [Marker(5)] public void Foo(string s) { } [Marker(6)] public void Foo(int[] s) { } [Marker(7)] public void Foo<U>(U t) { } [Marker(8)] public void Foo<U>(T t) { } [Marker(9)] public void Foo<U, V>(T t) { } [Marker(101)] public GenericTestClass() { } [Marker(102)] public GenericTestClass(T t) { } [Marker(103)] public GenericTestClass(int t) { } [Marker(201)] public int Field1; [Marker(202)] public int Field2; [Marker(203)] public T Field3; [Marker(301)] public int Property1 { get { throw null; } set { throw null; } } [Marker(302)] public int Property2 { get { throw null; } set { throw null; } } [Marker(303)] public T Property3 { get { throw null; } set { throw null; } } [Marker(401)] public event Action Event1 { add { } remove { } } [Marker(402)] public event Action<int> Event2 { add { } remove { } } [Marker(403)] public event Action<T> Event3 { add { } remove { } } } private class DerivedFromGenericTestClass<T> : GenericTestClass<T> { } [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class MarkerAttribute : Attribute { public MarkerAttribute(int mark) { Mark = mark; } public readonly int Mark; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel.Channels { /// <summary> /// This class is based on BufferedStream from the Desktop version of .Net. Only the write functionality /// is needed by WCF so the read capability has been removed. This allowed some extra logic to be removed /// from the write code path. Also some validation code has been removed as this class is no longer /// general purpose and is only used in pre-known scenarios and only called by WCF code. Some validation /// checks have been converted to only run on a debug build to allow catching code bugs in other WCF code, /// but not causing release build overhead. /// /// One of the design goals here is to prevent the buffer from getting in the way and slowing /// down underlying stream accesses when it is not needed. /// See a large comment in Write for the details of the write buffer heuristic. /// /// This class will never cache more bytes than the max specified buffer size. /// However, it may use a temporary buffer of up to twice the size in order to combine several IO operations on /// the underlying stream into a single operation. This is because we assume that memory copies are significantly /// faster than IO operations on the underlying stream (if this was not true, using buffering is never appropriate). /// The max size of this "shadow" buffer is limited as to not allocate it on the LOH. /// Shadowing is always transient. Even when using this technique, this class still guarantees that the number of /// bytes cached (not yet written to the target stream or not yet consumed by the user) is never larger than the /// actual specified buffer size. /// </summary> internal sealed class BufferedWriteStream : Stream { public const int DefaultBufferSize = 4096; private Stream _stream; // Underlying stream. Close sets _stream to null. private byte[] _buffer; // Wwrite buffer. private readonly int _bufferSize; // Length of internal buffer (not counting the shadow buffer). private int _writePos; // Write pointer within buffer. private readonly SemaphoreSlim _sem = new SemaphoreSlim(1, 1); public BufferedWriteStream(Stream stream) : this(stream, DefaultBufferSize) { } public BufferedWriteStream(Stream stream, int bufferSize) { Contract.Assert(stream != Null, "stream!=Null"); Contract.Assert(bufferSize > 0, "bufferSize>0"); Contract.Assert(stream.CanWrite); _stream = stream; _bufferSize = bufferSize; EnsureBufferAllocated(); } private void EnsureNotClosed() { if (_stream == null) throw new ObjectDisposedException("BufferedWriteStream"); } private void EnsureCanWrite() { Contract.Requires(_stream != null); if (!_stream.CanWrite) throw new NotSupportedException("write"); } /// <summary><code>MaxShadowBufferSize</code> is chosen such that shadow buffers are not allocated on the Large Object Heap. /// Currently, an object is allocated on the LOH if it is larger than 85000 bytes. /// We will go with exactly 80 KBytes, although this is somewhat arbitrary.</summary> private const int MaxShadowBufferSize = 81920; // Make sure not to get to the Large Object Heap. private void EnsureShadowBufferAllocated() { Contract.Assert(_buffer != null); Contract.Assert(_bufferSize > 0); // Already have shadow buffer? if (_buffer.Length != _bufferSize || _bufferSize >= MaxShadowBufferSize) { return; } byte[] shadowBuffer = new byte[Math.Min(_bufferSize + _bufferSize, MaxShadowBufferSize)]; Array.Copy(_buffer, 0, shadowBuffer, 0, _writePos); _buffer = shadowBuffer; } private void EnsureBufferAllocated() { if (_buffer == null) _buffer = new byte[_bufferSize]; } public override bool CanRead { get { return false; } } public override bool CanWrite { get { return _stream != null && _stream.CanWrite; } } public override bool CanSeek { get { return false; } } public override long Length { get { throw new NotSupportedException("Position"); } } public override long Position { get { throw new NotSupportedException("Position"); } set { throw new NotSupportedException("Position"); } } protected override void Dispose(bool disposing) { try { if (disposing && _stream != null) { try { Flush(); } finally { _stream.Dispose(); } } } finally { _stream = null; _buffer = null; // Call base.Dispose(bool) to cleanup async IO resources base.Dispose(disposing); } } public override void Flush() { EnsureNotClosed(); // Has WRITE data in the buffer: if (_writePos > 0) { FlushWrite(); Contract.Assert(_writePos == 0); return; } // We had no data in the buffer, but we still need to tell the underlying stream to flush. _stream.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } EnsureNotClosed(); return FlushAsyncInternal(cancellationToken); } private async Task FlushAsyncInternal(CancellationToken cancellationToken) { await _sem.WaitAsync().ConfigureAwait(false); try { if (_writePos > 0) { await FlushWriteAsync(cancellationToken).ConfigureAwait(false); Contract.Assert(_writePos == 0); return; } // We had no data in the buffer, but we still need to tell the underlying stream to flush. await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); // There was nothing in the buffer: Contract.Assert(_writePos == 0); } finally { _sem.Release(); } } private void FlushWrite() { Contract.Assert(_buffer != null && _bufferSize >= _writePos, "BufferedWriteStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!"); _stream.Write(_buffer, 0, _writePos); _writePos = 0; _stream.Flush(); } private async Task FlushWriteAsync(CancellationToken cancellationToken) { Contract.Assert(_buffer != null && _bufferSize >= _writePos, "BufferedWriteStream: Write buffer must be allocated and write position must be in the bounds of the buffer in FlushWrite!"); await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false); _writePos = 0; await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); } public override int Read([In, Out] byte[] array, int offset, int count) { throw new NotSupportedException("Read"); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { throw new NotSupportedException("ReadAsync"); } public override int ReadByte() { throw new NotSupportedException("ReadByte"); } private void WriteToBuffer(byte[] array, ref int offset, ref int count) { int bytesToWrite = Math.Min(_bufferSize - _writePos, count); if (bytesToWrite <= 0) { return; } Array.Copy(array, offset, _buffer, _writePos, bytesToWrite); _writePos += bytesToWrite; count -= bytesToWrite; offset += bytesToWrite; } private void WriteToBuffer(byte[] array, ref int offset, ref int count, out Exception error) { try { error = null; WriteToBuffer(array, ref offset, ref count); } catch (Exception ex) { error = ex; } } public override void Write(byte[] array, int offset, int count) { Contract.Assert(array != null); Contract.Assert(offset >= 0); Contract.Assert(count >= 0); Contract.Assert(count <= array.Length - offset); EnsureNotClosed(); EnsureCanWrite(); #region Write algorithm comment // We need to use the buffer, while avoiding unnecessary buffer usage / memory copies. // We ASSUME that memory copies are much cheaper than writes to the underlying stream, so if an extra copy is // guaranteed to reduce the number of writes, we prefer it. // We pick a simple strategy that makes degenerate cases rare if our assumptions are right. // // For every write, we use a simple heuristic (below) to decide whether to use the buffer. // The heuristic has the desirable property (*) that if the specified user data can fit into the currently available // buffer space without filling it up completely, the heuristic will always tell us to use the buffer. It will also // tell us to use the buffer in cases where the current write would fill the buffer, but the remaining data is small // enough such that subsequent operations can use the buffer again. // // Algorithm: // Determine whether or not to buffer according to the heuristic (below). // If we decided to use the buffer: // Copy as much user data as we can into the buffer. // If we consumed all data: We are finished. // Otherwise, write the buffer out. // Copy the rest of user data into the now cleared buffer (no need to write out the buffer again as the heuristic // will prevent it from being filled twice). // If we decided not to use the buffer: // Can the data already in the buffer and current user data be combines to a single write // by allocating a "shadow" buffer of up to twice the size of _bufferSize (up to a limit to avoid LOH)? // Yes, it can: // Allocate a larger "shadow" buffer and ensure the buffered data is moved there. // Copy user data to the shadow buffer. // Write shadow buffer to the underlying stream in a single operation. // No, it cannot (amount of data is still too large): // Write out any data possibly in the buffer. // Write out user data directly. // // Heuristic: // If the subsequent write operation that follows the current write operation will result in a write to the // underlying stream in case that we use the buffer in the current write, while it would not have if we avoided // using the buffer in the current write (by writing current user data to the underlying stream directly), then we // prefer to avoid using the buffer since the corresponding memory copy is wasted (it will not reduce the number // of writes to the underlying stream, which is what we are optimising for). // ASSUME that the next write will be for the same amount of bytes as the current write (most common case) and // determine if it will cause a write to the underlying stream. If the next write is actually larger, our heuristic // still yields the right behaviour, if the next write is actually smaller, we may making an unnecessary write to // the underlying stream. However, this can only occur if the current write is larger than half the buffer size and // we will recover after one iteration. // We have: // useBuffer = (_writePos + count + count < _bufferSize + _bufferSize) // // Example with _bufferSize = 20, _writePos = 6, count = 10: // // +---------------------------------------+---------------------------------------+ // | current buffer | next iteration's "future" buffer | // +---------------------------------------+---------------------------------------+ // |0| | | | | | | | | |1| | | | | | | | | |2| | | | | | | | | |3| | | | | | | | | | // |0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9| // +-----------+-------------------+-------------------+---------------------------+ // | _writePos | current count | assumed next count|avail buff after next write| // +-----------+-------------------+-------------------+---------------------------+ // // A nice property (*) of this heuristic is that it will always succeed if the user data completely fits into the // available buffer, i.e. if count < (_bufferSize - _writePos). #endregion Write algorithm comment Contract.Assert(_writePos < _bufferSize); int totalUserBytes; bool useBuffer; checked { // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early: totalUserBytes = _writePos + count; useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize)); } if (useBuffer) { WriteToBuffer(array, ref offset, ref count); if (_writePos < _bufferSize) { Contract.Assert(count == 0); return; } Contract.Assert(count >= 0); Contract.Assert(_writePos == _bufferSize); Contract.Assert(_buffer != null); _stream.Write(_buffer, 0, _writePos); _writePos = 0; WriteToBuffer(array, ref offset, ref count); Contract.Assert(count == 0); Contract.Assert(_writePos < _bufferSize); } else { // if (!useBuffer) // Write out the buffer if necessary. if (_writePos > 0) { Contract.Assert(_buffer != null); Contract.Assert(totalUserBytes >= _bufferSize); // Try avoiding extra write to underlying stream by combining previously buffered data with current user data: if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize) { EnsureShadowBufferAllocated(); Array.Copy(array, offset, _buffer, _writePos, count); _stream.Write(_buffer, 0, totalUserBytes); _writePos = 0; return; } _stream.Write(_buffer, 0, _writePos); _writePos = 0; } // Write out user data. _stream.Write(array, offset, count); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Contract.Assert(buffer != null); Contract.Assert(offset >= 0); Contract.Assert(count >= 0); Contract.Assert(count <= buffer.Length - offset); // Fast path check for cancellation already requested if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); EnsureNotClosed(); EnsureCanWrite(); // Try to satisfy the request from the buffer synchronously. But still need a sem-lock in case that another // Async IO Task accesses the buffer concurrently. If we fail to acquire the lock without waiting, make this // an Async operation. Task semaphoreLockTask = _sem.WaitAsync(); if (semaphoreLockTask.Status == TaskStatus.RanToCompletion) { bool completeSynchronously = true; try { Contract.Assert(_writePos < _bufferSize); // If the write completely fits into the buffer, we can complete synchronously: completeSynchronously = (count < _bufferSize - _writePos); if (completeSynchronously) { Exception error; WriteToBuffer(buffer, ref offset, ref count, out error); Contract.Assert(count == 0); return (error == null) ? Task.CompletedTask : Task.FromException(error); } } finally { if (completeSynchronously) { // if this is FALSE, we will be entering WriteToUnderlyingStreamAsync and releasing there. _sem.Release(); } } } // Delegate to the async implementation. return WriteToUnderlyingStreamAsync(buffer, offset, count, cancellationToken, semaphoreLockTask); } private async Task WriteToUnderlyingStreamAsync(byte[] array, int offset, int count, CancellationToken cancellationToken, Task semaphoreLockTask) { // (These should be Contract.Requires(..) but that method had some issues in async methods; using Assert(..) for now.) EnsureNotClosed(); EnsureCanWrite(); // See the LARGE COMMENT in Write(..) for the explanation of the write buffer algorithm. await semaphoreLockTask.ConfigureAwait(false); try { // The buffer might have been changed by another async task while we were waiting on the semaphore. // However, note that if we recalculate the sync completion condition to TRUE, then useBuffer will also be TRUE. int totalUserBytes; bool useBuffer; checked { // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early: totalUserBytes = _writePos + count; useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize)); } if (useBuffer) { WriteToBuffer(array, ref offset, ref count); if (_writePos < _bufferSize) { Contract.Assert(count == 0); return; } Contract.Assert(count >= 0); Contract.Assert(_writePos == _bufferSize); Contract.Assert(_buffer != null); await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false); _writePos = 0; WriteToBuffer(array, ref offset, ref count); Contract.Assert(count == 0); Contract.Assert(_writePos < _bufferSize); } else { // if (!useBuffer) // Write out the buffer if necessary. if (_writePos > 0) { Contract.Assert(_buffer != null); Contract.Assert(totalUserBytes >= _bufferSize); // Try avoiding extra write to underlying stream by combining previously buffered data with current user data: if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize) { EnsureShadowBufferAllocated(); Buffer.BlockCopy(array, offset, _buffer, _writePos, count); await _stream.WriteAsync(_buffer, 0, totalUserBytes, cancellationToken).ConfigureAwait(false); _writePos = 0; return; } await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false); _writePos = 0; } // Write out user data. await _stream.WriteAsync(array, offset, count, cancellationToken).ConfigureAwait(false); } } finally { _sem.Release(); } } public override void WriteByte(byte value) { EnsureNotClosed(); // We should not be flushing here, but only writing to the underlying stream, but previous version flushed, so we keep this. if (_writePos >= _bufferSize - 1) { FlushWrite(); } _buffer[_writePos++] = value; Contract.Assert(_writePos < _bufferSize); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("seek"); } public override void SetLength(long value) { throw new NotSupportedException("SetLength"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Web; using System.Web.Mvc; using System.Diagnostics.Contracts; using HyperSlackers.Bootstrap.Extensions; namespace HyperSlackers.Bootstrap { public class FontAwesomeIcon : Icon<FontAwesomeIcon> { readonly internal FontAwesomeIconType fontAwesomeIcon = FontAwesomeIconType.Undefined; internal FontAwesomeIconSize size = FontAwesomeIconSize.Default; internal FontAwesomeIconRotate rotation = FontAwesomeIconRotate.Default; internal TextColor color = TextColor.Default; internal bool fixedWidth = false; internal bool spin = false; internal bool pulse = false; internal bool border = false; internal bool listIcon = false; internal bool pullRight = false; internal bool pullLeft = false; internal bool inverse = false; public FontAwesomeIcon(FontAwesomeIconType icon) { fontAwesomeIcon = icon; } public FontAwesomeIcon(FontAwesomeIconType icon, bool inverse) { fontAwesomeIcon = icon; this.inverse = inverse; } public FontAwesomeIcon Size(FontAwesomeIconSize size) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.size = size; return this; } public FontAwesomeIcon Rotate(FontAwesomeIconRotate rotation) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.rotation = rotation; return this; } public FontAwesomeIcon Color(TextColor color) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.color = color; return this; } public FontAwesomeIcon FixedWidth(bool fixedWidth = true) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.fixedWidth = fixedWidth; return this; } public FontAwesomeIcon Spin(bool spin = true) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.spin = spin; return this; } public FontAwesomeIcon Pulse(bool pulse = true) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.pulse = pulse; return this; } public FontAwesomeIcon Inverse(bool inverse = true) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.inverse = inverse; return this; } public FontAwesomeIcon Border(bool border = true) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.border = border; return this; } public FontAwesomeIcon PullRight(bool pullRight = true) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.pullRight = pullRight; if (pullRight) { pullLeft = false; } return this; } public FontAwesomeIcon PullLeft(bool pullLeft = true) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); this.pullLeft = pullLeft; if (pullLeft) { pullRight = false; } return this; } public FontAwesomeIcon ListIcon(bool listIcon = true) { Contract.Ensures(Contract.Result<FontAwesomeIcon>() != null); // TODO: the UL needs a "fa-ul" class applied... this.listIcon = listIcon; return this; } [EditorBrowsable(EditorBrowsableState.Never)] public override string ToHtmlString() { Contract.Ensures(!Contract.Result<string>().IsNullOrWhiteSpace()); TagBuilder tagBuilder = new TagBuilder("i"); IDictionary<string, object> attributes = htmlAttributes.FormatHtmlAttributes(); if (tooltip != null) { attributes.AddOrReplaceHtmlAttributes(tooltip.ToDictionary()); } if (popover != null) { attributes.AddOrReplaceHtmlAttributes(popover.ToDictionary()); } tagBuilder.MergeHtmlAttributes(attributes); // font awesome classes tagBuilder.AddCssClass("fa"); tagBuilder.AddCssClass("fa-" + fontAwesomeIcon.ToString().SpaceOnUpperCase().ToLowerInvariant().Replace(" ", "-")); if (size != FontAwesomeIconSize.Default) { switch (size) { case FontAwesomeIconSize.Default: break; case FontAwesomeIconSize.Large: tagBuilder.AddCssClass("fa-lg"); break; case FontAwesomeIconSize.X2: tagBuilder.AddCssClass("fa-2x"); break; case FontAwesomeIconSize.X3: tagBuilder.AddCssClass("fa-3x"); break; case FontAwesomeIconSize.X4: tagBuilder.AddCssClass("fa-4x"); break; case FontAwesomeIconSize.X5: tagBuilder.AddCssClass("fa-5x"); break; default: break; } } if (rotation != FontAwesomeIconRotate.Default) { switch (rotation) { case FontAwesomeIconRotate.Default: break; case FontAwesomeIconRotate.Rotate90: tagBuilder.AddCssClass("fa-rotate-90"); break; case FontAwesomeIconRotate.Rotate180: tagBuilder.AddCssClass("fa-rotate-180"); break; case FontAwesomeIconRotate.Rotate270: tagBuilder.AddCssClass("fa-rotate-270"); break; case FontAwesomeIconRotate.FlipHorizontal: tagBuilder.AddCssClass("fa-flip-horizontal"); break; case FontAwesomeIconRotate.FlipVertical: tagBuilder.AddCssClass("fa-flip-vertical"); break; default: break; } } if (color != TextColor.Default) { tagBuilder.AddCssClass(Helpers.GetCssClass(color)); } if (fixedWidth) { tagBuilder.AddCssClass("fa-fw"); } if (listIcon) { tagBuilder.AddCssClass("fa-li"); } if (border) { tagBuilder.AddCssClass("fa-border"); } if (spin) { tagBuilder.AddCssClass("fa-spin"); } if (pulse) { tagBuilder.AddCssClass("fa-pulse"); } if (inverse) { tagBuilder.AddCssClass("fa-inverse"); } if (pullLeft) { tagBuilder.AddCssClass("pull-left"); } else if (pullRight) { tagBuilder.AddCssClass("pull-right"); } return tagBuilder.ToString(TagRenderMode.Normal); } [EditorBrowsable(EditorBrowsableState.Never)] public override string ToString() { return ToHtmlString(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { return Equals(obj); } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return GetHashCode(); } [EditorBrowsable(EditorBrowsableState.Never)] public new Type GetType() { return GetType(); } } }
using System; using System.Diagnostics; using System.Runtime.Serialization; using Hammock.Model; using Newtonsoft.Json; namespace TweetSharp { #if !SILVERLIGHT /// <summary> /// Represents a private <see cref="TwitterStatus" /> between two users. /// </summary> [Serializable] #endif #if !Smartphone && !NET20 [DataContract] [DebuggerDisplay("{SenderScreenName} to {RecipientScreenName}:{Text}")] #endif [JsonObject(MemberSerialization.OptIn)] public class TwitterDirectMessage : PropertyChangedBase, IComparable<TwitterDirectMessage>, IEquatable<TwitterDirectMessage>, ITwitterModel, ITweetable { private long _id; private string _idStr; private long _recipientId; private string _recipientScreenName; private TwitterUser _recipient; private long _senderId; private TwitterUser _sender; private string _senderScreenName; private string _text; private DateTime _createdDate; private TwitterEntities _entities; #if !Smartphone && !NET20 [DataMember] #endif public virtual long Id { get { return _id; } set { if (_id == value) { return; } _id = value; OnPropertyChanged("Id"); } } [JsonProperty("id_str")] #if !Smartphone && !NET20 [DataMember] #endif public virtual string IdStr { get { return _idStr; } set { if (_idStr == value) { return; } _idStr = value; OnPropertyChanged("IdStr"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual long RecipientId { get { return _recipientId; } set { if (_recipientId == value) { return; } _recipientId = value; OnPropertyChanged("RecipientId"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual string RecipientScreenName { get { return _recipientScreenName; } set { if (_recipientScreenName == value) { return; } _recipientScreenName = value; OnPropertyChanged("RecipientScreenName"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual TwitterUser Recipient { get { return _recipient; } set { if (_recipient == value) { return; } _recipient = value; OnPropertyChanged("Recipient"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual long SenderId { get { return _senderId; } set { if (_senderId == value) { return; } _senderId = value; OnPropertyChanged("SenderId"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual TwitterUser Sender { get { return _sender; } set { if (_sender == value) { return; } _sender = value; OnPropertyChanged("Sender"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual string SenderScreenName { get { return _senderScreenName; } set { if (_senderScreenName == value) { return; } _senderScreenName = value; OnPropertyChanged("SenderScreenName"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual string Text { get { return _text; } set { if (_text == value) { return; } _text = value; _entities = null; OnPropertyChanged("Text"); } } private string _textAsHtml; public virtual string TextAsHtml { get { return (_textAsHtml ?? (_textAsHtml = this.ParseTextWithEntities())); } set { _textAsHtml = value; OnPropertyChanged("TextAsHtml"); } } public ITweeter Author { get { return Sender; } } #if !Smartphone && !NET20 [DataMember] #endif [JsonProperty("created_at")] public virtual DateTime CreatedDate { get { return _createdDate; } set { if (_createdDate == value) { return; } _createdDate = value; OnPropertyChanged("CreatedDate"); } } #if !Smartphone && !NET20 [DataMember] #endif public virtual TwitterEntities Entities { get { return _entities ?? (Entities = Text.ParseTwitterageToEntities()); } set { if (_entities != null) { return; } _entities = value; OnPropertyChanged("Entities"); } } #region IComparable<TwitterDirectMessage> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <returns> /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. /// </returns> /// <param name="other">An object to compare with this object.</param> public int CompareTo(TwitterDirectMessage other) { return other.Id == Id ? 0 : other.Id > Id ? -1 : 1; } #endregion #region IEquatable<TwitterDirectMessage> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="obj">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="obj"/> parameter; otherwise, false. /// </returns> public bool Equals(TwitterDirectMessage obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.Id == Id; } #endregion /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == typeof (TwitterDirectMessage) && Equals((TwitterDirectMessage) obj); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return Id.GetHashCode(); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(TwitterDirectMessage left, TwitterDirectMessage right) { return Equals(left, right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(TwitterDirectMessage left, TwitterDirectMessage right) { return !Equals(left, right); } #if !Smartphone && !NET20 [DataMember] #endif public virtual string RawSource { get; set; } } }
namespace AjourBT.Domain.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.Employees", c => new { EmployeeID = c.Int(nullable: false, identity: true), FirstName = c.String(nullable: false), LastName = c.String(nullable: false), EID = c.String(nullable: false), DepartmentID = c.Int(nullable: false), DateEmployed = c.DateTime(nullable: false), PositionID = c.Int(nullable: false), BirthDay = c.DateTime(), Comment = c.String(), FullNameUk = c.String(), DateDismissed = c.DateTime(), IsManager = c.Boolean(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), BTRestrictions = c.String(), }) .PrimaryKey(t => t.EmployeeID) .ForeignKey("dbo.Departments", t => t.DepartmentID) .ForeignKey("dbo.Positions", t => t.PositionID, cascadeDelete: true) .Index(t => t.DepartmentID) .Index(t => t.PositionID); CreateTable( "dbo.Departments", c => new { DepartmentID = c.Int(nullable: false, identity: true), DepartmentName = c.String(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.DepartmentID); CreateTable( "dbo.Positions", c => new { PositionID = c.Int(nullable: false, identity: true), TitleUk = c.String(nullable: false), TitleEn = c.String(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.PositionID); CreateTable( "dbo.BusinessTrips", c => new { BusinessTripID = c.Int(nullable: false, identity: true), StartDate = c.DateTime(nullable: false), OldStartDate = c.DateTime(), EndDate = c.DateTime(nullable: false), OldEndDate = c.DateTime(), OrderStartDate = c.DateTime(), OrderEndDate = c.DateTime(), DaysInBtForOrder = c.Int(), Status = c.Int(nullable: false), LocationID = c.Int(nullable: false), OldLocationID = c.Int(nullable: false), OldLocationTitle = c.String(), EmployeeID = c.Int(nullable: false), Purpose = c.String(), Manager = c.String(), Responsible = c.String(), Comment = c.String(), RejectComment = c.String(), CancelComment = c.String(), BTMComment = c.String(), Habitation = c.String(), HabitationConfirmed = c.Boolean(nullable: false), Flights = c.String(), FlightsConfirmed = c.Boolean(nullable: false), Invitation = c.Boolean(nullable: false), LastCRUDedBy = c.String(), LastCRUDTimestamp = c.DateTime(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.BusinessTripID) .ForeignKey("dbo.Locations", t => t.LocationID) .ForeignKey("dbo.Employees", t => t.EmployeeID) .Index(t => t.LocationID) .Index(t => t.EmployeeID); CreateTable( "dbo.Locations", c => new { LocationID = c.Int(nullable: false, identity: true), Title = c.String(nullable: false), Address = c.String(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.LocationID); CreateTable( "dbo.Visas", c => new { EmployeeID = c.Int(nullable: false), VisaType = c.String(nullable: false), StartDate = c.DateTime(nullable: false), DueDate = c.DateTime(nullable: false), Days = c.Int(nullable: false), DaysUsedInBT = c.Int(), DaysUsedInPrivateTrips = c.Int(), Entries = c.Int(nullable: false), EntriesUsedInBT = c.Int(), EntriesUsedInPrivateTrips = c.Int(), CorrectionForVisaDays = c.Int(), CorrectionForVisaEntries = c.Int(), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.EmployeeID) .ForeignKey("dbo.Employees", t => t.EmployeeID) .Index(t => t.EmployeeID); CreateTable( "dbo.PrivateTrips", c => new { PrivateTripID = c.Int(nullable: false, identity: true), StartDate = c.DateTime(nullable: false), EndDate = c.DateTime(nullable: false), EmployeeID = c.Int(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.PrivateTripID) .ForeignKey("dbo.Visas", t => t.EmployeeID, cascadeDelete: true) .Index(t => t.EmployeeID); CreateTable( "dbo.VisaRegistrationDates", c => new { EmployeeID = c.Int(nullable: false), VisaType = c.String(nullable: false), RegistrationDate = c.DateTime(nullable: false), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.EmployeeID) .ForeignKey("dbo.Employees", t => t.EmployeeID) .Index(t => t.EmployeeID); CreateTable( "dbo.Permits", c => new { EmployeeID = c.Int(nullable: false), IsKartaPolaka = c.Boolean(nullable: false), Number = c.String(), StartDate = c.DateTime(), EndDate = c.DateTime(), CancelRequestDate = c.DateTime(), ProlongRequestDate = c.DateTime(), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.EmployeeID) .ForeignKey("dbo.Employees", t => t.EmployeeID) .Index(t => t.EmployeeID); CreateTable( "dbo.Passports", c => new { EmployeeID = c.Int(nullable: false), EndDate = c.DateTime(), RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"), }) .PrimaryKey(t => t.EmployeeID) .ForeignKey("dbo.Employees", t => t.EmployeeID) .Index(t => t.EmployeeID); CreateTable( "dbo.UserProfile", c => new { UserId = c.Int(nullable: false, identity: true), UserName = c.String(), }) .PrimaryKey(t => t.UserId); CreateTable( "dbo.Messages", c => new { MessageID = c.Int(nullable: false, identity: true), Role = c.String(), Subject = c.String(), Body = c.String(), Link = c.String(), TimeStamp = c.DateTime(nullable: false), ReplyTo = c.String(), }) .PrimaryKey(t => t.MessageID); } public override void Down() { DropIndex("dbo.Passports", new[] { "EmployeeID" }); DropIndex("dbo.Permits", new[] { "EmployeeID" }); DropIndex("dbo.VisaRegistrationDates", new[] { "EmployeeID" }); DropIndex("dbo.PrivateTrips", new[] { "EmployeeID" }); DropIndex("dbo.Visas", new[] { "EmployeeID" }); DropIndex("dbo.BusinessTrips", new[] { "EmployeeID" }); DropIndex("dbo.BusinessTrips", new[] { "LocationID" }); DropIndex("dbo.Employees", new[] { "PositionID" }); DropIndex("dbo.Employees", new[] { "DepartmentID" }); DropForeignKey("dbo.Passports", "EmployeeID", "dbo.Employees"); DropForeignKey("dbo.Permits", "EmployeeID", "dbo.Employees"); DropForeignKey("dbo.VisaRegistrationDates", "EmployeeID", "dbo.Employees"); DropForeignKey("dbo.PrivateTrips", "EmployeeID", "dbo.Visas"); DropForeignKey("dbo.Visas", "EmployeeID", "dbo.Employees"); DropForeignKey("dbo.BusinessTrips", "EmployeeID", "dbo.Employees"); DropForeignKey("dbo.BusinessTrips", "LocationID", "dbo.Locations"); DropForeignKey("dbo.Employees", "PositionID", "dbo.Positions"); DropForeignKey("dbo.Employees", "DepartmentID", "dbo.Departments"); DropTable("dbo.Messages"); DropTable("dbo.UserProfile"); DropTable("dbo.Passports"); DropTable("dbo.Permits"); DropTable("dbo.VisaRegistrationDates"); DropTable("dbo.PrivateTrips"); DropTable("dbo.Visas"); DropTable("dbo.Locations"); DropTable("dbo.BusinessTrips"); DropTable("dbo.Positions"); DropTable("dbo.Departments"); DropTable("dbo.Employees"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// A collection of <see cref="Note"/> exposed in the <see cref="Repository"/>. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class NoteCollection : IEnumerable<Note> { internal readonly Repository repo; private readonly Lazy<string> defaultNamespace; /// <summary> /// Needed for mocking purposes. /// </summary> protected NoteCollection() { } internal NoteCollection(Repository repo) { this.repo = repo; defaultNamespace = new Lazy<string>(RetrieveDefaultNamespace); } #region Implementation of IEnumerable /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns> public virtual IEnumerator<Note> GetEnumerator() { return this[DefaultNamespace].GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion /// <summary> /// The default namespace for notes. /// </summary> public virtual string DefaultNamespace { get { return defaultNamespace.Value; } } /// <summary> /// The list of canonicalized namespaces related to notes. /// </summary> public virtual IEnumerable<string> Namespaces { get { return NamespaceRefs.Select(UnCanonicalizeName); } } internal IEnumerable<string> NamespaceRefs { get { return new[] { NormalizeToCanonicalName(DefaultNamespace) }.Concat(repo.Refs .Select(reference => reference.CanonicalName) .Where(refCanonical => refCanonical.StartsWith(Reference.NotePrefix, StringComparison.Ordinal) && refCanonical != NormalizeToCanonicalName(DefaultNamespace))); } } /// <summary> /// Gets the collection of <see cref="Note"/> associated with the specified <see cref="ObjectId"/>. /// </summary> public virtual IEnumerable<Note> this[ObjectId id] { get { Ensure.ArgumentNotNull(id, "id"); return NamespaceRefs .Select(ns => this[ns, id]) .Where(n => n != null); } } /// <summary> /// Gets the collection of <see cref="Note"/> associated with the specified namespace. /// <para>This is similar to the 'get notes list' command.</para> /// </summary> public virtual IEnumerable<Note> this[string @namespace] { get { Ensure.ArgumentNotNull(@namespace, "@namespace"); string canonicalNamespace = NormalizeToCanonicalName(@namespace); return Proxy.git_note_foreach(repo.Handle, canonicalNamespace, (blobId,annotatedObjId) => this[canonicalNamespace, annotatedObjId]); } } /// <summary> /// Gets the <see cref="Note"/> associated with the specified objectId and the specified namespace. /// </summary> public virtual Note this[string @namespace, ObjectId id] { get { Ensure.ArgumentNotNull(id, "id"); Ensure.ArgumentNotNull(@namespace, "@namespace"); string canonicalNamespace = NormalizeToCanonicalName(@namespace); using (NoteSafeHandle noteHandle = Proxy.git_note_read(repo.Handle, canonicalNamespace, id)) { return noteHandle == null ? null : Note.BuildFromPtr(noteHandle, UnCanonicalizeName(canonicalNamespace), id); } } } private string RetrieveDefaultNamespace() { string notesRef = Proxy.git_note_default_ref(repo.Handle); return UnCanonicalizeName(notesRef); } internal static string NormalizeToCanonicalName(string name) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); if (name.LooksLikeNote()) { return name; } return string.Concat(Reference.NotePrefix, name); } internal static string UnCanonicalizeName(string name) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); if (!name.LooksLikeNote()) { return name; } return name.Substring(Reference.NotePrefix.Length); } /// <summary> /// Creates or updates a <see cref="Note"/> on the specified object, and for the given namespace. /// <para>Both the Author and Committer will be guessed from the Git configuration. An exception will be raised if no configuration is reachable.</para> /// </summary> /// <param name="targetId">The target <see cref="ObjectId"/>, for which the note will be created.</param> /// <param name="message">The note message.</param> /// <param name="namespace">The namespace on which the note will be created. It can be either a canonical namespace or an abbreviated namespace ('refs/notes/myNamespace' or just 'myNamespace').</param> /// <returns>The note which was just saved.</returns> public virtual Note Add(ObjectId targetId, string message, string @namespace) { Signature author = repo.Config.BuildSignature(DateTimeOffset.Now, true); return Add(targetId, message, author, author, @namespace); } /// <summary> /// Creates or updates a <see cref="Note"/> on the specified object, and for the given namespace. /// </summary> /// <param name="targetId">The target <see cref="ObjectId"/>, for which the note will be created.</param> /// <param name="message">The note message.</param> /// <param name="author">The author.</param> /// <param name="committer">The committer.</param> /// <param name="namespace">The namespace on which the note will be created. It can be either a canonical namespace or an abbreviated namespace ('refs/notes/myNamespace' or just 'myNamespace').</param> /// <returns>The note which was just saved.</returns> public virtual Note Add(ObjectId targetId, string message, Signature author, Signature committer, string @namespace) { Ensure.ArgumentNotNull(targetId, "targetId"); Ensure.ArgumentNotNullOrEmptyString(message, "message"); Ensure.ArgumentNotNull(author, "author"); Ensure.ArgumentNotNull(committer, "committer"); Ensure.ArgumentNotNullOrEmptyString(@namespace, "@namespace"); string canonicalNamespace = NormalizeToCanonicalName(@namespace); Remove(targetId, author, committer, @namespace); Proxy.git_note_create(repo.Handle, canonicalNamespace, author, committer, targetId, message, true); return this[canonicalNamespace, targetId]; } /// <summary> /// Deletes the note on the specified object, and for the given namespace. /// <para>Both the Author and Committer will be guessed from the Git configuration. An exception will be raised if no configuration is reachable.</para> /// </summary> /// <param name="targetId">The target <see cref="ObjectId"/>, for which the note will be created.</param> /// <param name="namespace">The namespace on which the note will be removed. It can be either a canonical namespace or an abbreviated namespace ('refs/notes/myNamespace' or just 'myNamespace').</param> public virtual void Remove(ObjectId targetId, string @namespace) { Signature author = repo.Config.BuildSignature(DateTimeOffset.Now, true); Remove(targetId, author, author, @namespace); } /// <summary> /// Deletes the note on the specified object, and for the given namespace. /// </summary> /// <param name="targetId">The target <see cref="ObjectId"/>, for which the note will be created.</param> /// <param name="author">The author.</param> /// <param name="committer">The committer.</param> /// <param name="namespace">The namespace on which the note will be removed. It can be either a canonical namespace or an abbreviated namespace ('refs/notes/myNamespace' or just 'myNamespace').</param> public virtual void Remove(ObjectId targetId, Signature author, Signature committer, string @namespace) { Ensure.ArgumentNotNull(targetId, "targetId"); Ensure.ArgumentNotNull(author, "author"); Ensure.ArgumentNotNull(committer, "committer"); Ensure.ArgumentNotNullOrEmptyString(@namespace, "@namespace"); string canonicalNamespace = NormalizeToCanonicalName(@namespace); Proxy.git_note_remove(repo.Handle, canonicalNamespace, author, committer, targetId); } private string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "Count = {0}", this.Count()); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract001.extract001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract001.extract001; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class B { public void Foo() { Test.Status = 2; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { List<dynamic> myList = new List<dynamic>() { new A(), new B()} ; int i = 1; foreach (var item in myList) { item.Foo(); if (i++ != Test.Status) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract002.extract002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract002.extract002; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class B { public void Foo() { Test.Status = 2; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { List<object> myList = new List<object>() { new A(), new B()} ; int i = 1; foreach (dynamic item in myList) { item.Foo(); if (i++ != Test.Status) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract003.extract003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract003.extract003; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class B { public void Foo() { Test.Status = 2; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { List<dynamic> myList = new List<object>() { new A(), new B()} ; int i = 1; foreach (var item in myList) { item.Foo(); if (i++ != Test.Status) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract004.extract004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract004.extract004; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class B { public void Foo() { Test.Status = 2; } } public class Foo { public List<dynamic> GetList() { return new List<dynamic>() { new A(), new B()} ; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); int i = 1; foreach (var item in f.GetList()) { item.Foo(); if (i++ != Test.Status) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract005.extract005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract005.extract005; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class B { public void Foo() { Test.Status = 2; } } public class Foo { public List<dynamic> GetList() { return new List<object>() { new A(), new B()} ; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); int i = 1; foreach (var item in f.GetList()) { item.Foo(); if (i++ != Test.Status) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract006.extract006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract006.extract006; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class B { public void Foo() { Test.Status = 2; } } public class Foo { public IEnumerable<dynamic> GetList() { return new List<dynamic>() { new A(), new B()} ; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); int i = 1; foreach (var item in f.GetList()) { item.Foo(); if (i++ != Test.Status) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract007.extract007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract007.extract007; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class B { public void Foo() { Test.Status = 2; } } public class Foo { public IEnumerable<dynamic> GetList() { return new List<object>() { new A(), new B()} ; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); int i = 1; foreach (var item in f.GetList()) { item.Foo(); if (i++ != Test.Status) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract008.extract008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract008.extract008; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class Foo { public List<Dictionary<string, List<dynamic>>> GetSomething() { var list = new List<Dictionary<string, List<dynamic>>>(); var dict = new Dictionary<string, List<dynamic>>(); dict.Add("Test", new List<dynamic>() { new A()} ); list.Add(dict); return list; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); var list = f.GetSomething(); list[0]["Test"][0].Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract009.extract009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract009.extract009; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class Foo { public List<Dictionary<string, List<dynamic>>> GetSomething() { var list = new List<Dictionary<string, List<object>>>(); var dict = new Dictionary<string, List<object>>(); dict.Add("Test", new List<object>() { new A()} ); list.Add(dict); return list; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); var list = f.GetSomething(); list[0]["Test"][0].Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract010.extract010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract010.extract010; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class B { public void Foo() { Test.Status = 2; } } public class Foo { public List<Dictionary<dynamic, Dictionary<string, List<dynamic>>>> GetSomething() { var list = new List<Dictionary<dynamic, Dictionary<string, List<dynamic>>>>(); var dict = new Dictionary<dynamic, Dictionary<string, List<dynamic>>>(); var dict2 = new Dictionary<string, List<dynamic>>(); list.Add(dict); dict.Add("bar", dict2); dict2.Add("foo", new List<dynamic>() { new A(), new B()} ); return list; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); var list = f.GetSomething(); list[0]["bar"]["foo"][0].Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract011.extract011 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.extractDynamic.extract011.extract011; // <Title>Extract a dynamic element from a generic type</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class A { public void Foo() { Test.Status = 1; } } public class B { public void Foo() { Test.Status = 2; } } public class C<T> { public T t; public T getT() { return t; } public void Add(T tt) { t = tt; } } public class D<T, U> { public T t; public U u; public T getT() { return t; } public U getU() { return u; } public void Add(T tt, U uu) { t = tt; u = uu; } } public class Foo { public C<D<dynamic, D<string, C<dynamic>>>> Get() { var list = new C<D<dynamic, D<string, C<dynamic>>>>(); var dict = new D<dynamic, D<string, C<dynamic>>>(); var dict2 = new D<string, C<dynamic>>(); var test = new C<dynamic>(); test.Add(new A()); list.Add(dict); dict.Add("bar", dict2); dict2.Add("foo", test); return list; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); var list = f.Get(); list.getT().getU().getU().getT().Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Globalization; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data. /// </summary> public abstract class JsonReader : IDisposable { /// <summary> /// Specifies the state of the reader. /// </summary> protected internal enum State { /// <summary> /// The Read method has not been called. /// </summary> Start, /// <summary> /// The end of the file has been reached successfully. /// </summary> Complete, /// <summary> /// Reader is at a property. /// </summary> Property, /// <summary> /// Reader is at the start of an object. /// </summary> ObjectStart, /// <summary> /// Reader is in an object. /// </summary> Object, /// <summary> /// Reader is at the start of an array. /// </summary> ArrayStart, /// <summary> /// Reader is in an array. /// </summary> Array, /// <summary> /// The Close method has been called. /// </summary> Closed, /// <summary> /// Reader has just read a value. /// </summary> PostValue, /// <summary> /// Reader is at the start of a constructor. /// </summary> ConstructorStart, /// <summary> /// Reader in a constructor. /// </summary> Constructor, /// <summary> /// An error occurred that prevents the read operation from continuing. /// </summary> Error, /// <summary> /// The end of the file has been reached successfully. /// </summary> Finished } // current Token data private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; internal ReadType _readType; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string _dateFormatString; private readonly List<JsonPosition> _stack; /// <summary> /// Gets the current reader state. /// </summary> /// <value>The current reader state.</value> protected State CurrentState { get { return _currentState; } } /// <summary> /// Gets or sets a value indicating whether the underlying stream or /// <see cref="TextReader"/> should be closed when the reader is closed. /// </summary> /// <value> /// true to close the underlying stream or <see cref="TextReader"/> when /// the reader is closed; otherwise false. The default is true. /// </value> public bool CloseInput { get; set; } /// <summary> /// Gets or sets a value indicating whether multiple pieces of JSON content can /// be read from a continuous stream without erroring. /// </summary> /// <value> /// true to support reading multiple pieces of JSON content; otherwise false. The default is false. /// </value> public bool SupportMultipleContent { get; set; } /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { _floatParseHandling = value; } } /// <summary> /// Get or set how custom date formatted strings are parsed when reading JSON. /// </summary> public string DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) throw new ArgumentException("Value must be positive.", "value"); _maxDepth = value; } } /// <summary> /// Gets the type of the current JSON token. /// </summary> public virtual JsonToken TokenType { get { return _tokenType; } } /// <summary> /// Gets the text value of the current JSON token. /// </summary> public virtual object Value { get { return _value; } } /// <summary> /// Gets The Common Language Runtime (CLR) type for the current JSON token. /// </summary> public virtual Type ValueType { get { return (_value != null) ? _value.GetType() : null; } } /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public virtual int Depth { get { int depth = _stack.Count; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) return depth; else return depth + 1; } } /// <summary> /// Gets the path of the current JSON token. /// </summary> public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) return string.Empty; bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); IEnumerable<JsonPosition> positions = (!insideContainer) ? _stack : _stack.Concat(new[] { _currentPosition }); return JsonPosition.BuildPath(positions); } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (depth < _stack.Count) return _stack[depth]; return _currentPosition; } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> protected JsonReader() { _currentState = State.Start; _stack = new List<JsonPosition>(4); _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); } else { _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); // this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition oldPosition; if (_stack.Count > 0) { oldPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { oldPosition = _currentPosition; _currentPosition = new JsonPosition(); } if (_maxDepth != null && Depth <= _maxDepth) _hasExceededMaxDepth = false; return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns> public abstract bool Read(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract int? ReadAsInt32(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract string ReadAsString(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Byte"/>[]. /// </summary> /// <returns>A <see cref="Byte"/>[] or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns> public abstract byte[] ReadAsBytes(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract decimal? ReadAsDecimal(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract DateTime? ReadAsDateTime(); #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns> public abstract DateTimeOffset? ReadAsDateTimeOffset(); #endif internal virtual bool ReadInternal() { throw new NotImplementedException(); } #if !NET20 internal DateTimeOffset? ReadAsDateTimeOffsetInternal() { _readType = ReadType.ReadAsDateTimeOffset; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Date) { if (Value is DateTime) SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false); return (DateTimeOffset)Value; } if (t == JsonToken.Null) return null; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } object temp; DateTimeOffset dt; if (DateTimeUtils.TryParseDateTime(s, DateParseHandling.DateTimeOffset, DateTimeZoneHandling, _dateFormatString, Culture, out temp)) { dt = (DateTimeOffset)temp; SetToken(JsonToken.Date, dt, false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } #endif internal byte[] ReadAsBytesInternal() { _readType = ReadType.ReadAsBytes; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (IsWrappedInTypeObject()) { byte[] data = ReadAsBytes(); ReadInternal(); SetToken(JsonToken.Bytes, data, false); return data; } // attempt to convert possible base 64 string to bytes if (t == JsonToken.String) { string s = (string)Value; byte[] data; Guid g; if (s.Length == 0) { data = new byte[0]; } else if (ConvertUtils.TryConvertGuid(s, out g)) { data = g.ToByteArray(); } else { data = Convert.FromBase64String(s); } SetToken(JsonToken.Bytes, data, false); return data; } if (t == JsonToken.Null) return null; if (t == JsonToken.Bytes) { if (ValueType == typeof(Guid)) { byte[] data = ((Guid)Value).ToByteArray(); SetToken(JsonToken.Bytes, data, false); return data; } return (byte[])Value; } if (t == JsonToken.StartArray) { List<byte> data = new List<byte>(); while (ReadInternal()) { t = TokenType; switch (t) { case JsonToken.Integer: data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); break; case JsonToken.EndArray: byte[] d = data.ToArray(); SetToken(JsonToken.Bytes, d, false); return d; case JsonToken.Comment: // skip break; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal decimal? ReadAsDecimalInternal() { _readType = ReadType.ReadAsDecimal; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is decimal)) SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false); return (decimal)Value; } if (t == JsonToken.Null) return null; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } decimal d; if (decimal.TryParse(s, NumberStyles.Number, Culture, out d)) { SetToken(JsonToken.Float, d, false); return d; } else { throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal int? ReadAsInt32Internal() { _readType = ReadType.ReadAsInt32; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is int)) SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false); return (int)Value; } if (t == JsonToken.Null) return null; int i; if (t == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out i)) { SetToken(JsonToken.Integer, i, false); return i; } else { throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal string ReadAsStringInternal() { _readType = ReadType.ReadAsString; JsonToken t; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } else { t = TokenType; } } while (t == JsonToken.Comment); if (t == JsonToken.String) return (string)Value; if (t == JsonToken.Null) return null; if (JsonTokenUtils.IsPrimitiveToken(t)) { if (Value != null) { string s; if (Value is IFormattable) s = ((IFormattable)Value).ToString(null, Culture); else s = Value.ToString(); SetToken(JsonToken.String, s, false); return s; } } if (t == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal DateTime? ReadAsDateTimeInternal() { _readType = ReadType.ReadAsDateTime; do { if (!ReadInternal()) { SetToken(JsonToken.None); return null; } } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Date) return (DateTime)Value; if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.String) { string s = (string)Value; if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null); return null; } DateTime dt; object temp; if (DateTimeUtils.TryParseDateTime(s, DateParseHandling.DateTime, DateTimeZoneHandling, _dateFormatString, Culture, out temp)) { dt = (DateTime)temp; dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } if (TokenType == JsonToken.EndArray) return null; throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } private bool IsWrappedInTypeObject() { _readType = ReadType.Read; if (TokenType == JsonToken.StartObject) { if (!ReadInternal()) throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); if (Value.ToString() == JsonTypeReflector.TypePropertyName) { ReadInternal(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReadInternal(); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) { return true; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } return false; } /// <summary> /// Skips the children of the current token. /// </summary> public void Skip() { if (TokenType == JsonToken.PropertyName) Read(); if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && (depth < Depth)) { } } } /// <summary> /// Sets the current token. /// </summary> /// <param name="newToken">The new token.</param> protected void SetToken(JsonToken newToken) { SetToken(newToken, null, true); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, true); } internal void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Undefined: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Date: case JsonToken.String: case JsonToken.Raw: case JsonToken.Bytes: SetPostValueState(updateIndex); break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != JsonContainerType.None) _currentState = State.PostValue; else SetFinished(); if (updateIndex) UpdateScopeWithFinishedValue(); } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) _currentPosition.Position++; } private void ValidateEnd(JsonToken endToken) { JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); if (Peek() != JsonContainerType.None) _currentState = State.PostValue; else SetFinished(); } /// <summary> /// Sets the state based on current token type. /// </summary> protected void SetStateBasedOnCurrent() { JsonContainerType currentObject = Peek(); switch (currentObject) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); } } private void SetFinished() { if (SupportMultipleContent) _currentState = State.Start; else _currentState = State.Finished; } private JsonContainerType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JsonContainerType.Object; case JsonToken.EndArray: return JsonContainerType.Array; case JsonToken.EndConstructor: return JsonContainerType.Constructor; default: throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { Dispose(true); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) Close(); } /// <summary> /// Changes the <see cref="State"/> to Closed. /// </summary> public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } } }
using McMaster.Extensions.CommandLineUtils; using NuKeeper.Abstractions; using NuKeeper.Abstractions.Configuration; using NuKeeper.Abstractions.Formats; using NuKeeper.Abstractions.Logging; using NuKeeper.Abstractions.NuGet; using NuKeeper.Abstractions.Output; using NuKeeper.Engine; using NuKeeper.Inspection.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace NuKeeper.Commands { [HelpOption] internal abstract class CommandBase { private readonly IConfigureLogger _configureLogger; protected readonly IFileSettingsCache FileSettingsCache; [Option(CommandOptionType.SingleValue, ShortName = "c", LongName = "change", Description = "Allowed version change: Patch, Minor, Major. Defaults to Major.")] public VersionChange? AllowedChange { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "", LongName = "useprerelease", Description = "Allowed prerelease: Always, Never, FromPrerelease. Defaults to FromPrerelease.")] public UsePrerelease? UsePrerelease { get; set; } [Option(CommandOptionType.MultipleValue, ShortName = "s", LongName = "source", Description = "Specifies a NuGet package source to use during the operation. This setting overrides all of the sources specified in the NuGet.config files. Multiple sources can be provided by specifying this option multiple times.")] // ReSharper disable once UnassignedGetOnlyAutoProperty // ReSharper disable once MemberCanBePrivate.Global protected string[] Source { get; } protected NuGetSources NuGetSources => Source == null ? null : new NuGetSources(Source); [Option(CommandOptionType.SingleValue, ShortName = "a", LongName = "age", Description = "Exclude updates that do not meet a minimum age, in order to not consume packages immediately after they are released. Examples: 0 = zero, 12h = 12 hours, 3d = 3 days, 2w = two weeks. The default is 7 days.")] // ReSharper disable once UnassignedGetOnlyAutoProperty // ReSharper disable once MemberCanBePrivate.Global protected string MinimumPackageAge { get; } [Option(CommandOptionType.SingleValue, ShortName = "i", LongName = "include", Description = "Only consider packages matching this regex pattern.")] public string Include { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "e", LongName = "exclude", Description = "Do not consider packages matching this regex pattern.")] public string Exclude { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "v", LongName = "verbosity", Description = "Sets the verbosity level of the command. Allowed values are q[uiet], m[inimal], n[ormal], d[etailed].")] public LogLevel? Verbosity { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "", LongName = "logdestination", Description = "Destination for logging.")] public LogDestination? LogDestination { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "", LongName = "logfile", Description = "Log to the named file.")] public string LogFile { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "", LongName = "outputformat", Description = "Format for output.")] public OutputFormat? OutputFormat { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "", LongName = "outputdestination", Description = "Destination for output.")] public OutputDestination? OutputDestination { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "", LongName = "outputfile", Description = "File name for output.")] public string OutputFileName { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "", LongName = "branchnametemplate", Description = "Template used for creating the branch name.")] public string BranchNameTemplate { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "git", LongName = "gitclipath", Description = "Path to git to use instead of lib2gitsharp implementation")] public string GitCliPath { get; set; } protected CommandBase(IConfigureLogger logger, IFileSettingsCache fileSettingsCache) { _configureLogger = logger; FileSettingsCache = fileSettingsCache; } public async Task<int> OnExecute() { InitialiseLogging(); var settings = MakeSettings(); var validationResult = await PopulateSettings(settings); if (!validationResult.IsSuccess) { var logger = _configureLogger as INuKeeperLogger; logger?.Error(validationResult.ErrorMessage); return -1; } return await Run(settings); } private void InitialiseLogging() { var settingsFromFile = FileSettingsCache.GetSettings(); var defaultLogDestination = string.IsNullOrWhiteSpace(LogFile) ? Abstractions.Logging.LogDestination.Console : Abstractions.Logging.LogDestination.File; var logDest = Concat.FirstValue(LogDestination, settingsFromFile.LogDestination, defaultLogDestination); var logLevel = Concat.FirstValue(Verbosity, settingsFromFile.Verbosity, LogLevel.Normal); var logFile = Concat.FirstValue(LogFile, settingsFromFile.LogFile, "nukeeper.log"); _configureLogger.Initialise(logLevel, logDest, logFile); } private SettingsContainer MakeSettings() { var fileSettings = FileSettingsCache.GetSettings(); var allowedChange = Concat.FirstValue(AllowedChange, fileSettings.Change, VersionChange.Major); var usePrerelease = Concat.FirstValue(UsePrerelease, fileSettings.UsePrerelease, Abstractions.Configuration.UsePrerelease.FromPrerelease); var branchNameTemplate = Concat.FirstValue(BranchNameTemplate, fileSettings.BranchNameTemplate); var gitpath = Concat.FirstValue(GitCliPath, fileSettings.GitCliPath); var settings = new SettingsContainer { SourceControlServerSettings = new SourceControlServerSettings(), PackageFilters = new FilterSettings(), UserSettings = new UserSettings { AllowedChange = allowedChange, UsePrerelease = usePrerelease, NuGetSources = NuGetSources, GitPath = gitpath }, BranchSettings = new BranchSettings { BranchNameTemplate = branchNameTemplate } }; return settings; } protected virtual async Task<ValidationResult> PopulateSettings(SettingsContainer settings) { var minPackageAge = ReadMinPackageAge(); if (!minPackageAge.HasValue) { return await Task.FromResult(ValidationResult.Failure($"Min package age '{MinimumPackageAge}' could not be parsed")); } settings.PackageFilters.MinimumAge = minPackageAge.Value; var regexIncludeValid = PopulatePackageIncludes(settings); if (!regexIncludeValid.IsSuccess) { return regexIncludeValid; } var regexExcludeValid = PopulatePackageExcludes(settings); if (!regexExcludeValid.IsSuccess) { return regexExcludeValid; } var settingsFromFile = FileSettingsCache.GetSettings(); var defaultOutputDestination = string.IsNullOrWhiteSpace(OutputFileName) ? Abstractions.Output.OutputDestination.Console : Abstractions.Output.OutputDestination.File; settings.UserSettings.OutputDestination = Concat.FirstValue(OutputDestination, settingsFromFile.OutputDestination, defaultOutputDestination); settings.UserSettings.OutputFormat = Concat.FirstValue(OutputFormat, settingsFromFile.OutputFormat, Abstractions.Output.OutputFormat.Text); settings.UserSettings.OutputFileName = Concat.FirstValue(OutputFileName, settingsFromFile.OutputFileName, "nukeeper.out"); var branchNameTemplateValid = PopulateBranchNameTemplate(settings); if (!branchNameTemplateValid.IsSuccess) { return branchNameTemplateValid; } return await Task.FromResult(ValidationResult.Success); } private TimeSpan? ReadMinPackageAge() { const string defaultMinPackageAge = "7d"; var settingsFromFile = FileSettingsCache.GetSettings(); var valueWithFallback = Concat.FirstValue(MinimumPackageAge, settingsFromFile.Age, defaultMinPackageAge); return DurationParser.Parse(valueWithFallback); } private ValidationResult PopulatePackageIncludes( SettingsContainer settings) { var settingsFromFile = FileSettingsCache.GetSettings(); var value = Concat.FirstValue(Include, settingsFromFile.Include); if (string.IsNullOrWhiteSpace(value)) { settings.PackageFilters.Includes = null; return ValidationResult.Success; } try { settings.PackageFilters.Includes = new Regex(value); } catch (ArgumentException ex) { { return ValidationResult.Failure( $"Unable to parse regex '{value}' for Include: {ex.Message}"); } } return ValidationResult.Success; } private ValidationResult PopulatePackageExcludes( SettingsContainer settings) { var settingsFromFile = FileSettingsCache.GetSettings(); var value = Concat.FirstValue(Exclude, settingsFromFile.Exclude); if (string.IsNullOrWhiteSpace(value)) { settings.PackageFilters.Excludes = null; return ValidationResult.Success; } try { settings.PackageFilters.Excludes = new Regex(value); } catch (ArgumentException ex) { { return ValidationResult.Failure( $"Unable to parse regex '{value}' for Exclude: {ex.Message}"); } } return ValidationResult.Success; } private ValidationResult PopulateBranchNameTemplate( SettingsContainer settings) { var settingsFromFile = FileSettingsCache.GetSettings(); var value = Concat.FirstValue(BranchNameTemplate, settingsFromFile.BranchNameTemplate); if (string.IsNullOrWhiteSpace(value)) { settings.BranchSettings.BranchNameTemplate = null; return ValidationResult.Success; } // Validating git branch names: https://stackoverflow.com/a/12093994/1661209 // We validate the user defined branch name prefix in combination with a actual branch name that NuKeeper could create. // We want to validate the combination since the prefix doesn't need to fully comply with the rules (E.G. 'nukeeper/' is not allowed soley as a branch name). var tokenErrors = new StringBuilder(); var tokenSet = Regex.Matches(value, @"{(\w+)}").Select(match => match.Groups[1].Value); foreach (var token in tokenSet) { if (!BranchNamer.IsValidTemplateToken(token)) { tokenErrors.Append($",{token}"); } } // Check for valid placeholders if (tokenErrors.Length > 0) { return ValidationResult.Failure( $"Provided branch template has unknown tokens: '{tokenErrors.ToString().Trim(',')}'."); } // Test if the generated branchname would be ok. // We assume tokens will be generated in valid values, so we use dummy values here var tokenValues = new Dictionary<string, string>(); foreach (var token in BranchNamer.TemplateTokens) { tokenValues.Add(token, "dummy"); } var validationValue = BranchNamer.MakeName(tokenValues, value); if (!Regex.IsMatch(validationValue, @"^(?!@$|build-|/|.*([/.]\.|//|@\{|\\))[^\000-\037\177 ~^:?*[]+/[^\000-\037\177 ~^:?*[]+(?<!\.lock|[/.])$")) { return ValidationResult.Failure( $"Provided branch template '{value}' does not comply with branch naming rules."); } settings.BranchSettings.BranchNameTemplate = value; return ValidationResult.Success; } protected abstract Task<int> Run(SettingsContainer settings); } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Avalonia.Diagnostics; namespace Avalonia.Collections { /// <summary> /// Describes the action notified on a clear of a <see cref="AvaloniaList{T}"/>. /// </summary> public enum ResetBehavior { /// <summary> /// Clearing the list notifies a with a /// <see cref="NotifyCollectionChangedAction.Reset"/>. /// </summary> Reset, /// <summary> /// Clearing the list notifies a with a /// <see cref="NotifyCollectionChangedAction.Remove"/>. /// </summary> Remove, } /// <summary> /// A notifying list. /// </summary> /// <typeparam name="T">The type of the list items.</typeparam> /// <remarks> /// <para> /// AvaloniaList is similar to <see cref="System.Collections.ObjectModel.ObservableCollection{T}"/> /// with a few added features: /// </para> /// /// <list type="bullet"> /// <item> /// It can be configured to notify the <see cref="CollectionChanged"/> event with a /// <see cref="NotifyCollectionChangedAction.Remove"/> action instead of a /// <see cref="NotifyCollectionChangedAction.Reset"/> when the list is cleared by /// setting <see cref="ResetBehavior"/> to <see cref="ResetBehavior.Remove"/>. /// removed /// </item> /// <item> /// A <see cref="Validate"/> function can be used to validate each item before insertion. /// removed /// </item> /// </list> /// </remarks> public class AvaloniaList<T> : IAvaloniaList<T>, IList, INotifyCollectionChangedDebug { private readonly List<T> _inner; private NotifyCollectionChangedEventHandler? _collectionChanged; /// <summary> /// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class. /// </summary> public AvaloniaList() { _inner = new List<T>(); } /// <summary> /// Initializes a new instance of the <see cref="AvaloniaList{T}"/>. /// </summary> /// <param name="capacity">Initial list capacity.</param> public AvaloniaList(int capacity) { _inner = new List<T>(capacity); } /// <summary> /// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class. /// </summary> /// <param name="items">The initial items for the collection.</param> public AvaloniaList(IEnumerable<T> items) { _inner = new List<T>(items); } /// <summary> /// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class. /// </summary> /// <param name="items">The initial items for the collection.</param> public AvaloniaList(params T[] items) { _inner = new List<T>(items); } /// <summary> /// Raised when a change is made to the collection's items. /// </summary> public event NotifyCollectionChangedEventHandler? CollectionChanged { add => _collectionChanged += value; remove => _collectionChanged -= value; } /// <summary> /// Raised when a property on the collection changes. /// </summary> public event PropertyChangedEventHandler? PropertyChanged; /// <summary> /// Gets the number of items in the collection. /// </summary> public int Count => _inner.Count; /// <summary> /// Gets or sets the reset behavior of the list. /// </summary> public ResetBehavior ResetBehavior { get; set; } /// <summary> /// Gets or sets a validation routine that can be used to validate items before they are /// added. /// </summary> public Action<T>? Validate { get; set; } /// <inheritdoc/> bool IList.IsFixedSize => false; /// <inheritdoc/> bool IList.IsReadOnly => false; /// <inheritdoc/> int ICollection.Count => _inner.Count; /// <inheritdoc/> bool ICollection.IsSynchronized => false; /// <inheritdoc/> object ICollection.SyncRoot => this; /// <inheritdoc/> bool ICollection<T>.IsReadOnly => false; /// <summary> /// Gets or sets the item at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns>The item.</returns> public T this[int index] { get { return _inner[index]; } set { Validate?.Invoke(value); T old = _inner[index]; if (!EqualityComparer<T>.Default.Equals(old, value)) { _inner[index] = value; if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, value, old, index); _collectionChanged(this, e); } } } } /// <summary> /// Gets or sets the item at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns>The item.</returns> object? IList.this[int index] { get { return this[index]; } set { this[index] = (T)value!; } } /// <summary> /// Gets or sets the total number of elements the internal data structure can hold without resizing. /// </summary> public int Capacity { get => _inner.Capacity; set => _inner.Capacity = value; } /// <summary> /// Adds an item to the collection. /// </summary> /// <param name="item">The item.</param> public virtual void Add(T item) { Validate?.Invoke(item); int index = _inner.Count; _inner.Add(item); NotifyAdd(item, index); } /// <summary> /// Adds multiple items to the collection. /// </summary> /// <param name="items">The items.</param> public virtual void AddRange(IEnumerable<T> items) => InsertRange(_inner.Count, items); /// <summary> /// Removes all items from the collection. /// </summary> public virtual void Clear() { if (Count > 0) { if (_collectionChanged != null) { var e = ResetBehavior == ResetBehavior.Reset ? EventArgsCache.ResetCollectionChanged : new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, _inner.ToList(), 0); _inner.Clear(); _collectionChanged(this, e); } else { _inner.Clear(); } NotifyCountChanged(); } } /// <summary> /// Tests if the collection contains the specified item. /// </summary> /// <param name="item">The item.</param> /// <returns>True if the collection contains the item; otherwise false.</returns> public bool Contains(T item) { return _inner.Contains(item); } /// <summary> /// Copies the collection's contents to an array. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">The first index of the array to copy to.</param> public void CopyTo(T[] array, int arrayIndex) { _inner.CopyTo(array, arrayIndex); } /// <summary> /// Returns an enumerator that enumerates the items in the collection. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/>.</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(_inner); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_inner); } public Enumerator GetEnumerator() { return new Enumerator(_inner); } /// <summary> /// Gets a range of items from the collection. /// </summary> /// <param name="index">The zero-based <see cref="AvaloniaList{T}"/> index at which the range starts.</param> /// <param name="count">The number of elements in the range.</param> public IEnumerable<T> GetRange(int index, int count) { return _inner.GetRange(index, count); } /// <summary> /// Gets the index of the specified item in the collection. /// </summary> /// <param name="item">The item.</param> /// <returns> /// The index of the item or -1 if the item is not contained in the collection. /// </returns> public int IndexOf(T item) { return _inner.IndexOf(item); } /// <summary> /// Inserts an item at the specified index. /// </summary> /// <param name="index">The index.</param> /// <param name="item">The item.</param> public virtual void Insert(int index, T item) { Validate?.Invoke(item); _inner.Insert(index, item); NotifyAdd(item, index); } /// <summary> /// Inserts multiple items at the specified index. /// </summary> /// <param name="index">The index.</param> /// <param name="items">The items.</param> public virtual void InsertRange(int index, IEnumerable<T> items) { _ = items ?? throw new ArgumentNullException(nameof(items)); bool willRaiseCollectionChanged = _collectionChanged != null; bool hasValidation = Validate != null; if (items is IList list) { if (list.Count > 0) { if (list is ICollection<T> collection) { if (hasValidation) { foreach (T item in collection) { Validate!(item); } } _inner.InsertRange(index, collection); NotifyAdd(list, index); } else { EnsureCapacity(_inner.Count + list.Count); using (IEnumerator<T> en = items.GetEnumerator()) { int insertIndex = index; while (en.MoveNext()) { T item = en.Current; if (hasValidation) { Validate!(item); } _inner.Insert(insertIndex++, item); } } NotifyAdd(list, index); } } } else { using (IEnumerator<T> en = items.GetEnumerator()) { if (en.MoveNext()) { // Avoid allocating list for collection notification if there is no event subscriptions. List<T>? notificationItems = willRaiseCollectionChanged ? new List<T>() : null; int insertIndex = index; do { T item = en.Current; if (hasValidation) { Validate!(item); } _inner.Insert(insertIndex++, item); notificationItems?.Add(item); } while (en.MoveNext()); if (notificationItems is not null) NotifyAdd(notificationItems, index); } } } } /// <summary> /// Moves an item to a new index. /// </summary> /// <param name="oldIndex">The index of the item to move.</param> /// <param name="newIndex">The index to move the item to.</param> public void Move(int oldIndex, int newIndex) { var item = this[oldIndex]; _inner.RemoveAt(oldIndex); _inner.Insert(newIndex, item); if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, item, newIndex, oldIndex); _collectionChanged(this, e); } } /// <summary> /// Moves multiple items to a new index. /// </summary> /// <param name="oldIndex">The first index of the items to move.</param> /// <param name="count">The number of items to move.</param> /// <param name="newIndex">The index to move the items to.</param> public void MoveRange(int oldIndex, int count, int newIndex) { var items = _inner.GetRange(oldIndex, count); var modifiedNewIndex = newIndex; _inner.RemoveRange(oldIndex, count); if (newIndex > oldIndex) { modifiedNewIndex -= count; } _inner.InsertRange(modifiedNewIndex, items); if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, items, newIndex, oldIndex); _collectionChanged(this, e); } } /// <summary> /// Ensures that the capacity of the list is at least <see cref="Capacity"/>. /// </summary> /// <param name="capacity">The capacity.</param> public void EnsureCapacity(int capacity) { // Adapted from List<T> implementation. var currentCapacity = _inner.Capacity; if (currentCapacity < capacity) { var newCapacity = currentCapacity == 0 ? 4 : currentCapacity * 2; if (newCapacity < capacity) { newCapacity = capacity; } _inner.Capacity = newCapacity; } } /// <summary> /// Removes an item from the collection. /// </summary> /// <param name="item">The item.</param> /// <returns>True if the item was found and removed, otherwise false.</returns> public virtual bool Remove(T item) { int index = _inner.IndexOf(item); if (index != -1) { _inner.RemoveAt(index); NotifyRemove(item , index); return true; } return false; } /// <summary> /// Removes multiple items from the collection. /// </summary> /// <param name="items">The items.</param> public virtual void RemoveAll(IEnumerable<T> items) { _ = items ?? throw new ArgumentNullException(nameof(items)); var hItems = new HashSet<T>(items); int counter = 0; for (int i = _inner.Count - 1; i >= 0; --i) { if (hItems.Contains(_inner[i])) { counter += 1; } else if(counter > 0) { RemoveRange(i + 1, counter); counter = 0; } } if (counter > 0) RemoveRange(0, counter); } /// <summary> /// Removes the item at the specified index. /// </summary> /// <param name="index">The index.</param> public virtual void RemoveAt(int index) { T item = _inner[index]; _inner.RemoveAt(index); NotifyRemove(item , index); } /// <summary> /// Removes a range of elements from the collection. /// </summary> /// <param name="index">The first index to remove.</param> /// <param name="count">The number of items to remove.</param> public virtual void RemoveRange(int index, int count) { if (count > 0) { var list = _inner.GetRange(index, count); _inner.RemoveRange(index, count); NotifyRemove(list, index); } } /// <inheritdoc/> int IList.Add(object? value) { int index = Count; Add((T)value!); return index; } /// <inheritdoc/> bool IList.Contains(object? value) { return Contains((T)value!); } /// <inheritdoc/> void IList.Clear() { Clear(); } /// <inheritdoc/> int IList.IndexOf(object? value) { return IndexOf((T)value!); } /// <inheritdoc/> void IList.Insert(int index, object? value) { Insert(index, (T)value!); } /// <inheritdoc/> void IList.Remove(object? value) { Remove((T)value!); } /// <inheritdoc/> void IList.RemoveAt(int index) { RemoveAt(index); } /// <inheritdoc/> void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException("Multi-dimensional arrays are not supported."); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException("Non-zero lower bounds are not supported."); } if (index < 0) { throw new ArgumentException("Invalid index."); } if (array.Length - index < Count) { throw new ArgumentException("The target array is too small."); } if (array is T[] tArray) { _inner.CopyTo(tArray, index); } else { // // Catch the obvious case assignment will fail. // We can't find all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType()!; Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { throw new ArgumentException("Invalid array type"); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // if (array is not object?[] objects) { throw new ArgumentException("Invalid array type"); } int count = _inner.Count; try { for (int i = 0; i < count; i++) { objects[index++] = _inner[i]; } } catch (ArrayTypeMismatchException) { throw new ArgumentException("Invalid array type"); } } } /// <inheritdoc/> Delegate[]? INotifyCollectionChangedDebug.GetCollectionChangedSubscribers() => _collectionChanged?.GetInvocationList(); /// <summary> /// Raises the <see cref="CollectionChanged"/> event with an add action. /// </summary> /// <param name="t">The items that were added.</param> /// <param name="index">The starting index.</param> private void NotifyAdd(IList t, int index) { if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, t, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// <summary> /// Raises the <see cref="CollectionChanged"/> event with a add action. /// </summary> /// <param name="item">The item that was added.</param> /// <param name="index">The starting index.</param> private void NotifyAdd(T item, int index) { if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new[] { item }, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// <summary> /// Raises the <see cref="PropertyChanged"/> event when the <see cref="Count"/> property /// changes. /// </summary> private void NotifyCountChanged() { PropertyChanged?.Invoke(this, EventArgsCache.CountPropertyChanged); } /// <summary> /// Raises the <see cref="CollectionChanged"/> event with a remove action. /// </summary> /// <param name="t">The items that were removed.</param> /// <param name="index">The starting index.</param> private void NotifyRemove(IList t, int index) { if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, t, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// <summary> /// Raises the <see cref="CollectionChanged"/> event with a remove action. /// </summary> /// <param name="item">The item that was removed.</param> /// <param name="index">The starting index.</param> private void NotifyRemove(T item, int index) { if (_collectionChanged != null) { var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new[] { item }, index); _collectionChanged(this, e); } NotifyCountChanged(); } /// <summary> /// Enumerates the elements of a <see cref="AvaloniaList{T}"/>. /// </summary> public struct Enumerator : IEnumerator<T> { private List<T>.Enumerator _innerEnumerator; public Enumerator(List<T> inner) { _innerEnumerator = inner.GetEnumerator(); } public bool MoveNext() { return _innerEnumerator.MoveNext(); } void IEnumerator.Reset() { ((IEnumerator)_innerEnumerator).Reset(); } public T Current => _innerEnumerator.Current; object? IEnumerator.Current => Current; public void Dispose() { _innerEnumerator.Dispose(); } } } internal static class EventArgsCache { internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs(nameof(AvaloniaList<object>.Count)); internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset); } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Runtime.Remoting { using System.Globalization; using System.Runtime.Remoting; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Activation; using System.Runtime.Remoting.Lifetime; using System.Security.Cryptography; using Microsoft.Win32; using System.Threading; using System; // Identity is the base class for remoting identities. An instance of Identity (or a derived class) // is associated with each instance of a remoted object. Likewise, an instance of Identity is // associated with each instance of a remoting proxy. // using System.Collections; internal class Identity { // We use a Guid to create a URI from. Each time a new URI is needed we increment // the sequence number and append it to the statically inited Guid. // private static readonly Guid IDGuid = Guid.NewGuid(); internal static String ProcessIDGuid { get { return SharedStatics.Remoting_Identity_IDGuid; } } // We need the original and the configured one because we have to compare // both when looking at a uri since something might be marshalled before // the id is set. private static String s_originalAppDomainGuid = Guid.NewGuid().ToString().Replace('-', '_'); private static String s_configuredAppDomainGuid = null; internal static String AppDomainUniqueId { get { if (s_configuredAppDomainGuid != null) return s_configuredAppDomainGuid; else return s_originalAppDomainGuid; } // get } // AppDomainGuid private static String s_originalAppDomainGuidString = "/" + s_originalAppDomainGuid.ToLower(CultureInfo.InvariantCulture) + "/"; private static String s_configuredAppDomainGuidString = null; private static String s_IDGuidString = "/" + s_originalAppDomainGuid.ToLower(CultureInfo.InvariantCulture) + "/"; // Used to get random numbers private static RNGCryptoServiceProvider s_rng = new RNGCryptoServiceProvider(); internal static String IDGuidString { get { return s_IDGuidString; } } internal static String RemoveAppNameOrAppGuidIfNecessary(String uri) { // uri is assumed to be in lower-case at this point // If the uri starts with either, "/<appname>/" or "/<appdomainguid>/" we // should strip that off. // We only need to look further if the uri starts with a "/". if ((uri == null) || (uri.Length <= 1) || (uri[0] != '/')) return uri; // compare to process guid (guid string already has slash at beginnning and end) String guidStr; if (s_configuredAppDomainGuidString != null) { guidStr = s_configuredAppDomainGuidString; if (uri.Length > guidStr.Length) { if (StringStartsWith(uri, guidStr)) { // remove "/<appdomainguid>/" return uri.Substring(guidStr.Length); } } } // always need to check original guid as well in case the object with this // uri was marshalled before we changed the app domain id guidStr = s_originalAppDomainGuidString; if (uri.Length > guidStr.Length) { if (StringStartsWith(uri, guidStr)) { // remove "/<appdomainguid>/" return uri.Substring(guidStr.Length); } } // compare to application name (application name will never have slashes) String appName = RemotingConfiguration.ApplicationName; if (appName != null) { // add +2 to appName length for surrounding slashes if (uri.Length > (appName.Length + 2)) { if (String.Compare(uri, 1, appName, 0, appName.Length, true, CultureInfo.InvariantCulture) == 0) { // now, make sure there is a slash after "/<appname>" in uri if (uri[appName.Length + 1] == '/') { // remove "/<appname>/" return uri.Substring(appName.Length + 2); } } } } // it didn't start with "/<appname>/" or "/<processguid>/", so just remove the // first slash and return. uri = uri.Substring(1); return uri; } // RemoveAppNameOrAppGuidIfNecessary private static bool StringStartsWith(String s1, String prefix) { // String.StartsWith uses String.Compare instead of String.CompareOrdinal, // so we provide our own implementation of StartsWith. if (s1.Length < prefix.Length) return false; return (String.CompareOrdinal(s1, 0, prefix, 0, prefix.Length) == 0); } // StringStartsWith // DISCONNECTED_FULL denotes that the object is disconnected // from both local & remote (x-appdomain & higher) clients // DISCONNECTED_REM denotes that the object is disconnected // from remote (x-appdomain & higher) clients ... however // x-context proxies continue to work as expected. protected const int IDFLG_DISCONNECTED_FULL= 0x00000001; protected const int IDFLG_DISCONNECTED_REM = 0x00000002; protected const int IDFLG_IN_IDTABLE = 0x00000004; protected const int IDFLG_CONTEXT_BOUND = 0x00000010; protected const int IDFLG_WELLKNOWN = 0x00000100; protected const int IDFLG_SERVER_SINGLECALL= 0x00000200; protected const int IDFLG_SERVER_SINGLETON = 0x00000400; internal int _flags; internal Object _tpOrObject; protected String _ObjURI; protected String _URL; // These have to be "Object" to use Interlocked operations internal Object _objRef; internal Object _channelSink; // Remoting proxy has this field too, we use the latter only for // ContextBoundObject identities. internal Object _envoyChain; // This manages the dynamically registered sinks for the proxy. internal DynamicPropertyHolder _dph; // Lease for object internal Lease _lease; internal static String ProcessGuid {get {return ProcessIDGuid;}} private static int GetNextSeqNum() { return SharedStatics.Remoting_Identity_GetNextSeqNum(); } private static Byte[] GetRandomBytes() { // PERF? In a situation where objects need URIs at a very fast // rate, we will end up creating too many of these tiny byte-arrays // causing pressure on GC! // One option would be to have a buff in the managed thread class // and use that to get a chunk of random bytes consuming // 18 bytes at a time. // This would avoid the need to have a lock across threads. Byte[] randomBytes = new byte[18]; s_rng.GetBytes(randomBytes); return randomBytes; } // Constructs a new identity using the given the URI. This is used for // creating client side identities. // // internal Identity(String objURI, String URL) { BCLDebug.Assert(objURI!=null,"objURI should not be null here"); if (URL != null) { _flags |= IDFLG_WELLKNOWN; _URL = URL; } SetOrCreateURI(objURI, true /*calling from ID ctor*/); } // Constructs a new identity. This is used for creating server side // identities. The URI for server side identities is lazily generated // during the first call to Marshal because if we associate a URI with the // object at the time of creation then you cannot call Marshal with a // URI of your own choice. // // internal Identity(bool bContextBound) { if(bContextBound) _flags |= IDFLG_CONTEXT_BOUND; } internal bool IsContextBound { get { return (_flags&IDFLG_CONTEXT_BOUND) == IDFLG_CONTEXT_BOUND; } } internal bool IsWellKnown() { return (_flags&IDFLG_WELLKNOWN) == IDFLG_WELLKNOWN; } internal void SetInIDTable() { while(true) { int currentFlags = _flags; int newFlags = _flags | IDFLG_IN_IDTABLE; if(currentFlags == Interlocked.CompareExchange(ref _flags, newFlags, currentFlags)) break; } } [System.Security.SecurityCritical] // auto-generated internal void ResetInIDTable(bool bResetURI) { BCLDebug.Assert(IdentityHolder.TableLock.IsWriterLockHeld, "IDTable should be write-locked"); while(true) { int currentFlags = _flags; int newFlags = _flags & (~IDFLG_IN_IDTABLE); if(currentFlags == Interlocked.CompareExchange(ref _flags, newFlags, currentFlags)) break; } // bResetURI is true for the external API call to Disconnect, it is // false otherwise. Thus when a user Disconnects an object // its URI will get reset but if lifetime service times it out // it will not clear out the URIs if (bResetURI) { ((ObjRef)_objRef).URI = null; _ObjURI = null; } } internal bool IsInIDTable() { return((_flags & IDFLG_IN_IDTABLE) == IDFLG_IN_IDTABLE); } internal void SetFullyConnected() { BCLDebug.Assert( this is ServerIdentity, "should be setting these flags for srvIDs only!"); BCLDebug.Assert( (_ObjURI != null), "Object must be assigned a URI to be fully connected!"); while(true) { int currentFlags = _flags; int newFlags = _flags & (~(IDFLG_DISCONNECTED_FULL | IDFLG_DISCONNECTED_REM)); if(currentFlags == Interlocked.CompareExchange(ref _flags, newFlags, currentFlags)) break; } } internal bool IsFullyDisconnected() { BCLDebug.Assert( this is ServerIdentity, "should be setting these flags for srvIDs only!"); return (_flags&IDFLG_DISCONNECTED_FULL) == IDFLG_DISCONNECTED_FULL; } internal bool IsRemoteDisconnected() { BCLDebug.Assert( this is ServerIdentity, "should be setting these flags for srvIDs only!"); return (_flags&IDFLG_DISCONNECTED_REM) == IDFLG_DISCONNECTED_REM; } internal bool IsDisconnected() { BCLDebug.Assert( this is ServerIdentity, "should be setting these flags for srvIDs only!"); return (IsFullyDisconnected() || IsRemoteDisconnected()); } // Get the URI internal String URI { get { if(IsWellKnown()) { return _URL; } else { return _ObjURI; } } } internal String ObjURI { get { return _ObjURI; } } internal MarshalByRefObject TPOrObject { get { return (MarshalByRefObject) _tpOrObject; } } // Set the transparentProxy field protecting against ----s. The returned transparent // proxy could be different than the one the caller is attempting to set. // internal Object RaceSetTransparentProxy(Object tpObj) { if (_tpOrObject == null) Interlocked.CompareExchange(ref _tpOrObject, tpObj, null); return _tpOrObject; } // Get the ObjRef. internal ObjRef ObjectRef { [System.Security.SecurityCritical] // auto-generated get { return (ObjRef) _objRef; } } // Set the objRef field protecting against ----s. The returned objRef // could be different than the one the caller is attempting to set. // [System.Security.SecurityCritical] // auto-generated internal ObjRef RaceSetObjRef(ObjRef objRefGiven) { if (_objRef == null) { Interlocked.CompareExchange(ref _objRef, objRefGiven, null); } return (ObjRef) _objRef; } // Get the ChannelSink. internal IMessageSink ChannelSink { get { return (IMessageSink) _channelSink;} } // Set the channelSink field protecting against ----s. The returned // channelSink proxy could be different than the one the caller is // attempting to set. // internal IMessageSink RaceSetChannelSink(IMessageSink channelSink) { if (_channelSink == null) { Interlocked.CompareExchange( ref _channelSink, channelSink, null); } return (IMessageSink) _channelSink; } // Get/Set the Envoy Sink chain.. internal IMessageSink EnvoyChain { get { return (IMessageSink)_envoyChain; } } // Get/Set Lease internal Lease Lease { get { return _lease; } set { _lease = value; } } // Set the channelSink field protecting against ----s. The returned // channelSink proxy could be different than the one the caller is // attempting to set. // internal IMessageSink RaceSetEnvoyChain( IMessageSink envoyChain) { if (_envoyChain == null) { Interlocked.CompareExchange( ref _envoyChain, envoyChain, null); } return (IMessageSink) _envoyChain; } // A URI is lazily generated for the identity based on a GUID. // Well known objects supply their own URI internal void SetOrCreateURI(String uri) { SetOrCreateURI(uri, false); } internal void SetOrCreateURI(String uri, bool bIdCtor) { if(bIdCtor == false) { // This method is called either from the ID Constructor or // with a writeLock on the ID Table BCLDebug.Assert(IdentityHolder.TableLock.IsWriterLockHeld, "IDTable should be write-locked"); if (null != _ObjURI) { throw new RemotingException( Environment.GetResourceString("Remoting_SetObjectUriForMarshal__UriExists")); } } if(null == uri) { // We insert the tick count, so that the uri is not 100% predictable. // (i.e. perhaps we should consider using a random number as well) String random = System.Convert.ToBase64String(GetRandomBytes()); // Need to replace the '/' with '_' since '/' is not a valid uri char _ObjURI = (IDGuidString + random.Replace('/', '_') + "_" + GetNextSeqNum().ToString(CultureInfo.InvariantCulture.NumberFormat) + ".rem").ToLower(CultureInfo.InvariantCulture); } else { if (this is ServerIdentity) _ObjURI = IDGuidString + uri; else _ObjURI = uri; } } // SetOrCreateURI // This is used by ThreadAffinity/Synchronization contexts // (Shares the seqNum space with URIs) internal static String GetNewLogicalCallID() { return IDGuidString + GetNextSeqNum(); } [System.Security.SecurityCritical] // auto-generated [System.Diagnostics.Conditional("_DEBUG")] internal virtual void AssertValid() { if (URI != null) { Identity resolvedIdentity = IdentityHolder.ResolveIdentity(URI); BCLDebug.Assert( (resolvedIdentity == null) || (resolvedIdentity == this), "Server ID mismatch with URI"); } } [System.Security.SecurityCritical] // auto-generated internal bool AddProxySideDynamicProperty(IDynamicProperty prop) { lock(this) { if (_dph == null) { DynamicPropertyHolder dph = new DynamicPropertyHolder(); lock(this) { if (_dph == null) { _dph = dph; } } } return _dph.AddDynamicProperty(prop); } } [System.Security.SecurityCritical] // auto-generated internal bool RemoveProxySideDynamicProperty(String name) { lock(this) { if (_dph == null) { throw new RemotingException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Contexts_NoProperty"), name)); } return _dph.RemoveDynamicProperty(name); } } internal ArrayWithSize ProxySideDynamicSinks { [System.Security.SecurityCritical] // auto-generated get { if (_dph == null) { return null; } else { return _dph.DynamicSinks; } } } #if _DEBUG public override String ToString() { return ("IDENTITY: " + " URI = " + _ObjURI); } #endif } }
//----------------------------------------------------------------------- // <copyright file="FlowSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Akka.Actor; using Akka.Configuration; using Akka.Pattern; using Akka.Streams.Dsl; using Akka.Streams.Implementation; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Stage; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Akka.TestKit.Internal; using Akka.TestKit.TestEvent; using FluentAssertions; using Reactive.Streams; using Xunit; using Xunit.Abstractions; // ReSharper disable InvokeAsExtensionMethod // ReSharper disable UnusedVariable namespace Akka.Streams.Tests.Dsl { public class FlowSpec : AkkaSpec { private interface IFruit { }; private sealed class Apple : IFruit { }; private static IEnumerable<Apple> Apples() => Enumerable.Range(1, 1000).Select(_ => new Apple()); private static readonly Config Config = ConfigurationFactory.ParseString(@" akka.actor.debug.receive=off akka.loglevel=INFO "); public ActorMaterializerSettings Settings { get; } private ActorMaterializer Materializer { get; } public FlowSpec(ITestOutputHelper helper) : base(Config.WithFallback(ConfigurationFactory.FromResource<ScriptedTest>("Akka.Streams.TestKit.Tests.reference.conf")), helper) { Settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 2); Materializer = ActorMaterializer.Create(Sys, Settings); } [Theory] [InlineData("identity", 1)] [InlineData("identity", 2)] [InlineData("identity", 4)] [InlineData("identity2", 1)] [InlineData("identity2", 2)] [InlineData("identity2", 4)] public void A_flow_must_request_initial_elements_from_upstream(string name, int n) { ChainSetup<int, int, NotUsed> setup; if (name.Equals("identity")) setup = new ChainSetup<int, int, NotUsed>(Identity, Settings.WithInputBuffer(n, n), (settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this); else setup = new ChainSetup<int, int, NotUsed>(Identity2, Settings.WithInputBuffer(n, n), (settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, setup.Settings.MaxInputBufferSize); } [Fact] public void A_Flow_must_request_more_elements_from_upstream_when_downstream_requests_more_elements() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings, (settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, Settings.MaxInputBufferSize); setup.DownstreamSubscription.Request(1); setup.Upstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); setup.DownstreamSubscription.Request(2); setup.Upstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); setup.UpstreamSubscription.SendNext("a"); setup.Downstream.ExpectNext("a"); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); setup.Upstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); setup.UpstreamSubscription.SendNext("b"); setup.UpstreamSubscription.SendNext("c"); setup.UpstreamSubscription.SendNext("d"); setup.Downstream.ExpectNext("b"); setup.Downstream.ExpectNext("c"); } [Fact] public void A_Flow_must_deliver_events_when_publisher_sends_elements_and_then_completes() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings, (settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this); setup.DownstreamSubscription.Request(1); setup.UpstreamSubscription.SendNext("test"); setup.UpstreamSubscription.SendComplete(); setup.Downstream.ExpectNext("test"); setup.Downstream.ExpectComplete(); } [Fact] public void A_Flow_must_deliver_complete_signal_when_publisher_immediately_completes() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings, (settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this); setup.UpstreamSubscription.SendComplete(); setup.Downstream.ExpectComplete(); } [Fact] public void A_Flow_must_deliver_error_signal_when_publisher_immediately_fails() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings, (settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this); var weirdError = new Exception("weird test exception"); setup.UpstreamSubscription.SendError(weirdError); setup.Downstream.ExpectError().Should().Be(weirdError); } [Fact] public void A_Flow_must_cancel_upstream_when_single_subscriber_cancels_subscription_while_receiving_data() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1), (settings, factory) => ActorMaterializer.Create(factory, settings), ToPublisher, this); setup.DownstreamSubscription.Request(5); setup.UpstreamSubscription.ExpectRequest(1); setup.UpstreamSubscription.SendNext("test"); setup.UpstreamSubscription.ExpectRequest(1); setup.UpstreamSubscription.SendNext("test2"); setup.Downstream.ExpectNext("test"); setup.Downstream.ExpectNext("test2"); setup.DownstreamSubscription.Cancel(); // because of the "must cancel its upstream Subscription if its last downstream Subscription has been canceled" rule setup.UpstreamSubscription.ExpectCancellation(); } [Fact] public void A_Flow_must_materialize_into_Publisher_Subscriber() { var flow = Flow.Create<string>(); var t = MaterializeIntoSubscriberAndPublisher(flow, Materializer); var flowIn = t.Item1; var flowOut = t.Item2; var c1 = this.CreateManualSubscriberProbe<string>(); flowOut.Subscribe(c1); var source = Source.From(new[] {"1", "2", "3"}).RunWith(Sink.AsPublisher<string>(false), Materializer); source.Subscribe(flowIn); var sub1 = c1.ExpectSubscription(); sub1.Request(3); c1.ExpectNext("1"); c1.ExpectNext("2"); c1.ExpectNext("3"); c1.ExpectComplete(); } [Fact] public void A_Flow_must_materialize_into_Publisher_Subscriber_and_transformation_processor() { var flow = Flow.Create<int>().Select(i=>i.ToString()); var t = MaterializeIntoSubscriberAndPublisher(flow, Materializer); var flowIn = t.Item1; var flowOut = t.Item2; var c1 = this.CreateManualSubscriberProbe<string>(); flowOut.Subscribe(c1); var sub1 = c1.ExpectSubscription(); sub1.Request(3); c1.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); var source = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer); source.Subscribe(flowIn); c1.ExpectNext("1"); c1.ExpectNext("2"); c1.ExpectNext("3"); c1.ExpectComplete(); } [Fact] public void A_Flow_must_materialize_into_Publisher_Subscriber_and_multiple_transformation_processor() { var flow = Flow.Create<int>().Select(i => i.ToString()).Select(s => "elem-" + s); var t = MaterializeIntoSubscriberAndPublisher(flow, Materializer); var flowIn = t.Item1; var flowOut = t.Item2; var c1 = this.CreateManualSubscriberProbe<string>(); flowOut.Subscribe(c1); var sub1 = c1.ExpectSubscription(); sub1.Request(3); c1.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); var source = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer); source.Subscribe(flowIn); c1.ExpectNext("elem-1"); c1.ExpectNext("elem-2"); c1.ExpectNext("elem-3"); c1.ExpectComplete(); } [Fact] public void A_Flow_must_subscribe_Subscriber() { var flow = Flow.Create<string>(); var c1 = this.CreateManualSubscriberProbe<string>(); var sink = flow.To(Sink.FromSubscriber(c1)); var publisher = Source.From(new[] { "1", "2", "3" }).RunWith(Sink.AsPublisher<string>(false), Materializer); Source.FromPublisher(publisher).To(sink).Run(Materializer); var sub1 = c1.ExpectSubscription(); sub1.Request(3); c1.ExpectNext("1"); c1.ExpectNext("2"); c1.ExpectNext("3"); c1.ExpectComplete(); } [Fact] public void A_Flow_must_perform_transformation_operation() { var flow = Flow.Create<int>().Select(i => { TestActor.Tell(i.ToString()); return i.ToString(); }); var publisher = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer); Source.FromPublisher(publisher).Via(flow).To(Sink.Ignore<string>()).Run(Materializer); ExpectMsg("1"); ExpectMsg("2"); ExpectMsg("3"); } [Fact] public void A_Flow_must_perform_transformation_operation_and_subscribe_Subscriber() { var flow = Flow.Create<int>().Select(i => i.ToString()); var c1 = this.CreateManualSubscriberProbe<string>(); var sink = flow.To(Sink.FromSubscriber(c1)); var publisher = Source.From(new[] { 1, 2, 3 }).RunWith(Sink.AsPublisher<int>(false), Materializer); Source.FromPublisher(publisher).To(sink).Run(Materializer); var sub1 = c1.ExpectSubscription(); sub1.Request(3); c1.ExpectNext("1"); c1.ExpectNext("2"); c1.ExpectNext("3"); c1.ExpectComplete(); } [Fact] public void A_Flow_must_be_materializable_several_times_with_fanout_publisher() { this.AssertAllStagesStopped(() => { var flow = Source.From(new[] {1, 2, 3}).Select(i => i.ToString()); var p1 = flow.RunWith(Sink.AsPublisher<string>(true), Materializer); var p2 = flow.RunWith(Sink.AsPublisher<string>(true), Materializer); var s1 = this.CreateManualSubscriberProbe<string>(); var s2 = this.CreateManualSubscriberProbe<string>(); var s3 = this.CreateManualSubscriberProbe<string>(); p1.Subscribe(s1); p2.Subscribe(s2); p2.Subscribe(s3); var sub1 = s1.ExpectSubscription(); var sub2 = s2.ExpectSubscription(); var sub3 = s3.ExpectSubscription(); sub1.Request(3); s1.ExpectNext("1"); s1.ExpectNext("2"); s1.ExpectNext("3"); s1.ExpectComplete(); sub2.Request(3); sub3.Request(3); s2.ExpectNext("1"); s2.ExpectNext("2"); s2.ExpectNext("3"); s2.ExpectComplete(); s3.ExpectNext("1"); s3.ExpectNext("2"); s3.ExpectNext("3"); s3.ExpectComplete(); }, Materializer); } [Fact] public void A_Flow_must_be_covariant() { Source<IFruit, NotUsed> f1 = Source.From<IFruit>(Apples()); IPublisher<IFruit> p1 = Source.From<IFruit>(Apples()).RunWith(Sink.AsPublisher<IFruit>(false), Materializer); SubFlow<IFruit, NotUsed, IRunnableGraph<NotUsed>> f2 = Source.From<IFruit>(Apples()).SplitWhen(_ => true); SubFlow<IFruit, NotUsed, IRunnableGraph<NotUsed>> f3 = Source.From<IFruit>(Apples()).GroupBy(2, _ => true); Source<Tuple<IImmutableList<IFruit>, Source<IFruit, NotUsed>>, NotUsed> f4 = Source.From<IFruit>(Apples()).PrefixAndTail(1); SubFlow<IFruit, NotUsed, Sink<string, NotUsed>> d1 = Flow.Create<string>() .Select<string, string, IFruit, NotUsed>(_ => new Apple()) .SplitWhen(_ => true); SubFlow<IFruit, NotUsed, Sink<string, NotUsed>> d2 = Flow.Create<string>() .Select<string, string, IFruit, NotUsed>(_ => new Apple()) .GroupBy(-1,_ => 2); Flow<string, Tuple<IImmutableList<IFruit>, Source<IFruit, NotUsed>>, NotUsed> d3 = Flow.Create<string>().Select<string, string, IFruit, NotUsed>(_ => new Apple()).PrefixAndTail(1); } [Fact] public void A_Flow_must_be_possible_to_convert_to_a_processor_and_should_be_able_to_take_a_Processor() { var identity1 = Flow.Create<int>().ToProcessor(); var identity2 = Flow.FromProcessor(() => identity1.Run(Materializer)); var task = Source.From(Enumerable.Range(1, 10)) .Via(identity2) .Limit(100) .RunWith(Sink.Seq<int>(), Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1,10)); // Reusable: task = Source.From(Enumerable.Range(1, 10)) .Via(identity2) .Limit(100) .RunWith(Sink.Seq<int>(), Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10)); } [Fact] public void A_Flow_with_multiple_subscribers_FanOutBox_must_adapt_speed_to_the_currently_slowest_subscriber() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1), (settings, factory) => ActorMaterializer.Create(factory, settings), (source, materializer) => ToFanoutPublisher(source, materializer, 1), this); var downstream2 = this.CreateManualSubscriberProbe<string>(); setup.Publisher.Subscribe(downstream2); var downstream2Subscription = downstream2.ExpectSubscription(); setup.DownstreamSubscription.Request(5); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // because initialInputBufferSize=1 setup.UpstreamSubscription.SendNext("firstElement"); setup.Downstream.ExpectNext("firstElement"); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); setup.UpstreamSubscription.SendNext("element2"); setup.Downstream.ExpectNoMsg(TimeSpan.FromSeconds(1)); downstream2Subscription.Request(1); downstream2.ExpectNext("firstElement"); setup.Downstream.ExpectNext("element2"); downstream2Subscription.Request(1); downstream2.ExpectNext("element2"); } [Fact] public void A_Flow_with_multiple_subscribers_FanOutBox_must_support_slow_subscriber_with_fan_out_2() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1), (settings, factory) => ActorMaterializer.Create(factory, settings), (source, materializer) => ToFanoutPublisher(source, materializer, 2), this); var downstream2 = this.CreateManualSubscriberProbe<string>(); setup.Publisher.Subscribe(downstream2); var downstream2Subscription = downstream2.ExpectSubscription(); setup.DownstreamSubscription.Request(5); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // because initialInputBufferSize=1 setup.UpstreamSubscription.SendNext("element1"); setup.Downstream.ExpectNext("element1"); setup.UpstreamSubscription.ExpectRequest(1); setup.UpstreamSubscription.SendNext("element2"); setup.Downstream.ExpectNext("element2"); setup.UpstreamSubscription.ExpectRequest(1); setup.UpstreamSubscription.SendNext("element3"); // downstream2 has not requested anything, fan-out buffer 2 setup.Downstream.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100))); downstream2Subscription.Request(2); setup.Downstream.ExpectNext("element3"); downstream2.ExpectNext("element1"); downstream2.ExpectNext("element2"); downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100))); setup.UpstreamSubscription.Request(1); setup.UpstreamSubscription.SendNext("element4"); setup.Downstream.ExpectNext("element4"); downstream2Subscription.Request(2); downstream2.ExpectNext("element3"); downstream2.ExpectNext("element4"); setup.UpstreamSubscription.SendComplete(); setup.Downstream.ExpectComplete(); downstream2.ExpectComplete(); } [Fact] public void A_Flow_with_multiple_subscribers_FanOutBox_must_support_incoming_subscriber_while_elements_were_requested_before() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1), (settings, factory) => ActorMaterializer.Create(factory, settings), (source, materializer) => ToFanoutPublisher(source, materializer, 1), this); setup.DownstreamSubscription.Request(5); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); setup.UpstreamSubscription.SendNext("a1"); setup.Downstream.ExpectNext("a1"); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); setup.UpstreamSubscription.SendNext("a2"); setup.Downstream.ExpectNext("a2"); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // link now while an upstream element is already requested var downstream2 = this.CreateManualSubscriberProbe<string>(); setup.Publisher.Subscribe(downstream2); var downstream2Subscription = downstream2.ExpectSubscription(); // situation here: // downstream 1 now has 3 outstanding // downstream 2 has 0 outstanding setup.UpstreamSubscription.SendNext("a3"); setup.Downstream.ExpectNext("a3"); downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100))); // as nothing was requested yet, fanOutBox needs to cache element in this case downstream2Subscription.Request(1); downstream2.ExpectNext("a3"); // d1 now has 2 outstanding // d2 now has 0 outstanding // buffer should be empty so we should be requesting one new element setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // because of buffer size 1 } [Fact] public void A_Flow_with_multiple_subscribers_FanOutBox_must_be_unblocked_when_blocking_subscriber_cancels_subscription() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1), (settings, factory) => ActorMaterializer.Create(factory, settings), (source, materializer) => ToFanoutPublisher(source, materializer, 1), this); var downstream2 = this.CreateManualSubscriberProbe<string>(); setup.Publisher.Subscribe(downstream2); var downstream2Subscription = downstream2.ExpectSubscription(); setup.DownstreamSubscription.Request(5); setup.UpstreamSubscription.ExpectRequest(1); setup.UpstreamSubscription.SendNext("firstElement"); setup.Downstream.ExpectNext("firstElement"); downstream2Subscription.Request(1); downstream2.ExpectNext("firstElement"); setup.UpstreamSubscription.ExpectRequest(1); setup.UpstreamSubscription.SendNext("element2"); setup.Downstream.ExpectNext("element2"); setup.UpstreamSubscription.ExpectRequest(1); setup.UpstreamSubscription.SendNext("element3"); setup.UpstreamSubscription.ExpectRequest(1); setup.Downstream.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(200))); setup.Upstream.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(200))); downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(200))); // should unblock fanoutbox downstream2Subscription.Cancel(); setup.Downstream.ExpectNext("element3"); setup.UpstreamSubscription.SendNext("element4"); setup.Downstream.ExpectNext("element4"); setup.UpstreamSubscription.SendComplete(); setup.Downstream.ExpectComplete(); } [Fact] public void A_Flow_with_multiple_subscribers_FanOutBox_must_call_future_subscribers_OnError_after_OnSubscribe_if_initial_upstream_was_completed() { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1), (settings, factory) => ActorMaterializer.Create(factory, settings), (source, materializer) => ToFanoutPublisher(source, materializer, 1), this); var downstream2 = this.CreateManualSubscriberProbe<string>(); // don't link it just yet setup.DownstreamSubscription.Request(5); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); setup.UpstreamSubscription.SendNext("a1"); setup.Downstream.ExpectNext("a1"); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); setup.UpstreamSubscription.SendNext("a2"); setup.Downstream.ExpectNext("a2"); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); // link now while an upstream element is already requested setup.Publisher.Subscribe(downstream2); var downstream2Subscription = downstream2.ExpectSubscription(); setup.UpstreamSubscription.SendNext("a3"); setup.UpstreamSubscription.SendComplete(); setup.Downstream.ExpectNext("a3"); setup.Downstream.ExpectComplete(); downstream2.ExpectNoMsg(Dilated(TimeSpan.FromMilliseconds(100))); // as nothing was requested yet, fanOutBox needs to cache element in this case downstream2Subscription.Request(1); downstream2.ExpectNext("a3"); downstream2.ExpectComplete(); var downstream3 = this.CreateManualSubscriberProbe<string>(); setup.Publisher.Subscribe(downstream3); downstream3.ExpectSubscription(); downstream3.ExpectError().Should().BeOfType<NormalShutdownException>(); } [Fact] public void A_Flow_with_multiple_subscribers_FanOutBox_must_call_future_subscribers_OnError_should_be_called_instead_of_OnSubscribed_after_initial_upstream_reported_an_error() { var setup = new ChainSetup<int, string, NotUsed>(flow => flow.Select<int,int,string,NotUsed>(_ => { throw new TestException("test"); }), Settings.WithInputBuffer(1, 1), (settings, factory) => ActorMaterializer.Create(factory, settings), (source, materializer) => ToFanoutPublisher(source, materializer, 1), this); setup.DownstreamSubscription.Request(1); setup.UpstreamSubscription.ExpectRequest(1); setup.UpstreamSubscription.SendNext(5); setup.UpstreamSubscription.ExpectRequest(1); setup.UpstreamSubscription.ExpectCancellation(); setup.Downstream.ExpectError().Should().BeOfType<TestException>(); var downstream2 = this.CreateManualSubscriberProbe<string>(); setup.Publisher.Subscribe(downstream2); downstream2.ExpectSubscriptionAndError().Should().BeOfType<TestException>(); } [Fact] public void A_Flow_with_multiple_subscribers_FanOutBox_must_call_future_subscribers_OnError_when_all_subscriptions_were_cancelled () { var setup = new ChainSetup<string, string, NotUsed>(Identity, Settings.WithInputBuffer(1, 1), (settings, factory) => ActorMaterializer.Create(factory, settings), (source, materializer) => ToFanoutPublisher(source, materializer, 16), this); // make sure stream is initialized before canceling downstream Thread.Sleep(100); setup.UpstreamSubscription.ExpectRequest(1); setup.DownstreamSubscription.Cancel(); setup.UpstreamSubscription.ExpectCancellation(); var downstream2 = this.CreateManualSubscriberProbe<string>(); setup.Publisher.Subscribe(downstream2); // IllegalStateException shut down downstream2.ExpectSubscriptionAndError().Should().BeAssignableTo<IllegalStateException>(); } [Fact] public void A_Flow_with_multiple_subscribers_FanOutBox_should_be_created_from_a_function_easily() { Source.From(Enumerable.Range(0, 10)) .Via(Flow.FromFunction<int, int>(i => i + 1)) .RunWith(Sink.Seq<int>(), Materializer) .Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10)); } [Fact] public void A_broken_Flow_must_cancel_upstream_and_call_onError_on_current_and_future_downstream_subscribers_if_an_internal_error_occurs() { var setup = new ChainSetup<string, string, NotUsed>(FaultyFlow<string,string,string>, Settings.WithInputBuffer(1, 1), (settings, factory) => ActorMaterializer.Create(factory, settings), (source, materializer) => ToFanoutPublisher(source, materializer, 16), this); Action<TestSubscriber.ManualProbe<string>> checkError = sprobe => { var error = sprobe.ExpectError(); error.Should().BeOfType<AbruptTerminationException>(); error.Message.Should().StartWith("Processor actor"); }; var downstream2 = this.CreateManualSubscriberProbe<string>(); setup.Publisher.Subscribe(downstream2); var downstream2Subscription = downstream2.ExpectSubscription(); setup.DownstreamSubscription.Request(5); downstream2Subscription.Request(5); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); setup.UpstreamSubscription.SendNext("a1"); setup.Downstream.ExpectNext("a1"); downstream2.ExpectNext("a1"); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); setup.UpstreamSubscription.SendNext("a2"); setup.Downstream.ExpectNext("a2"); downstream2.ExpectNext("a2"); var filters = new EventFilterBase[] { new ErrorFilter(typeof(NullReferenceException)), new ErrorFilter(typeof(IllegalStateException)), new ErrorFilter(typeof(PostRestartException)),// This is thrown because we attach the dummy failing actor to toplevel }; try { Sys.EventStream.Publish(new Mute(filters)); setup.Upstream.ExpectRequest(setup.UpstreamSubscription, 1); setup.UpstreamSubscription.SendNext("a3"); setup.UpstreamSubscription.ExpectCancellation(); // IllegalStateException terminated abruptly checkError(setup.Downstream); checkError(downstream2); var downstream3 = this.CreateManualSubscriberProbe<string>(); setup.Publisher.Subscribe(downstream3); downstream3.ExpectSubscription(); // IllegalStateException terminated abruptly checkError(downstream3); } finally { Sys.EventStream.Publish(new Unmute(filters)); } } [Fact] public void A_broken_Flow_must_suitably_override_attribute_handling_methods() { var f = Flow.Create<int>().Select(x => x + 1).Async().AddAttributes(Attributes.None).Named("name"); f.Module.Attributes.GetFirstAttribute<Attributes.Name>().Value.Should().Be("name"); f.Module.Attributes.GetFirstAttribute<Attributes.AsyncBoundary>() .Should() .Be(Attributes.AsyncBoundary.Instance); } private static Flow<TIn, TOut, TMat> Identity<TIn, TOut, TMat>(Flow<TIn, TOut, TMat> flow) => flow.Select(e => e); private static Flow<TIn, TOut, TMat> Identity2<TIn, TOut, TMat>(Flow<TIn, TOut, TMat> flow) => Identity(flow); private sealed class BrokenActorInterpreter : ActorGraphInterpreter { private readonly object _brokenMessage; public BrokenActorInterpreter(GraphInterpreterShell shell, object brokenMessage) : base(shell) { _brokenMessage = brokenMessage; } protected override bool AroundReceive(Receive receive, object message) { var next = message as OnNext?; if (next.HasValue && next.Value.Id == 0 && next.Value.Event == _brokenMessage) throw new NullReferenceException($"I'm so broken {next.Value.Event}"); return base.AroundReceive(receive, message); } } private Flow<TIn, TOut2, NotUsed> FaultyFlow<TIn, TOut, TOut2>(Flow<TIn, TOut, NotUsed> flow) where TOut : TOut2 { Func<Flow<TOut, TOut2, NotUsed>> createGraph = () => { var stage = new Select<TOut, TOut2>(x => x); var assembly = new GraphAssembly(new IGraphStageWithMaterializedValue<Shape, object>[] { stage }, new[] { Attributes.None }, new Inlet[] { stage.Shape.Inlet , null}, new[] { 0, -1 }, new Outlet[] { null, stage.Shape.Outlet }, new[] { -1, 0 }); var t = assembly.Materialize(Attributes.None, assembly.Stages.Select(s => s.Module).ToArray(), new Dictionary<IModule, object>(), _ => { }); var connections = t.Item1; var logics = t.Item2; var shell = new GraphInterpreterShell(assembly, connections, logics, stage.Shape, Settings, (ActorMaterializerImpl) Materializer); var props = Props.Create(() => new BrokenActorInterpreter(shell, "a3")) .WithDeploy(Deploy.Local) .WithDispatcher("akka.test.stream-dispatcher"); var impl = Sys.ActorOf(props, "broken-stage-actor"); var subscriber = new ActorGraphInterpreter.BoundarySubscriber<TOut>(impl, shell, 0); var publisher = new FaultyFlowPublisher<TOut2>(impl, shell); impl.Tell(new ActorGraphInterpreter.ExposedPublisher(shell, 0, publisher)); return Flow.FromSinkAndSource(Sink.FromSubscriber(subscriber), Source.FromPublisher(publisher)); }; return flow.Via(createGraph()); } private sealed class FaultyFlowPublisher<TOut> : ActorPublisher<TOut> { public FaultyFlowPublisher(IActorRef impl, GraphInterpreterShell shell) : base(impl) { WakeUpMessage = new ActorGraphInterpreter.SubscribePending(shell, 0); } protected override object WakeUpMessage { get; } } private static IPublisher<TOut> ToPublisher<TOut, TMat>(Source<TOut, TMat> source, ActorMaterializer materializer) => source.RunWith(Sink.AsPublisher<TOut>(false), materializer); private static IPublisher<TOut> ToFanoutPublisher<TOut, TMat>(Source<TOut, TMat> source, ActorMaterializer materializer, int elasticity) => source.RunWith( Sink.AsPublisher<TOut>(true).WithAttributes(Attributes.CreateInputBuffer(elasticity, elasticity)), materializer); private static Tuple<ISubscriber<TIn>, IPublisher<TOut>> MaterializeIntoSubscriberAndPublisher<TIn, TOut, TMat>( Flow<TIn, TOut, TMat> flow, ActorMaterializer materializer) => flow.RunWith(Source.AsSubscriber<TIn>(), Sink.AsPublisher<TOut>(false), materializer); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Insights { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Azure.OData; 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> /// AlertRulesOperations operations. /// </summary> internal partial class AlertRulesOperations : IServiceOperations<MonitorManagementClient>, IAlertRulesOperations { /// <summary> /// Initializes a new instance of the AlertRulesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal AlertRulesOperations(MonitorManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the MonitorManagementClient /// </summary> public MonitorManagementClient Client { get; private set; } /// <summary> /// Creates or updates an alert rule. /// Request method: PUT Request URI: /// https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/microsoft.insights/alertRules/{alert-rule-name}?api-version={api-version} /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='parameters'> /// The parameters of the rule to create or update. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<AlertRuleResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string ruleName, AlertRuleResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<AlertRuleResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AlertRuleResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AlertRuleResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes an alert rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _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> /// Gets an alert rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<AlertRuleResource>> GetWithHttpMessagesAsync(string resourceGroupName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (ruleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ruleName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("ruleName", ruleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<AlertRuleResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AlertRuleResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List the alert rules within a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<AlertRuleResource>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, ODataQuery<AlertRuleResource> odataQuery = default(ODataQuery<AlertRuleResource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<AlertRuleResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<AlertRuleResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // https://github.com/mythz/ServiceStack.Redis // ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2013 ServiceStack. // // Licensed under the same terms of Redis and ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using ServiceStack.DesignPatterns.Model; using ServiceStack.Redis.Support; using ServiceStack.Text; namespace ServiceStack.Redis { public partial class RedisClient : IRedisClient { public IHasNamed<IRedisSortedSet> SortedSets { get; set; } internal class RedisClientSortedSets : IHasNamed<IRedisSortedSet> { private readonly RedisClient client; public RedisClientSortedSets(RedisClient client) { this.client = client; } public IRedisSortedSet this[string setId] { get { return new RedisClientSortedSet(client, setId); } set { var col = this[setId]; col.Clear(); col.CopyTo(value.ToArray(), 0); } } } public static double GetLexicalScore(string value) { if (string.IsNullOrEmpty(value)) return 0; var lexicalValue = 0; if (value.Length >= 1) lexicalValue += value[0] * (int)Math.Pow(256, 3); if (value.Length >= 2) lexicalValue += value[1] * (int)Math.Pow(256, 2); if (value.Length >= 3) lexicalValue += value[2] * (int)Math.Pow(256, 1); if (value.Length >= 4) lexicalValue += value[3]; return lexicalValue; } public bool AddItemToSortedSet(string setId, string value) { return AddItemToSortedSet(setId, value, GetLexicalScore(value)); } public bool AddItemToSortedSet(string setId, string value, double score) { return base.ZAdd(setId, score, value.ToUtf8Bytes()) == Success; } public bool AddItemToSortedSet(string setId, string value, long score) { return base.ZAdd(setId, score, value.ToUtf8Bytes()) == Success; } public bool AddRangeToSortedSet(string setId, List<string> values, double score) { var pipeline = CreatePipelineCommand(); var uSetId = setId.ToUtf8Bytes(); var uScore = score.ToFastUtf8Bytes(); foreach (var value in values) { pipeline.WriteCommand(Commands.ZAdd, uSetId, uScore, value.ToUtf8Bytes()); } pipeline.Flush(); var success = pipeline.ReadAllAsIntsHaveSuccess(); return success; } public bool AddRangeToSortedSet(string setId, List<string> values, long score) { var pipeline = CreatePipelineCommand(); var uSetId = setId.ToUtf8Bytes(); var uScore = score.ToUtf8Bytes(); foreach (var value in values) { pipeline.WriteCommand(Commands.ZAdd, uSetId, uScore, value.ToUtf8Bytes()); } pipeline.Flush(); var success = pipeline.ReadAllAsIntsHaveSuccess(); return success; } public bool RemoveItemFromSortedSet(string setId, string value) { return base.ZRem(setId, value.ToUtf8Bytes()) == Success; } public string PopItemWithLowestScoreFromSortedSet(string setId) { //TODO: this should be atomic var topScoreItemBytes = base.ZRange(setId, FirstElement, 1); if (topScoreItemBytes.Length == 0) return null; base.ZRem(setId, topScoreItemBytes[0]); return topScoreItemBytes[0].FromUtf8Bytes(); } public string PopItemWithHighestScoreFromSortedSet(string setId) { //TODO: this should be atomic var topScoreItemBytes = base.ZRevRange(setId, FirstElement, 1); if (topScoreItemBytes.Length == 0) return null; base.ZRem(setId, topScoreItemBytes[0]); return topScoreItemBytes[0].FromUtf8Bytes(); } public bool SortedSetContainsItem(string setId, string value) { return base.ZRank(setId, value.ToUtf8Bytes()) != -1; } public double IncrementItemInSortedSet(string setId, string value, double incrementBy) { return base.ZIncrBy(setId, incrementBy, value.ToUtf8Bytes()); } public double IncrementItemInSortedSet(string setId, string value, long incrementBy) { return base.ZIncrBy(setId, incrementBy, value.ToUtf8Bytes()); } public long GetItemIndexInSortedSet(string setId, string value) { return base.ZRank(setId, value.ToUtf8Bytes()); } public long GetItemIndexInSortedSetDesc(string setId, string value) { return base.ZRevRank(setId, value.ToUtf8Bytes()); } public List<string> GetAllItemsFromSortedSet(string setId) { var multiDataList = base.ZRange(setId, FirstElement, LastElement); return multiDataList.ToStringList(); } public List<string> GetAllItemsFromSortedSetDesc(string setId) { var multiDataList = base.ZRevRange(setId, FirstElement, LastElement); return multiDataList.ToStringList(); } public List<string> GetRangeFromSortedSet(string setId, int fromRank, int toRank) { var multiDataList = base.ZRange(setId, fromRank, toRank); return multiDataList.ToStringList(); } public List<string> GetRangeFromSortedSetDesc(string setId, int fromRank, int toRank) { var multiDataList = base.ZRevRange(setId, fromRank, toRank); return multiDataList.ToStringList(); } public IDictionary<string, double> GetAllWithScoresFromSortedSet(string setId) { var multiDataList = base.ZRangeWithScores(setId, FirstElement, LastElement); return CreateSortedScoreMap(multiDataList); } public IDictionary<string, double> GetRangeWithScoresFromSortedSet(string setId, int fromRank, int toRank) { var multiDataList = base.ZRangeWithScores(setId, fromRank, toRank); return CreateSortedScoreMap(multiDataList); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetDesc(string setId, int fromRank, int toRank) { var multiDataList = base.ZRevRangeWithScores(setId, fromRank, toRank); return CreateSortedScoreMap(multiDataList); } private static IDictionary<string, double> CreateSortedScoreMap(byte[][] multiDataList) { var map = new OrderedDictionary<string, double>(); for (var i = 0; i < multiDataList.Length; i += 2) { var key = multiDataList[i].FromUtf8Bytes(); double value; double.TryParse(multiDataList[i + 1].FromUtf8Bytes(), NumberStyles.Any, CultureInfo.InvariantCulture, out value); map[key] = value; } return map; } public List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore) { return GetRangeFromSortedSetByLowestScore(setId, fromStringScore, toStringScore, null, null); } public List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take) { var fromScore = GetLexicalScore(fromStringScore); var toScore = GetLexicalScore(toStringScore); return GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take); } public List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore) { return GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, null, null); } public List<string> GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore) { return GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, null, null); } public List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take) { var multiDataList = base.ZRangeByScore(setId, fromScore, toScore, skip, take); return multiDataList.ToStringList(); } public List<string> GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take) { var multiDataList = base.ZRangeByScore(setId, fromScore, toScore, skip, take); return multiDataList.ToStringList(); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore) { return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromStringScore, toStringScore, null, null); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take) { var fromScore = GetLexicalScore(fromStringScore); var toScore = GetLexicalScore(toStringScore); return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore) { return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, null, null); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore) { return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, null, null); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take) { var multiDataList = base.ZRangeByScoreWithScores(setId, fromScore, toScore, skip, take); return CreateSortedScoreMap(multiDataList); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take) { var multiDataList = base.ZRangeByScoreWithScores(setId, fromScore, toScore, skip, take); return CreateSortedScoreMap(multiDataList); } public List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore) { return GetRangeFromSortedSetByHighestScore(setId, fromStringScore, toStringScore, null, null); } public List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take) { var fromScore = GetLexicalScore(fromStringScore); var toScore = GetLexicalScore(toStringScore); return GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take); } public List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore) { return GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, null, null); } public List<string> GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore) { return GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, null, null); } public List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take) { var multiDataList = base.ZRevRangeByScore(setId, fromScore, toScore, skip, take); return multiDataList.ToStringList(); } public List<string> GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take) { var multiDataList = base.ZRevRangeByScore(setId, fromScore, toScore, skip, take); return multiDataList.ToStringList(); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore) { return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromStringScore, toStringScore, null, null); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take) { var fromScore = GetLexicalScore(fromStringScore); var toScore = GetLexicalScore(toStringScore); return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore) { return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, null, null); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore) { return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, null, null); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take) { var multiDataList = base.ZRevRangeByScoreWithScores(setId, fromScore, toScore, skip, take); return CreateSortedScoreMap(multiDataList); } public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take) { var multiDataList = base.ZRevRangeByScoreWithScores(setId, fromScore, toScore, skip, take); return CreateSortedScoreMap(multiDataList); } public long RemoveRangeFromSortedSet(string setId, int minRank, int maxRank) { return base.ZRemRangeByRank(setId, minRank, maxRank); } public long RemoveRangeFromSortedSetByScore(string setId, double fromScore, double toScore) { return base.ZRemRangeByScore(setId, fromScore, toScore); } public long RemoveRangeFromSortedSetByScore(string setId, long fromScore, long toScore) { return base.ZRemRangeByScore(setId, fromScore, toScore); } public long GetSortedSetCount(string setId) { return base.ZCard(setId); } public long GetSortedSetCount(string setId, string fromStringScore, string toStringScore) { var fromScore = GetLexicalScore(fromStringScore); var toScore = GetLexicalScore(toStringScore); return GetSortedSetCount(setId, fromScore, toScore); } public long GetSortedSetCount(string setId, double fromScore, double toScore) { return base.ZCount(setId, fromScore, toScore); } public long GetSortedSetCount(string setId, long fromScore, long toScore) { return base.ZCount(setId, fromScore, toScore); } public double GetItemScoreInSortedSet(string setId, string value) { return base.ZScore(setId, value.ToUtf8Bytes()); } public long StoreIntersectFromSortedSets(string intoSetId, params string[] setIds) { return base.ZInterStore(intoSetId, setIds); } public long StoreUnionFromSortedSets(string intoSetId, params string[] setIds) { return base.ZUnionStore(intoSetId, setIds); } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using Quartz.Util; namespace Quartz.Impl.Triggers { /// <summary> /// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" /> /// based upon repeating calendar time intervals. /// </summary> /// <remarks> /// The trigger will fire every N (see <see cref="RepeatInterval" />) units of calendar time /// (see <see cref="RepeatIntervalUnit" />) as specified in the trigger's definition. /// This trigger can achieve schedules that are not possible with <see cref="ISimpleTrigger" /> (e.g /// because months are not a fixed number of seconds) or <see cref="ICronTrigger" /> (e.g. because /// "every 5 months" is not an even divisor of 12). /// <para> /// If you use an interval unit of <see cref="IntervalUnit.Month" /> then care should be taken when setting /// a <see cref="StartTimeUtc" /> value that is on a day near the end of the month. For example, /// if you choose a start time that occurs on January 31st, and have a trigger with unit /// <see cref="IntervalUnit.Month" /> and interval 1, then the next fire time will be February 28th, /// and the next time after that will be March 28th - and essentially each subsequent firing will /// occur on the 28th of the month, even if a 31st day exists. If you want a trigger that always /// fires on the last day of the month - regardless of the number of days in the month, /// you should use <see cref="ICronTrigger" />. /// </para> /// </remarks> /// <see cref="ITrigger" /> /// <see cref="ICronTrigger" /> /// <see cref="ISimpleTrigger" /> /// <see cref="IDailyTimeIntervalTrigger" /> /// <since>2.0</since> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class CalendarIntervalTriggerImpl : AbstractTrigger, ICalendarIntervalTrigger { private static readonly int YearToGiveupSchedulingAt = DateTime.Now.AddYears(100).Year; private DateTimeOffset startTime; private DateTimeOffset? endTime; private DateTimeOffset? nextFireTimeUtc; private DateTimeOffset? previousFireTimeUtc; private int repeatInterval; private IntervalUnit repeatIntervalUnit = IntervalUnit.Day; private TimeZoneInfo timeZone; private bool preserveHourOfDayAcrossDaylightSavings; // false is backward-compatible with behavior private bool skipDayIfHourDoesNotExist; private int timesTriggered; private bool complete = false; /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> with no settings. /// </summary> public CalendarIntervalTriggerImpl() { } /// <summary> /// Create a <see cref="CalendarIntervalTriggerImpl" /> that will occur immediately, and /// repeat at the the given interval. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, IntervalUnit intervalUnit, int repeatInterval) : this(name, null, intervalUnit, repeatInterval) { } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur immediately, and /// repeat at the the given interval /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="group">Group for the trigger instance.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, string group, IntervalUnit intervalUnit, int repeatInterval) : this(name, group, SystemTime.UtcNow(), null, intervalUnit, repeatInterval) { } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur at the given time, /// and repeat at the the given interval until the given end time. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param> /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, DateTimeOffset startTimeUtc, DateTimeOffset? endTimeUtc, IntervalUnit intervalUnit, int repeatInterval) : this(name, null, startTimeUtc, endTimeUtc, intervalUnit, repeatInterval) { } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur at the given time, /// and repeat at the the given interval until the given end time. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="group">Group for the trigger instance.</param> /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param> /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, string group, DateTimeOffset startTimeUtc, DateTimeOffset? endTimeUtc, IntervalUnit intervalUnit, int repeatInterval) : base(name, group) { StartTimeUtc = startTimeUtc; EndTimeUtc = endTimeUtc; RepeatIntervalUnit = (intervalUnit); RepeatInterval = (repeatInterval); } /// <summary> /// Create a <see cref="ICalendarIntervalTrigger" /> that will occur at the given time, /// and repeat at the the given interval until the given end time. /// </summary> /// <param name="name">Name for the trigger instance.</param> /// <param name="group">Group for the trigger instance.</param> /// <param name="jobName">Name of the associated job.</param> /// <param name="jobGroup">Group of the associated job.</param> /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param> /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param> /// <param name="intervalUnit">The repeat interval unit (minutes, days, months, etc).</param> /// <param name="repeatInterval">The number of milliseconds to pause between the repeat firing.</param> public CalendarIntervalTriggerImpl(string name, string group, string jobName, string jobGroup, DateTimeOffset startTimeUtc, DateTimeOffset? endTimeUtc, IntervalUnit intervalUnit, int repeatInterval) : base(name, group, jobName, jobGroup) { StartTimeUtc = startTimeUtc; EndTimeUtc = endTimeUtc; RepeatIntervalUnit = intervalUnit; RepeatInterval = repeatInterval; } /// <summary> /// Get the time at which the <see cref="CalendarIntervalTriggerImpl" /> should occur. /// </summary> public override DateTimeOffset StartTimeUtc { get { if (startTime == DateTimeOffset.MinValue) { startTime = SystemTime.UtcNow(); } return startTime; } set { if (value == DateTimeOffset.MinValue) { throw new ArgumentException("Start time cannot be DateTimeOffset.MinValue"); } DateTimeOffset? eTime = EndTimeUtc; if (eTime != null && eTime < value) { throw new ArgumentException("End time cannot be before start time"); } startTime = value; } } /// <summary> /// Tells whether this Trigger instance can handle events /// in millisecond precision. /// </summary> public override bool HasMillisecondPrecision { get { return true; } } /// <summary> /// Get the time at which the <see cref="ICalendarIntervalTrigger" /> should quit /// repeating. /// </summary> public override DateTimeOffset? EndTimeUtc { get { return endTime; } set { DateTimeOffset sTime = StartTimeUtc; if (value != null && sTime > value) { throw new ArgumentException("End time cannot be before start time"); } endTime = value; } } /// <summary> /// Get or set the interval unit - the time unit on with the interval applies. /// </summary> public IntervalUnit RepeatIntervalUnit { get { return repeatIntervalUnit; } set { this.repeatIntervalUnit = value; } } /// <summary> /// Get the the time interval that will be added to the <see cref="ICalendarIntervalTrigger" />'s /// fire time (in the set repeat interval unit) in order to calculate the time of the /// next trigger repeat. /// </summary> public int RepeatInterval { get { return repeatInterval; } set { if (value < 0) { throw new ArgumentException("Repeat interval must be >= 1"); } repeatInterval = value; } } public TimeZoneInfo TimeZone { get { if (timeZone == null) { timeZone = TimeZoneInfo.Local; } return timeZone; } set { timeZone = value; } } ///<summary> /// If intervals are a day or greater, this property (set to true) will /// cause the firing of the trigger to always occur at the same time of day, /// (the time of day of the startTime) regardless of daylight saving time /// transitions. Default value is false. /// </summary> /// <remarks> /// <para> /// For example, without the property set, your trigger may have a start /// time of 9:00 am on March 1st, and a repeat interval of 2 days. But /// after the daylight saving transition occurs, the trigger may start /// firing at 8:00 am every other day. /// </para> /// <para> /// If however, the time of day does not exist on a given day to fire /// (e.g. 2:00 am in the United States on the days of daylight saving /// transition), the trigger will go ahead and fire one hour off on /// that day, and then resume the normal hour on other days. If /// you wish for the trigger to never fire at the "wrong" hour, then /// you should set the property skipDayIfHourDoesNotExist. /// </para> ///</remarks> /// <seealso cref="ICalendarIntervalTrigger.SkipDayIfHourDoesNotExist"/> /// <seealso cref="ICalendarIntervalTrigger.TimeZone"/> /// <seealso cref="TriggerBuilder.StartAt"/> public bool PreserveHourOfDayAcrossDaylightSavings { get { return preserveHourOfDayAcrossDaylightSavings; } set { preserveHourOfDayAcrossDaylightSavings = value; } } /// <summary> /// If intervals are a day or greater, and /// preserveHourOfDayAcrossDaylightSavings property is set to true, and the /// hour of the day does not exist on a given day for which the trigger /// would fire, the day will be skipped and the trigger advanced a second /// interval if this property is set to true. Defaults to false. /// </summary> /// <remarks> /// <b>CAUTION!</b> If you enable this property, and your hour of day happens /// to be that of daylight savings transition (e.g. 2:00 am in the United /// States) and the trigger's interval would have had the trigger fire on /// that day, then you may actually completely miss a firing on the day of /// transition if that hour of day does not exist on that day! In such a /// case the next fire time of the trigger will be computed as double (if /// the interval is 2 days, then a span of 4 days between firings will /// occur). /// </remarks> /// <seealso cref="ICalendarIntervalTrigger.PreserveHourOfDayAcrossDaylightSavings"/> public bool SkipDayIfHourDoesNotExist { get { return skipDayIfHourDoesNotExist; } set { skipDayIfHourDoesNotExist = value; } } /// <summary> /// Get the number of times the <see cref="ICalendarIntervalTrigger" /> has already fired. /// </summary> public int TimesTriggered { get { return timesTriggered; } set { this.timesTriggered = value; } } /// <summary> /// Validates the misfire instruction. /// </summary> /// <param name="misfireInstruction">The misfire instruction.</param> /// <returns></returns> protected override bool ValidateMisfireInstruction(int misfireInstruction) { if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy) { return false; } if (misfireInstruction > Quartz.MisfireInstruction.CalendarIntervalTrigger.DoNothing) { return false; } return true; } /// <summary> /// Updates the <see cref="ICalendarIntervalTrigger" />'s state based on the /// MisfireInstruction.XXX that was selected when the <see cref="ICalendarIntervalTrigger" /> /// was created. /// </summary> /// <remarks> /// If the misfire instruction is set to <see cref="MisfireInstruction.SmartPolicy" />, /// then the following scheme will be used: /// <ul> /// <li>The instruction will be interpreted as <see cref="MisfireInstruction.CalendarIntervalTrigger.FireOnceNow" /></li> /// </ul> /// </remarks> public override void UpdateAfterMisfire(ICalendar cal) { int instr = MisfireInstruction; if (instr == Quartz.MisfireInstruction.IgnoreMisfirePolicy) { return; } if (instr == Quartz.MisfireInstruction.SmartPolicy) { instr = Quartz.MisfireInstruction.CalendarIntervalTrigger.FireOnceNow; } if (instr == Quartz.MisfireInstruction.CalendarIntervalTrigger.DoNothing) { DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow()); while (newFireTime != null && cal != null && !cal.IsTimeIncluded(newFireTime.Value)) { newFireTime = GetFireTimeAfter(newFireTime); } SetNextFireTimeUtc(newFireTime); } else if (instr == Quartz.MisfireInstruction.CalendarIntervalTrigger.FireOnceNow) { // fire once now... SetNextFireTimeUtc(SystemTime.UtcNow()); // the new fire time afterward will magically preserve the original // time of day for firing for day/week/month interval triggers, // because of the way getFireTimeAfter() works - in its always restarting // computation from the start time. } } /// <summary> /// This method should not be used by the Quartz client. /// <para> /// Called when the <see cref="IScheduler" /> has decided to 'fire' /// the trigger (Execute the associated <see cref="IJob" />), in order to /// give the <see cref="ITrigger" /> a chance to update itself for its next /// triggering (if any). /// </para> /// </summary> /// <seealso cref="JobExecutionException" /> public override void Triggered(ICalendar calendar) { timesTriggered++; previousFireTimeUtc = nextFireTimeUtc; nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); while (nextFireTimeUtc != null && calendar != null && !calendar.IsTimeIncluded(nextFireTimeUtc.Value)) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); if (nextFireTimeUtc == null) { break; } //avoid infinite loop if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt) { nextFireTimeUtc = null; } } } /// <summary> /// This method should not be used by the Quartz client. /// <para> /// The implementation should update the <see cref="ITrigger" />'s state /// based on the given new version of the associated <see cref="ICalendar" /> /// (the state should be updated so that it's next fire time is appropriate /// given the Calendar's new settings). /// </para> /// </summary> /// <param name="calendar"> </param> /// <param name="misfireThreshold"></param> public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold) { nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc); if (nextFireTimeUtc == null || calendar == null) { return; } DateTimeOffset now = SystemTime.UtcNow(); while (nextFireTimeUtc != null && !calendar.IsTimeIncluded(nextFireTimeUtc.Value)) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); if (nextFireTimeUtc == null) { break; } //avoid infinite loop if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt) { nextFireTimeUtc = null; } if (nextFireTimeUtc != null && nextFireTimeUtc < now) { TimeSpan diff = now - nextFireTimeUtc.Value; if (diff >= misfireThreshold) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); } } } } /// <summary> /// This method should not be used by the Quartz client. /// </summary> /// <remarks> /// <para> /// Called by the scheduler at the time a <see cref="ITrigger" /> is first /// added to the scheduler, in order to have the <see cref="ITrigger" /> /// compute its first fire time, based on any associated calendar. /// </para> /// /// <para> /// After this method has been called, <see cref="ITrigger.GetNextFireTimeUtc" /> /// should return a valid answer. /// </para> /// </remarks> /// <returns> /// The first time at which the <see cref="ITrigger" /> will be fired /// by the scheduler, which is also the same value <see cref="ITrigger.GetNextFireTimeUtc" /> /// will return (until after the first firing of the <see cref="ITrigger" />). /// </returns> public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar calendar) { nextFireTimeUtc = StartTimeUtc; while (nextFireTimeUtc != null && calendar != null && !calendar.IsTimeIncluded(nextFireTimeUtc.Value)) { nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc); if (nextFireTimeUtc == null) { break; } //avoid infinite loop if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt) { return null; } } return nextFireTimeUtc; } /// <summary> /// Returns the next time at which the <see cref="ITrigger" /> is scheduled to fire. If /// the trigger will not fire again, <see langword="null" /> will be returned. Note that /// the time returned can possibly be in the past, if the time that was computed /// for the trigger to next fire has already arrived, but the scheduler has not yet /// been able to fire the trigger (which would likely be due to lack of resources /// e.g. threads). /// </summary> ///<remarks> /// The value returned is not guaranteed to be valid until after the <see cref="ITrigger" /> /// has been added to the scheduler. /// </remarks> /// <returns></returns> public override DateTimeOffset? GetNextFireTimeUtc() { return nextFireTimeUtc; } /// <summary> /// Returns the previous time at which the <see cref="ICalendarIntervalTrigger" /> fired. /// If the trigger has not yet fired, <see langword="null" /> will be returned. /// </summary> public override DateTimeOffset? GetPreviousFireTimeUtc() { return previousFireTimeUtc; } public override void SetNextFireTimeUtc(DateTimeOffset? value) { nextFireTimeUtc = value; } public override void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTimeUtc) { this.previousFireTimeUtc = previousFireTimeUtc; } /// <summary> /// Returns the next time at which the <see cref="ICalendarIntervalTrigger" /> will fire, /// after the given time. If the trigger will not fire after the given time, /// <see langword="null" /> will be returned. /// </summary> public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTime) { return GetFireTimeAfter(afterTime, false); } protected DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTime, bool ignoreEndTime) { if (complete) { return null; } // increment afterTime by a second, so that we are // comparing against a time after it! if (afterTime == null) { afterTime = SystemTime.UtcNow().AddSeconds(1); } else { afterTime = afterTime.Value.AddSeconds(1); } DateTimeOffset startMillis = StartTimeUtc; DateTimeOffset afterMillis = afterTime.Value; DateTimeOffset endMillis = (EndTimeUtc == null) ? DateTimeOffset.MaxValue : EndTimeUtc.Value; if (!ignoreEndTime && (endMillis <= afterMillis)) { return null; } if (afterMillis < startMillis) { return startMillis; } long secondsAfterStart = (long) (afterMillis - startMillis).TotalSeconds; DateTimeOffset? time = null; long repeatLong = RepeatInterval; DateTimeOffset sTime = StartTimeUtc; if (timeZone != null) { sTime = TimeZoneUtil.ConvertTime(sTime, timeZone); } if (RepeatIntervalUnit == IntervalUnit.Second) { long jumpCount = secondsAfterStart/repeatLong; if (secondsAfterStart%repeatLong != 0) { jumpCount++; } time = sTime.AddSeconds(RepeatInterval*(int) jumpCount); } else if (RepeatIntervalUnit == IntervalUnit.Minute) { long jumpCount = secondsAfterStart/(repeatLong*60L); if (secondsAfterStart%(repeatLong*60L) != 0) { jumpCount++; } time = sTime.AddMinutes(RepeatInterval*(int) jumpCount); } else if (RepeatIntervalUnit == IntervalUnit.Hour) { long jumpCount = secondsAfterStart/(repeatLong*60L*60L); if (secondsAfterStart%(repeatLong*60L*60L) != 0) { jumpCount++; } time = sTime.AddHours(RepeatInterval*(int) jumpCount); } else { // intervals a day or greater ... int initialHourOfDay = sTime.Hour; if (RepeatIntervalUnit == IntervalUnit.Day) { // Because intervals greater than an hour have an non-fixed number // of seconds in them (due to daylight savings, variation number of // days in each month, leap year, etc. ) we can't jump forward an // exact number of seconds to calculate the fire time as we can // with the second, minute and hour intervals. But, rather // than slowly crawling our way there by iteratively adding the // increment to the start time until we reach the "after time", // we can first make a big leap most of the way there... long jumpCount = secondsAfterStart/(repeatLong*24L*60L*60L); // if we need to make a big jump, jump most of the way there, // but not all the way because in some cases we may over-shoot or under-shoot if (jumpCount > 20) { if (jumpCount < 50) { jumpCount = (long) (jumpCount*0.80); } else if (jumpCount < 500) { jumpCount = (long) (jumpCount*0.90); } else { jumpCount = (long) (jumpCount*0.95); } sTime = sTime.AddDays(RepeatInterval*jumpCount); } // now baby-step the rest of the way there... while (sTime.UtcDateTime < afterTime.Value.UtcDateTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval); MakeHourAdjustmentIfNeeded(ref sTime, initialHourOfDay); //hours can shift due to DST } while (DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval); } time = sTime; } else if (RepeatIntervalUnit == IntervalUnit.Week) { // Because intervals greater than an hour have an non-fixed number // of seconds in them (due to daylight savings, variation number of // days in each month, leap year, etc. ) we can't jump forward an // exact number of seconds to calculate the fire time as we can // with the second, minute and hour intervals. But, rather // than slowly crawling our way there by iteratively adding the // increment to the start time until we reach the "after time", // we can first make a big leap most of the way there... long jumpCount = secondsAfterStart/(repeatLong*7L*24L*60L*60L); // if we need to make a big jump, jump most of the way there, // but not all the way because in some cases we may over-shoot or under-shoot if (jumpCount > 20) { if (jumpCount < 50) { jumpCount = (long) (jumpCount*0.80); } else if (jumpCount < 500) { jumpCount = (long) (jumpCount*0.90); } else { jumpCount = (long) (jumpCount*0.95); } sTime = sTime.AddDays((int) (RepeatInterval*jumpCount*7)); } while (sTime.UtcDateTime < afterTime.Value.UtcDateTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval*7); MakeHourAdjustmentIfNeeded(ref sTime, initialHourOfDay); //hours can shift due to DST } while (DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddDays(RepeatInterval*7); } time = sTime; } else if (RepeatIntervalUnit == IntervalUnit.Month) { // because of the large variation in size of months, and // because months are already large blocks of time, we will // just advance via brute-force iteration. while (sTime.UtcDateTime < afterTime.Value.UtcDateTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddMonths(RepeatInterval); MakeHourAdjustmentIfNeeded(ref sTime, initialHourOfDay); //hours can shift due to DST } while (DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddMonths(RepeatInterval); } time = sTime; } else if (RepeatIntervalUnit == IntervalUnit.Year) { while (sTime.UtcDateTime < afterTime.Value.UtcDateTime && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddYears(RepeatInterval); MakeHourAdjustmentIfNeeded(ref sTime, initialHourOfDay); //hours can shift due to DST } while (DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref sTime, initialHourOfDay) && sTime.Year < YearToGiveupSchedulingAt) { sTime = sTime.AddYears(RepeatInterval); } time = sTime; } } // case of interval of a day or greater if (!ignoreEndTime && endMillis <= time) { return null; } sTime = TimeZoneUtil.ConvertTime(sTime, this.TimeZone); //apply the timezone before we return the time. return time; } private bool DaylightSavingHourShiftOccurredAndAdvanceNeeded(ref DateTimeOffset newTime, int initialHourOfDay) { //need to apply timezone again to properly check if initialHourOfDay has changed. DateTimeOffset toCheck = TimeZoneUtil.ConvertTime(newTime, this.TimeZone); if (PreserveHourOfDayAcrossDaylightSavings && toCheck.Hour != initialHourOfDay) { //first apply the date, and then find the proper timezone offset newTime = new DateTimeOffset(newTime.Year, newTime.Month, newTime.Day, initialHourOfDay, newTime.Minute, newTime.Second, newTime.Millisecond, TimeSpan.Zero); newTime = new DateTimeOffset(newTime.DateTime, this.TimeZone.GetUtcOffset(newTime.DateTime)); //TimeZone.IsInvalidTime is true, if this hour does not exist in the specified timezone bool isInvalid = this.TimeZone.IsInvalidTime(newTime.DateTime); if (isInvalid && skipDayIfHourDoesNotExist) { return skipDayIfHourDoesNotExist; } else { //don't skip this day, instead find closest valid time by adding minutes. while (this.TimeZone.IsInvalidTime(newTime.DateTime)) { newTime = newTime.AddMinutes(1); } //apply proper offset for the adjusted time newTime = new DateTimeOffset(newTime.DateTime, this.TimeZone.GetUtcOffset(newTime.DateTime)); } } return false; } private void MakeHourAdjustmentIfNeeded(ref DateTimeOffset sTime, int initialHourOfDay) { //this method was made to adjust the time if a DST occurred, this is to stay consistent with the time //we are checking against, which is the afterTime. There were problems the occurred when the DST adjustment //took the time an hour back, leading to the times were not being adjusted properly. //avoid shifts in day, otherwise this will cause an infinite loop in the code. int initalYear = sTime.Year; int initalMonth = sTime.Month; int initialDay = sTime.Day; sTime = TimeZoneUtil.ConvertTime(sTime, this.TimeZone); if (PreserveHourOfDayAcrossDaylightSavings && sTime.Hour != initialHourOfDay) { //first apply the date, and then find the proper timezone offset sTime = new DateTimeOffset(initalYear, initalMonth, initialDay, initialHourOfDay, sTime.Minute, sTime.Second, sTime.Millisecond, TimeSpan.Zero); sTime = new DateTimeOffset(sTime.DateTime, this.TimeZone.GetUtcOffset(sTime.DateTime)); } } /// <summary> /// Returns the final time at which the <see cref="ICalendarIntervalTrigger" /> will /// fire, if there is no end time set, null will be returned. /// </summary> /// <value></value> /// <remarks>Note that the return time may be in the past.</remarks> public override DateTimeOffset? FinalFireTimeUtc { get { if (complete || EndTimeUtc == null) { return null; } // back up a second from end time DateTimeOffset? fTime = EndTimeUtc.Value.AddSeconds(-1); // find the next fire time after that fTime = GetFireTimeAfter(fTime, true); // the the trigger fires at the end time, that's it! if (fTime == EndTimeUtc) { return fTime; } // otherwise we have to back up one interval from the fire time after the end time DateTimeOffset lTime = fTime.Value; if (RepeatIntervalUnit == IntervalUnit.Second) { lTime = lTime.AddSeconds(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Minute) { lTime = lTime.AddMinutes(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Hour) { lTime = lTime.AddHours(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Day) { lTime = lTime.AddDays(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Week) { lTime = lTime.AddDays(-1*RepeatInterval*7); } else if (RepeatIntervalUnit == IntervalUnit.Month) { lTime = lTime.AddMonths(-1*RepeatInterval); } else if (RepeatIntervalUnit == IntervalUnit.Year) { lTime = lTime.AddYears(-1*RepeatInterval); } return lTime; } } /// <summary> /// Determines whether or not the <see cref="ICalendarIntervalTrigger" /> will occur /// again. /// </summary> /// <returns></returns> public override bool GetMayFireAgain() { return (GetNextFireTimeUtc() != null); } /// <summary> /// Validates whether the properties of the <see cref="IJobDetail" /> are /// valid for submission into a <see cref="IScheduler" />. /// </summary> public override void Validate() { base.Validate(); if (repeatIntervalUnit == IntervalUnit.Millisecond) { throw new SchedulerException("Invalid repeat IntervalUnit (must be Second, Minute, Hour, Day, Month, Week or Year)."); } if (repeatInterval < 1) { throw new SchedulerException("Repeat Interval cannot be zero."); } } public override IScheduleBuilder GetScheduleBuilder() { CalendarIntervalScheduleBuilder cb = CalendarIntervalScheduleBuilder.Create() .WithInterval(RepeatInterval, RepeatIntervalUnit) .InTimeZone(TimeZone) .PreserveHourOfDayAcrossDaylightSavings(PreserveHourOfDayAcrossDaylightSavings) .SkipDayIfHourDoesNotExist(SkipDayIfHourDoesNotExist); switch (MisfireInstruction) { case Quartz.MisfireInstruction.CalendarIntervalTrigger.DoNothing: cb.WithMisfireHandlingInstructionDoNothing(); break; case Quartz.MisfireInstruction.CalendarIntervalTrigger.FireOnceNow: cb.WithMisfireHandlingInstructionFireAndProceed(); break; } return cb; } public override bool HasAdditionalProperties { get { return false; } } } }
// Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.IO; #if NET40 using System.Numerics; #endif using System.Runtime.Serialization; using System.Text; using System.Xml; using OpenGamingLibrary.Json.Converters; using OpenGamingLibrary.Json.Linq; using OpenGamingLibrary.Json.Serialization; using OpenGamingLibrary.Json.Test.Serialization; using OpenGamingLibrary.Json.Test.TestObjects; using OpenGamingLibrary.Json.Utilities; using OpenGamingLibrary.Xunit.Extensions; using Xunit; namespace OpenGamingLibrary.Json.Test { public class JsonConvertTest : TestFixtureBase { [Fact] public void DefaultSettings() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }); StringAssert.Equal(@"{ ""test"": [ 1, 2, 3 ] }", json); } finally { JsonConvert.DefaultSettings = null; } } public class NameTableTestClass { public string Value { get; set; } } public class NameTableTestClassConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { reader.Read(); reader.Read(); JsonTextReader jsonTextReader = (JsonTextReader)reader; Assert.NotNull(jsonTextReader.NameTable); string s = serializer.Deserialize<string>(reader); Assert.Equal("hi", s); Assert.NotNull(jsonTextReader.NameTable); NameTableTestClass o = new NameTableTestClass { Value = s }; return o; } public override bool CanConvert(Type objectType) { return objectType == typeof(NameTableTestClass); } } [Fact] public void NameTableTest() { StringReader sr = new StringReader("{'property':'hi'}"); JsonTextReader jsonTextReader = new JsonTextReader(sr); Assert.Null(jsonTextReader.NameTable); JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new NameTableTestClassConverter()); NameTableTestClass o = serializer.Deserialize<NameTableTestClass>(jsonTextReader); Assert.Null(jsonTextReader.NameTable); Assert.Equal("hi", o.Value); } [Fact] public void DefaultSettings_Example() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }; Employee e = new Employee { FirstName = "Eric", LastName = "Example", BirthDate = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc), Department = "IT", JobTitle = "Web Dude" }; string json = JsonConvert.SerializeObject(e); // { // "firstName": "Eric", // "lastName": "Example", // "birthDate": "1980-04-20T00:00:00Z", // "department": "IT", // "jobTitle": "Web Dude" // } StringAssert.Equal(@"{ ""firstName"": ""Eric"", ""lastName"": ""Example"", ""birthDate"": ""1980-04-20T00:00:00Z"", ""department"": ""IT"", ""jobTitle"": ""Web Dude"" }", json); } finally { JsonConvert.DefaultSettings = null; } } [Fact] public void DefaultSettings_Override() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; string json = JsonConvert.SerializeObject(new { test = new[] { 1, 2, 3 } }, new JsonSerializerSettings { Formatting = Formatting.None }); Assert.Equal(@"{""test"":[1,2,3]}", json); } finally { JsonConvert.DefaultSettings = null; } } [Fact] public void DefaultSettings_Override_JsonConverterOrder() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented, Converters = { new IsoDateTimeConverter { DateTimeFormat = "yyyy" } } }; string json = JsonConvert.SerializeObject(new[] { new DateTime(2000, 12, 12, 4, 2, 4, DateTimeKind.Utc) }, new JsonSerializerSettings { Formatting = Formatting.None, Converters = { // should take precedence new JavaScriptDateTimeConverter(), new IsoDateTimeConverter { DateTimeFormat = "dd" } } }); Assert.Equal(@"[new Date(976593724000)]", json); } finally { JsonConvert.DefaultSettings = null; } } [Fact] public void DefaultSettings_Create() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; IList<int> l = new List<int> { 1, 2, 3 }; StringWriter sw = new StringWriter(); JsonSerializer serializer = JsonSerializer.CreateDefault(); serializer.Serialize(sw, l); StringAssert.Equal(@"[ 1, 2, 3 ]", sw.ToString()); sw = new StringWriter(); serializer.Formatting = Formatting.None; serializer.Serialize(sw, l); Assert.Equal(@"[1,2,3]", sw.ToString()); sw = new StringWriter(); serializer = new JsonSerializer(); serializer.Serialize(sw, l); Assert.Equal(@"[1,2,3]", sw.ToString()); sw = new StringWriter(); serializer = JsonSerializer.Create(); serializer.Serialize(sw, l); Assert.Equal(@"[1,2,3]", sw.ToString()); } finally { JsonConvert.DefaultSettings = null; } } [Fact] public void DefaultSettings_CreateWithSettings() { try { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; IList<int> l = new List<int> { 1, 2, 3 }; StringWriter sw = new StringWriter(); JsonSerializer serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = { new IntConverter() } }); serializer.Serialize(sw, l); StringAssert.Equal(@"[ 2, 4, 6 ]", sw.ToString()); sw = new StringWriter(); serializer.Converters.Clear(); serializer.Serialize(sw, l); StringAssert.Equal(@"[ 1, 2, 3 ]", sw.ToString()); sw = new StringWriter(); serializer = JsonSerializer.Create(new JsonSerializerSettings { Formatting = Formatting.Indented }); serializer.Serialize(sw, l); StringAssert.Equal(@"[ 1, 2, 3 ]", sw.ToString()); } finally { JsonConvert.DefaultSettings = null; } } public class IntConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { int i = (int)value; writer.WriteValue(i * 2); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { return objectType == typeof(int); } } [Fact] public void DeserializeObject_EmptyString() { object result = JsonConvert.DeserializeObject(string.Empty); Assert.Null(result); } [Fact] public void DeserializeObject_Integer() { object result = JsonConvert.DeserializeObject("1"); Assert.Equal(1L, result); } [Fact] public void DeserializeObject_Integer_EmptyString() { int? value = JsonConvert.DeserializeObject<int?>(""); Assert.Null(value); } [Fact] public void DeserializeObject_Decimal_EmptyString() { decimal? value = JsonConvert.DeserializeObject<decimal?>(""); Assert.Null(value); } [Fact] public void DeserializeObject_DateTime_EmptyString() { DateTime? value = JsonConvert.DeserializeObject<DateTime?>(""); Assert.Null(value); } [Fact] public void EscapeJavaScriptString() { string result; result = JavaScriptUtils.ToEscapedJavaScriptString("How now brown cow?", '"', true); Assert.Equal(@"""How now brown cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("How now 'brown' cow?", '"', true); Assert.Equal(@"""How now 'brown' cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("How now <brown> cow?", '"', true); Assert.Equal(@"""How now <brown> cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("How \r\nnow brown cow?", '"', true); Assert.Equal(@"""How \r\nnow brown cow?""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007", '"', true); Assert.Equal(@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013", '"', true); Assert.Equal(@"""\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013""", result); result = JavaScriptUtils.ToEscapedJavaScriptString( "\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f ", '"', true); Assert.Equal(@"""\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f """, result); result = JavaScriptUtils.ToEscapedJavaScriptString( "!\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]", '"', true); Assert.Equal(@"""!\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("^_`abcdefghijklmnopqrstuvwxyz{|}~", '"', true); Assert.Equal(@"""^_`abcdefghijklmnopqrstuvwxyz{|}~""", result); string data = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; string expected = @"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""; result = JavaScriptUtils.ToEscapedJavaScriptString(data, '"', true); Assert.Equal(expected, result); result = JavaScriptUtils.ToEscapedJavaScriptString("Fred's cat.", '\'', true); Assert.Equal(result, @"'Fred\'s cat.'"); result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are you gentlemen?"" said Cats.", '"', true); Assert.Equal(result, @"""\""How are you gentlemen?\"" said Cats."""); result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are' you gentlemen?"" said Cats.", '"', true); Assert.Equal(result, @"""\""How are' you gentlemen?\"" said Cats."""); result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true); Assert.Equal(result, @"'Fred\'s ""cat"".'"); result = JavaScriptUtils.ToEscapedJavaScriptString("\u001farray\u003caddress", '"', true); Assert.Equal(result, @"""\u001farray<address"""); } [Fact] public void EscapeJavaScriptString_UnicodeLinefeeds() { string result; result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u0085' + "after", '"', true); Assert.Equal(@"""before\u0085after""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2028' + "after", '"', true); Assert.Equal(@"""before\u2028after""", result); result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2029' + "after", '"', true); Assert.Equal(@"""before\u2029after""", result); } [Fact] public void ToStringInvalid() { AssertException.Throws<ArgumentException>(() => { JsonConvert.ToString(new Version(1, 0)); }); } [Fact] public void GuidToString() { Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D"); string json = JsonConvert.ToString(guid); Assert.Equal(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json); } [Fact] public void EnumToString() { string json = JsonConvert.ToString(StringComparison.CurrentCultureIgnoreCase); Assert.Equal("1", json); } [Fact] public void ObjectToString() { object value; value = 1; Assert.Equal("1", JsonConvert.ToString(value)); value = 1.1; Assert.Equal("1.1", JsonConvert.ToString(value)); value = 1.1m; Assert.Equal("1.1", JsonConvert.ToString(value)); value = (float)1.1; Assert.Equal("1.1", JsonConvert.ToString(value)); value = (short)1; Assert.Equal("1", JsonConvert.ToString(value)); value = (long)1; Assert.Equal("1", JsonConvert.ToString(value)); value = (byte)1; Assert.Equal("1", JsonConvert.ToString(value)); value = (uint)1; Assert.Equal("1", JsonConvert.ToString(value)); value = (ushort)1; Assert.Equal("1", JsonConvert.ToString(value)); value = (sbyte)1; Assert.Equal("1", JsonConvert.ToString(value)); value = (ulong)1; Assert.Equal("1", JsonConvert.ToString(value)); value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc); Assert.Equal(@"""1970-01-01T00:00:00Z""", JsonConvert.ToString(value)); value = new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc); Assert.Equal(@"""\/Date(0)\/""", JsonConvert.ToString((DateTime)value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind)); #if !NET20 value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero); Assert.Equal(@"""1970-01-01T00:00:00+00:00""", JsonConvert.ToString(value)); value = new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero); Assert.Equal(@"""\/Date(0+0000)\/""", JsonConvert.ToString((DateTimeOffset)value, DateFormatHandling.MicrosoftDateFormat)); #endif value = null; Assert.Equal("null", JsonConvert.ToString(value)); #if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40) value = DBNull.Value; Assert.Equal("null", JsonConvert.ToString(value)); #endif value = "I am a string"; Assert.Equal(@"""I am a string""", JsonConvert.ToString(value)); value = true; Assert.Equal("true", JsonConvert.ToString(value)); value = 'c'; Assert.Equal(@"""c""", JsonConvert.ToString(value)); } [Fact] public void TestInvalidStrings() { AssertException.Throws<JsonReaderException>(() => { string orig = @"this is a string ""that has quotes"" "; string serialized = JsonConvert.SerializeObject(orig); // *** Make string invalid by stripping \" \" serialized = serialized.Replace(@"\""", "\""); JsonConvert.DeserializeObject<string>(serialized); }); } [Fact] public void DeserializeValueObjects() { int i = JsonConvert.DeserializeObject<int>("1"); Assert.Equal(1, i); #if !NET20 DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/"""); Assert.Equal(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d); #endif bool b = JsonConvert.DeserializeObject<bool>("true"); Assert.Equal(true, b); object n = JsonConvert.DeserializeObject<object>("null"); Assert.Equal(null, n); object u = JsonConvert.DeserializeObject<object>("undefined"); Assert.Equal(null, u); } [Fact] public void FloatToString() { Assert.Equal("1.1", JsonConvert.ToString(1.1)); Assert.Equal("1.11", JsonConvert.ToString(1.11)); Assert.Equal("1.111", JsonConvert.ToString(1.111)); Assert.Equal("1.1111", JsonConvert.ToString(1.1111)); Assert.Equal("1.11111", JsonConvert.ToString(1.11111)); Assert.Equal("1.111111", JsonConvert.ToString(1.111111)); Assert.Equal("1.0", JsonConvert.ToString(1.0)); Assert.Equal("1.0", JsonConvert.ToString(1d)); Assert.Equal("-1.0", JsonConvert.ToString(-1d)); Assert.Equal("1.01", JsonConvert.ToString(1.01)); Assert.Equal("1.001", JsonConvert.ToString(1.001)); Assert.Equal(JsonConvert.PositiveInfinity, JsonConvert.ToString(Double.PositiveInfinity)); Assert.Equal(JsonConvert.NegativeInfinity, JsonConvert.ToString(Double.NegativeInfinity)); Assert.Equal(JsonConvert.NaN, JsonConvert.ToString(Double.NaN)); } [Fact] public void DecimalToString() { Assert.Equal("1.1", JsonConvert.ToString(1.1m)); Assert.Equal("1.11", JsonConvert.ToString(1.11m)); Assert.Equal("1.111", JsonConvert.ToString(1.111m)); Assert.Equal("1.1111", JsonConvert.ToString(1.1111m)); Assert.Equal("1.11111", JsonConvert.ToString(1.11111m)); Assert.Equal("1.111111", JsonConvert.ToString(1.111111m)); Assert.Equal("1.0", JsonConvert.ToString(1.0m)); Assert.Equal("-1.0", JsonConvert.ToString(-1.0m)); Assert.Equal("-1.0", JsonConvert.ToString(-1m)); Assert.Equal("1.0", JsonConvert.ToString(1m)); Assert.Equal("1.01", JsonConvert.ToString(1.01m)); Assert.Equal("1.001", JsonConvert.ToString(1.001m)); Assert.Equal("79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MaxValue)); Assert.Equal("-79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MinValue)); } [Fact] public void StringEscaping() { string v = "It's a good day\r\n\"sunshine\""; string json = JsonConvert.ToString(v); Assert.Equal(@"""It's a good day\r\n\""sunshine\""""", json); } [Fact] public void ToStringStringEscapeHandling() { string v = "<b>hi " + '\u20AC' + "</b>"; string json = JsonConvert.ToString(v, '"'); Assert.Equal(@"""<b>hi " + '\u20AC' + @"</b>""", json); json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeHtml); Assert.Equal(@"""\u003cb\u003ehi " + '\u20AC' + @"\u003c/b\u003e""", json); json = JsonConvert.ToString(v, '"', StringEscapeHandling.EscapeNonAscii); Assert.Equal(@"""<b>hi \u20ac</b>""", json); } [Fact] public void WriteDateTime() { DateTimeResult result = null; result = TestDateTime("DateTime Max", DateTime.MaxValue); Assert.Equal("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip); Assert.Equal("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.Equal("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified); Assert.Equal("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc); Assert.Equal(@"\/Date(253402300799999)\/", result.MsDateRoundtrip); Assert.Equal(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.Equal(@"\/Date(253402300799999)\/", result.MsDateUnspecified); Assert.Equal(@"\/Date(253402300799999)\/", result.MsDateUtc); DateTime year2000local = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local); string localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"); result = TestDateTime("DateTime Local", year2000local); Assert.Equal("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip); Assert.Equal("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.Equal("2000-01-01T01:01:01", result.IsoDateUnspecified); Assert.Equal(localToUtcDate, result.IsoDateUtc); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc); DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local); localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"); result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal); Assert.Equal("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip); Assert.Equal("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.Equal("2000-01-01T01:01:01.999", result.IsoDateUnspecified); Assert.Equal(localToUtcDate, result.IsoDateUtc); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc); DateTime ticksLocal = new DateTime(634663873826822481, DateTimeKind.Local); localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK"); result = TestDateTime("DateTime Local with ticks", ticksLocal); Assert.Equal("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip); Assert.Equal("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.Equal("2012-03-03T16:03:02.6822481", result.IsoDateUnspecified); Assert.Equal(localToUtcDate, result.IsoDateUtc); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc); DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); result = TestDateTime("DateTime Unspecified", year2000Unspecified); Assert.Equal("2000-01-01T01:01:01", result.IsoDateRoundtrip); Assert.Equal("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.Equal("2000-01-01T01:01:01", result.IsoDateUnspecified); Assert.Equal("2000-01-01T01:01:01Z", result.IsoDateUtc); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc); DateTime year2000Utc = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc); string utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss"); result = TestDateTime("DateTime Utc", year2000Utc); Assert.Equal("2000-01-01T01:01:01Z", result.IsoDateRoundtrip); Assert.Equal(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.Equal("2000-01-01T01:01:01", result.IsoDateUnspecified); Assert.Equal("2000-01-01T01:01:01Z", result.IsoDateUtc); Assert.Equal(@"\/Date(946688461000)\/", result.MsDateRoundtrip); Assert.Equal(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.Equal(@"\/Date(946688461000)\/", result.MsDateUtc); DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc); utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss"); result = TestDateTime("DateTime Unix Epoc", unixEpoc); Assert.Equal("1970-01-01T00:00:00Z", result.IsoDateRoundtrip); Assert.Equal(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.Equal("1970-01-01T00:00:00", result.IsoDateUnspecified); Assert.Equal("1970-01-01T00:00:00Z", result.IsoDateUtc); Assert.Equal(@"\/Date(0)\/", result.MsDateRoundtrip); Assert.Equal(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.Equal(@"\/Date(" + DateTimeUtils.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified); Assert.Equal(@"\/Date(0)\/", result.MsDateUtc); result = TestDateTime("DateTime Min", DateTime.MinValue); Assert.Equal("0001-01-01T00:00:00", result.IsoDateRoundtrip); Assert.Equal("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.Equal("0001-01-01T00:00:00", result.IsoDateUnspecified); Assert.Equal("0001-01-01T00:00:00Z", result.IsoDateUtc); Assert.Equal(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip); Assert.Equal(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.Equal(@"\/Date(-62135596800000)\/", result.MsDateUnspecified); Assert.Equal(@"\/Date(-62135596800000)\/", result.MsDateUtc); result = TestDateTime("DateTime Default", default(DateTime)); Assert.Equal("0001-01-01T00:00:00", result.IsoDateRoundtrip); Assert.Equal("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal); Assert.Equal("0001-01-01T00:00:00", result.IsoDateUnspecified); Assert.Equal("0001-01-01T00:00:00Z", result.IsoDateUtc); Assert.Equal(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip); Assert.Equal(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal); Assert.Equal(@"\/Date(-62135596800000)\/", result.MsDateUnspecified); Assert.Equal(@"\/Date(-62135596800000)\/", result.MsDateUtc); result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); Assert.Equal("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip); Assert.Equal(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1))); Assert.Equal("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip); Assert.Equal(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5))); Assert.Equal("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip); Assert.Equal(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13))); Assert.Equal("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip); Assert.Equal(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero)); Assert.Equal("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip); Assert.Equal(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue); Assert.Equal("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip); Assert.Equal(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue); Assert.Equal("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip); Assert.Equal(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip); result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset)); Assert.Equal("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip); Assert.Equal(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip); } public class DateTimeResult { public string IsoDateRoundtrip { get; set; } public string IsoDateLocal { get; set; } public string IsoDateUnspecified { get; set; } public string IsoDateUtc { get; set; } public string MsDateRoundtrip { get; set; } public string MsDateLocal { get; set; } public string MsDateUnspecified { get; set; } public string MsDateUtc { get; set; } } private DateTimeResult TestDateTime<T>(string name, T value) { Console.WriteLine(name); DateTimeResult result = new DateTimeResult(); result.IsoDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); if (value is DateTime) { result.IsoDateLocal = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Local); result.IsoDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Unspecified); result.IsoDateUtc = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Utc); } result.MsDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind); if (value is DateTime) { result.MsDateLocal = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Local); result.MsDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Unspecified); result.MsDateUtc = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Utc); } TestDateTimeFormat(value, new IsoDateTimeConverter()); if (value is DateTime) { Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind)); } else { Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value)); } MemoryStream ms = new MemoryStream(); DataContractSerializer s = new DataContractSerializer(typeof(T)); s.WriteObject(ms, value); string json = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length)); Console.WriteLine(json); Console.WriteLine(); return result; } private static string TestDateTimeFormat<T>(T value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { string date = null; if (value is DateTime) { date = JsonConvert.ToString((DateTime)(object)value, format, timeZoneHandling); } else { date = JsonConvert.ToString((DateTimeOffset)(object)value, format); } Console.WriteLine(format.ToString("g") + "-" + timeZoneHandling.ToString("g") + ": " + date); if (timeZoneHandling == DateTimeZoneHandling.RoundtripKind) { T parsed = JsonConvert.DeserializeObject<T>(date); try { Assert.Equal(value, parsed); } catch (Exception) { long valueTicks = GetTicks(value); long parsedTicks = GetTicks(parsed); valueTicks = (valueTicks / 10000) * 10000; Assert.Equal(valueTicks, parsedTicks); } } return date.Trim('"'); } private static void TestDateTimeFormat<T>(T value, JsonConverter converter) { string date = Write(value, converter); Console.WriteLine(converter.GetType().Name + ": " + date); T parsed = Read<T>(date, converter); try { Assert.Equal(value, parsed); } catch (Exception) { // JavaScript ticks aren't as precise, recheck after rounding long valueTicks = GetTicks(value); long parsedTicks = GetTicks(parsed); valueTicks = (valueTicks / 10000) * 10000; Assert.Equal(valueTicks, parsedTicks); } } public static long GetTicks(object value) { return (value is DateTime) ? ((DateTime)value).Ticks : ((DateTimeOffset)value).Ticks; } public static string Write(object value, JsonConverter converter) { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); converter.WriteJson(writer, value, null); writer.Flush(); return sw.ToString(); } public static T Read<T>(string text, JsonConverter converter) { JsonTextReader reader = new JsonTextReader(new StringReader(text)); reader.ReadAsString(); return (T)converter.ReadJson(reader, typeof(T), null, null); } [Fact] public void SerializeObjectDateTimeZoneHandling() { string json = JsonConvert.SerializeObject( new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified), new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); Assert.Equal(@"""2000-01-01T01:01:01Z""", json); } [Fact] public void DeserializeObject() { string json = @"{ 'Name': 'Bad Boys', 'ReleaseDate': '1995-4-7T00:00:00', 'Genres': [ 'Action', 'Comedy' ] }"; Movie m = JsonConvert.DeserializeObject<Movie>(json); string name = m.Name; // Bad Boys Assert.Equal("Bad Boys", m.Name); } [Fact] public void TestJsonDateTimeOffsetRoundtrip() { var now = DateTimeOffset.Now; var dict = new Dictionary<string, object> { { "foo", now } }; var settings = new JsonSerializerSettings(); settings.DateFormatHandling = DateFormatHandling.IsoDateFormat; settings.DateParseHandling = DateParseHandling.DateTimeOffset; settings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; var json = JsonConvert.SerializeObject(dict, settings); Console.WriteLine(json); var newDict = new Dictionary<string, object>(); JsonConvert.PopulateObject(json, newDict, settings); var date = newDict["foo"]; Assert.Equal(date, now); } [Fact] public void MaximumDateTimeOffsetLength() { DateTimeOffset dt = new DateTimeOffset(2000, 12, 31, 20, 59, 59, new TimeSpan(0, 11, 33, 0, 0)); dt = dt.AddTicks(9999999); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(dt); writer.Flush(); Console.WriteLine(sw.ToString()); Console.WriteLine(sw.ToString().Length); } [Fact] public void MaximumDateTimeLength() { DateTime dt = new DateTime(2000, 12, 31, 20, 59, 59, DateTimeKind.Local); dt = dt.AddTicks(9999999); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(dt); writer.Flush(); Console.WriteLine(sw.ToString()); Console.WriteLine(sw.ToString().Length); } [Fact] public void MaximumDateTimeMicrosoftDateFormatLength() { DateTime dt = DateTime.MaxValue; StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(dt); writer.Flush(); Console.WriteLine(sw.ToString()); Console.WriteLine(sw.ToString().Length); } #if NET40 [Fact] public void IntegerLengthOverflows() { // Maximum javascript number length (in characters) is 380 JObject o = JObject.Parse(@"{""biginteger"":" + new String('9', 380) + "}"); JValue v = (JValue)o["biginteger"]; Assert.Equal(JTokenType.Integer, v.Type); Assert.Equal(typeof(BigInteger), v.Value.GetType()); Assert.Equal(BigInteger.Parse(new String('9', 380)), (BigInteger)v.Value); AssertException.Throws<JsonReaderException>(() => JObject.Parse(@"{""biginteger"":" + new String('9', 381) + "}")); } #endif [Fact] public void ParseIsoDate() { StringReader sr = new StringReader(@"""2014-02-14T14:25:02-13:00"""); JsonReader jsonReader = new JsonTextReader(sr); Assert.True(jsonReader.Read()); Assert.Equal(typeof(DateTime), jsonReader.ValueType); } //[Fact] public void StackOverflowTest() { StringBuilder sb = new StringBuilder(); int depth = 900; for (int i = 0; i < depth; i++) { sb.Append("{'A':"); } // invalid json sb.Append("{***}"); for (int i = 0; i < depth; i++) { sb.Append("}"); } string json = sb.ToString(); JsonSerializer serializer = new JsonSerializer() { }; serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json))); } public class Nest { public Nest A { get; set; } } [Fact] public void ParametersPassedToJsonConverterConstructor() { ClobberMyProperties clobber = new ClobberMyProperties { One = "Red", Two = "Green", Three = "Yellow", Four = "Black" }; string json = JsonConvert.SerializeObject(clobber); Assert.Equal("{\"One\":\"Uno-1-Red\",\"Two\":\"Dos-2-Green\",\"Three\":\"Tres-1337-Yellow\",\"Four\":\"Black\"}", json); } public class ClobberMyProperties { [JsonConverter(typeof(ClobberingJsonConverter), "Uno", 1)] public string One { get; set; } [JsonConverter(typeof(ClobberingJsonConverter), "Dos", 2)] public string Two { get; set; } [JsonConverter(typeof(ClobberingJsonConverter), "Tres")] public string Three { get; set; } public string Four { get; set; } } public class ClobberingJsonConverter : JsonConverter { public string ClobberValueString { get; private set; } public int ClobberValueInt { get; private set; } public ClobberingJsonConverter(string clobberValueString, int clobberValueInt) { ClobberValueString = clobberValueString; ClobberValueInt = clobberValueInt; } public ClobberingJsonConverter(string clobberValueString) : this(clobberValueString, 1337) { } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(ClobberValueString + "-" + ClobberValueInt.ToString() + "-" + value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { return objectType == typeof(string); } } [Fact] public void WrongParametersPassedToJsonConvertConstructorShouldThrow() { IncorrectJsonConvertParameters value = new IncorrectJsonConvertParameters { One = "Boom" }; AssertException.Throws<JsonException>(() => { JsonConvert.SerializeObject(value); }); } public class IncorrectJsonConvertParameters { /// <summary> /// We deliberately use the wrong number/type of arguments for ClobberingJsonConverter to ensure an /// exception is thrown. /// </summary> [JsonConverter(typeof(ClobberingJsonConverter), "Uno", "Blammo")] public string One { get; set; } } [Fact] public void CustomDoubleRounding() { var measurements = new Measurements { Loads = new List<double> { 23283.567554707258, 23224.849899771067, 23062.5, 22846.272519910868, 22594.281246368635 }, Positions = new List<double> { 57.724227689317019, 60.440934405753069, 63.444192925248643, 66.813119113482557, 70.4496501404433 }, Gain = 12345.67895111213 }; string json = JsonConvert.SerializeObject(measurements); Assert.Equal("{\"Positions\":[57.72,60.44,63.44,66.81,70.45],\"Loads\":[23284.0,23225.0,23062.0,22846.0,22594.0],\"Gain\":12345.679}", json); } public class Measurements { [JsonProperty(ItemConverterType = typeof(RoundingJsonConverter))] public List<double> Positions { get; set; } [JsonProperty(ItemConverterType = typeof(RoundingJsonConverter), ItemConverterParameters = new object[] { 0, MidpointRounding.ToEven })] public List<double> Loads { get; set; } [JsonConverter(typeof(RoundingJsonConverter), 4)] public double Gain { get; set; } } public class RoundingJsonConverter : JsonConverter { int _precision; MidpointRounding _rounding; public RoundingJsonConverter() : this(2) { } public RoundingJsonConverter(int precision) : this(precision, MidpointRounding.AwayFromZero) { } public RoundingJsonConverter(int precision, MidpointRounding rounding) { _precision = precision; _rounding = rounding; } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return objectType == typeof(double); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(Math.Round((double)value, _precision, _rounding)); } } } }
// 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 { using System; using System.Reflection; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Globalization; using System.Diagnostics.Contracts; using System.Security; using System.Security.Permissions; [Serializable] [AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple=false)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Attribute))] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Attribute : _Attribute { #region Private Statics #region PropertyInfo private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit) { Contract.Requires(element != null); Contract.Requires(type != null); Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute)); // walk up the hierarchy chain Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit); if (!inherit) return attributes; // create the hashtable that keeps track of inherited types Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11); // create an array list to collect all the requested attibutes List<Attribute> attributeList = new List<Attribute>(); CopyToArrayList(attributeList, attributes, types); //if this is an index we need to get the parameter types to help disambiguate Type[] indexParamTypes = GetIndexParameterTypes(element); PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes); while (baseProp != null) { attributes = GetCustomAttributes(baseProp, type, false); AddAttributesToList(attributeList, attributes, types); baseProp = GetParentDefinition(baseProp, indexParamTypes); } Array array = CreateAttributeArrayHelper(type, attributeList.Count); Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count); return (Attribute[])array; } private static bool InternalIsDefined(PropertyInfo element, Type attributeType, bool inherit) { // walk up the hierarchy chain if (element.IsDefined(attributeType, inherit)) return true; if (inherit) { AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType); if (!usage.Inherited) return false; //if this is an index we need to get the parameter types to help disambiguate Type[] indexParamTypes = GetIndexParameterTypes(element); PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes); while (baseProp != null) { if (baseProp.IsDefined(attributeType, false)) return true; baseProp = GetParentDefinition(baseProp, indexParamTypes); } } return false; } private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters) { Contract.Requires(property != null); // for the current property get the base class of the getter and the setter, they might be different // note that this only works for RuntimeMethodInfo MethodInfo propAccessor = property.GetGetMethod(true); if (propAccessor == null) propAccessor = property.GetSetMethod(true); RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo; if (rtPropAccessor != null) { rtPropAccessor = rtPropAccessor.GetParentDefinition(); if (rtPropAccessor != null) { // There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type. // However, we cannot use that because it doesn't accept null for "types". return rtPropAccessor.DeclaringType.GetProperty( property.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, //will use default binder property.PropertyType, propertyParameters, //used for index properties null); } } return null; } #endregion #region EventInfo private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit) { Contract.Requires(element != null); Contract.Requires(type != null); Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute)); // walk up the hierarchy chain Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit); if (inherit) { // create the hashtable that keeps track of inherited types Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11); // create an array list to collect all the requested attibutes List<Attribute> attributeList = new List<Attribute>(); CopyToArrayList(attributeList, attributes, types); EventInfo baseEvent = GetParentDefinition(element); while (baseEvent != null) { attributes = GetCustomAttributes(baseEvent, type, false); AddAttributesToList(attributeList, attributes, types); baseEvent = GetParentDefinition(baseEvent); } Array array = CreateAttributeArrayHelper(type, attributeList.Count); Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count); return (Attribute[])array; } else return attributes; } private static EventInfo GetParentDefinition(EventInfo ev) { Contract.Requires(ev != null); // note that this only works for RuntimeMethodInfo MethodInfo add = ev.GetAddMethod(true); RuntimeMethodInfo rtAdd = add as RuntimeMethodInfo; if (rtAdd != null) { rtAdd = rtAdd.GetParentDefinition(); if (rtAdd != null) return rtAdd.DeclaringType.GetEvent(ev.Name); } return null; } private static bool InternalIsDefined (EventInfo element, Type attributeType, bool inherit) { Contract.Requires(element != null); // walk up the hierarchy chain if (element.IsDefined(attributeType, inherit)) return true; if (inherit) { AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType); if (!usage.Inherited) return false; EventInfo baseEvent = GetParentDefinition(element); while (baseEvent != null) { if (baseEvent.IsDefined(attributeType, false)) return true; baseEvent = GetParentDefinition(baseEvent); } } return false; } #endregion #region ParameterInfo private static ParameterInfo GetParentDefinition(ParameterInfo param) { Contract.Requires(param != null); // note that this only works for RuntimeMethodInfo RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo; if (rtMethod != null) { rtMethod = rtMethod.GetParentDefinition(); if (rtMethod != null) { // Find the ParameterInfo on this method int position = param.Position; if (position == -1) { return rtMethod.ReturnParameter; } else { ParameterInfo[] parameters = rtMethod.GetParameters(); return parameters[position]; // Point to the correct ParameterInfo of the method } } } return null; } private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit) { Contract.Requires(param != null); // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that // have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes // that are marked inherited from the remainder of the MethodInfo's in the inheritance chain. // For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned. // For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the // class inherits from and return the respective ParameterInfo attributes List<Type> disAllowMultiple = new List<Type>(); Object [] objAttr; if (type == null) type = typeof(Attribute); objAttr = param.GetCustomAttributes(type, false); for (int i =0;i < objAttr.Length;i++) { Type objType = objAttr[i].GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); if (attribUsage.AllowMultiple == false) disAllowMultiple.Add(objType); } // Get all the attributes that have Attribute as the base class Attribute [] ret = null; if (objAttr.Length == 0) ret = CreateAttributeArrayHelper(type,0); else ret = (Attribute[])objAttr; if (param.Member.DeclaringType == null) // This is an interface so we are done. return ret; if (!inherit) return ret; ParameterInfo baseParam = GetParentDefinition(param); while (baseParam != null) { objAttr = baseParam.GetCustomAttributes(type, false); int count = 0; for (int i =0;i < objAttr.Length;i++) { Type objType = objAttr[i].GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false)) { if (attribUsage.AllowMultiple == false) disAllowMultiple.Add(objType); count++; } else objAttr[i] = null; } // Get all the attributes that have Attribute as the base class Attribute [] attributes = CreateAttributeArrayHelper(type,count); count = 0; for (int i =0;i < objAttr.Length;i++) { if (objAttr[i] != null) { attributes[count] = (Attribute)objAttr[i]; count++; } } Attribute [] temp = ret; ret = CreateAttributeArrayHelper(type,temp.Length + count); Array.Copy(temp,ret,temp.Length); int offset = temp.Length; for (int i =0;i < attributes.Length;i++) ret[offset + i] = attributes[i]; baseParam = GetParentDefinition(baseParam); } return ret; } private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit) { Contract.Requires(param != null); Contract.Requires(type != null); // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain. // We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes // that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain. // For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a // Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from. if (param.IsDefined(type, false)) return true; if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done. return false; ParameterInfo baseParam = GetParentDefinition(param); while (baseParam != null) { Object[] objAttr = baseParam.GetCustomAttributes(type, false); for (int i =0; i < objAttr.Length; i++) { Type objType = objAttr[i].GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); if ((objAttr[i] is Attribute) && (attribUsage.Inherited)) return true; } baseParam = GetParentDefinition(baseParam); } return false; } #endregion #region Utility private static void CopyToArrayList(List<Attribute> attributeList,Attribute[] attributes,Dictionary<Type, AttributeUsageAttribute> types) { for (int i = 0; i < attributes.Length; i++) { attributeList.Add(attributes[i]); Type attrType = attributes[i].GetType(); if (!types.ContainsKey(attrType)) types[attrType] = InternalGetAttributeUsage(attrType); } } private static Type[] GetIndexParameterTypes(PropertyInfo element) { ParameterInfo[] indexParams = element.GetIndexParameters(); if (indexParams.Length > 0) { Type[] indexParamTypes = new Type[indexParams.Length]; for (int i = 0; i < indexParams.Length; i++) { indexParamTypes[i] = indexParams[i].ParameterType; } return indexParamTypes; } return Array.Empty<Type>(); } private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types) { for (int i = 0; i < attributes.Length; i++) { Type attrType = attributes[i].GetType(); AttributeUsageAttribute usage = null; types.TryGetValue(attrType, out usage); if (usage == null) { // the type has never been seen before if it's inheritable add it to the list usage = InternalGetAttributeUsage(attrType); types[attrType] = usage; if (usage.Inherited) attributeList.Add(attributes[i]); } else if (usage.Inherited && usage.AllowMultiple) { // we saw this type already add it only if it is inheritable and it does allow multiple attributeList.Add(attributes[i]); } } } private static AttributeUsageAttribute InternalGetAttributeUsage(Type type) { // Check if the custom attributes is Inheritable Object [] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false); if (obj.Length == 1) return (AttributeUsageAttribute)obj[0]; if (obj.Length == 0) return AttributeUsageAttribute.Default; throw new FormatException( Environment.GetResourceString("Format_AttributeUsage", type)); } [System.Security.SecuritySafeCritical] private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount) { return (Attribute[])Array.UnsafeCreateInstance(elementType, elementCount); } #endregion #endregion #region Public Statics #region MemberInfo public static Attribute[] GetCustomAttributes(MemberInfo element, Type type) { return GetCustomAttributes(element, type, true); } public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit) { if (element == null) throw new ArgumentNullException("element"); if (type == null) throw new ArgumentNullException("type"); if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); switch (element.MemberType) { case MemberTypes.Property: return InternalGetCustomAttributes((PropertyInfo)element, type, inherit); case MemberTypes.Event: return InternalGetCustomAttributes((EventInfo)element, type, inherit); default: return element.GetCustomAttributes(type, inherit) as Attribute[]; } } public static Attribute[] GetCustomAttributes(MemberInfo element) { return GetCustomAttributes(element, true); } public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit) { if (element == null) throw new ArgumentNullException("element"); Contract.EndContractBlock(); switch (element.MemberType) { case MemberTypes.Property: return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit); case MemberTypes.Event: return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit); default: return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]; } } public static bool IsDefined(MemberInfo element, Type attributeType) { return IsDefined(element, attributeType, true); } public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit) { // Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk if (element == null) throw new ArgumentNullException("element"); if (attributeType == null) throw new ArgumentNullException("attributeType"); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); switch(element.MemberType) { case MemberTypes.Property: return InternalIsDefined((PropertyInfo)element, attributeType, inherit); case MemberTypes.Event: return InternalIsDefined((EventInfo)element, attributeType, inherit); default: return element.IsDefined(attributeType, inherit); } } public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit) { Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit); if (attrib == null || attrib.Length == 0) return null; if (attrib.Length == 1) return attrib[0]; throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); } #endregion #region ParameterInfo public static Attribute[] GetCustomAttributes(ParameterInfo element) { return GetCustomAttributes(element, true); } public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType) { return (Attribute[])GetCustomAttributes(element, attributeType, true); } public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit) { if (element == null) throw new ArgumentNullException("element"); if (attributeType == null) throw new ArgumentNullException("attributeType"); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); if (element.Member == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element"); Contract.EndContractBlock(); MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[]; return element.GetCustomAttributes(attributeType, inherit) as Attribute[]; } public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit) { if (element == null) throw new ArgumentNullException("element"); if (element.Member == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element"); Contract.EndContractBlock(); MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[]; return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]; } public static bool IsDefined(ParameterInfo element, Type attributeType) { return IsDefined(element, attributeType, true); } public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit) { // Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk if (element == null) throw new ArgumentNullException("element"); if (attributeType == null) throw new ArgumentNullException("attributeType"); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); MemberInfo member = element.Member; switch(member.MemberType) { case MemberTypes.Method: // We need to climb up the member hierarchy return InternalParamIsDefined(element, attributeType, inherit); case MemberTypes.Constructor: return element.IsDefined(attributeType, false); case MemberTypes.Property: return element.IsDefined(attributeType, false); default: Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class"); throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo")); } } public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit); if (attrib == null || attrib.Length == 0) return null; if (attrib.Length == 0) return null; if (attrib.Length == 1) return attrib[0]; throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); } #endregion #region Module public static Attribute[] GetCustomAttributes(Module element, Type attributeType) { return GetCustomAttributes (element, attributeType, true); } public static Attribute[] GetCustomAttributes(Module element) { return GetCustomAttributes(element, true); } public static Attribute[] GetCustomAttributes(Module element, bool inherit) { if (element == null) throw new ArgumentNullException("element"); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit) { if (element == null) throw new ArgumentNullException("element"); if (attributeType == null) throw new ArgumentNullException("attributeType"); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(attributeType, inherit); } public static bool IsDefined(Module element, Type attributeType) { return IsDefined(element, attributeType, false); } public static bool IsDefined(Module element, Type attributeType, bool inherit) { // Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk if (element == null) throw new ArgumentNullException("element"); if (attributeType == null) throw new ArgumentNullException("attributeType"); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); return element.IsDefined(attributeType,false); } public static Attribute GetCustomAttribute(Module element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the Module or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit); if (attrib == null || attrib.Length == 0) return null; if (attrib.Length == 1) return attrib[0]; throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); } #endregion #region Assembly public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType) { return GetCustomAttributes(element, attributeType, true); } public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit) { if (element == null) throw new ArgumentNullException("element"); if (attributeType == null) throw new ArgumentNullException("attributeType"); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(attributeType, inherit); } public static Attribute[] GetCustomAttributes(Assembly element) { return GetCustomAttributes(element, true); } public static Attribute[] GetCustomAttributes(Assembly element, bool inherit) { if (element == null) throw new ArgumentNullException("element"); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } public static bool IsDefined (Assembly element, Type attributeType) { return IsDefined (element, attributeType, true); } public static bool IsDefined (Assembly element, Type attributeType, bool inherit) { // Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk if (element == null) throw new ArgumentNullException("element"); if (attributeType == null) throw new ArgumentNullException("attributeType"); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); Contract.EndContractBlock(); return element.IsDefined(attributeType, false); } public static Attribute GetCustomAttribute(Assembly element, Type attributeType) { return GetCustomAttribute (element, attributeType, true); } public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit); if (attrib == null || attrib.Length == 0) return null; if (attrib.Length == 1) return attrib[0]; throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); } #endregion #endregion #region Constructor protected Attribute() { } #endregion #region Object Overrides [SecuritySafeCritical] public override bool Equals(Object obj) { if (obj == null) return false; RuntimeType thisType = (RuntimeType)this.GetType(); RuntimeType thatType = (RuntimeType)obj.GetType(); if (thatType != thisType) return false; Object thisObj = this; Object thisResult, thatResult; FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < thisFields.Length; i++) { // Visibility check and consistency check are not necessary. thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj); thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj); if (!AreFieldValuesEqual(thisResult, thatResult)) { return false; } } return true; } // Compares values of custom-attribute fields. private static bool AreFieldValuesEqual(Object thisValue, Object thatValue) { if (thisValue == null && thatValue == null) return true; if (thisValue == null || thatValue == null) return false; if (thisValue.GetType().IsArray) { // Ensure both are arrays of the same type. if (!thisValue.GetType().Equals(thatValue.GetType())) { return false; } Array thisValueArray = thisValue as Array; Array thatValueArray = thatValue as Array; if (thisValueArray.Length != thatValueArray.Length) { return false; } // Attributes can only contain single-dimension arrays, so we don't need to worry about // multidimensional arrays. Contract.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1); for (int j = 0; j < thisValueArray.Length; j++) { if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j))) { return false; } } } else { // An object of type Attribute will cause a stack overflow. // However, this should never happen because custom attributes cannot contain values other than // constants, single-dimensional arrays and typeof expressions. Contract.Assert(!(thisValue is Attribute)); if (!thisValue.Equals(thatValue)) return false; } return true; } [SecuritySafeCritical] public override int GetHashCode() { Type type = GetType(); FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Object vThis = null; for (int i = 0; i < fields.Length; i++) { // Visibility check and consistency check are not necessary. Object fieldValue = ((RtFieldInfo)fields[i]).UnsafeGetValue(this); // The hashcode of an array ignores the contents of the array, so it can produce // different hashcodes for arrays with the same contents. // Since we do deep comparisons of arrays in Equals(), this means Equals and GetHashCode will // be inconsistent for arrays. Therefore, we ignore hashes of arrays. if (fieldValue != null && !fieldValue.GetType().IsArray) vThis = fieldValue; if (vThis != null) break; } if (vThis != null) return vThis.GetHashCode(); return type.GetHashCode(); } #endregion #region Public Virtual Members public virtual Object TypeId { get { return GetType(); } } public virtual bool Match(Object obj) { return Equals(obj); } #endregion #region Public Members public virtual bool IsDefaultAttribute() { return false; } #endregion #if !FEATURE_CORECLR void _Attribute.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _Attribute.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _Attribute.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _Attribute.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using OpenMetaverse; using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace OpenSim.Region.Physics.Manager { public interface IMeshingPlugin { IMesher GetMesher(IConfigSource config); string GetName(); } public interface IPhysicsPlugin { void Dispose(); string GetName(); PhysicsScene GetScene(String sceneIdentifier); bool Init(); } /// <summary> /// Description of MyClass. /// </summary> public class PhysicsPluginManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<string, IMeshingPlugin> _MeshPlugins = new Dictionary<string, IMeshingPlugin>(); private Dictionary<string, IPhysicsPlugin> _PhysPlugins = new Dictionary<string, IPhysicsPlugin>(); /// <summary> /// Constructor. /// </summary> public PhysicsPluginManager() { // Load "plugins", that are hard coded and not existing in form of an external lib, and hence always // available IMeshingPlugin plugHard; plugHard = new ZeroMesherPlugin(); _MeshPlugins.Add(plugHard.GetName(), plugHard); m_log.Info("[PHYSICS]: Added meshing engine: " + plugHard.GetName()); } //--- public static void PhysicsPluginMessage(string message, bool isWarning) { if (isWarning) { m_log.Warn("[PHYSICS]: " + message); } else { m_log.Info("[PHYSICS]: " + message); } } /// <summary> /// Get a physics scene for the given physics engine and mesher. /// </summary> /// <param name="physEngineName"></param> /// <param name="meshEngineName"></param> /// <param name="config"></param> /// <returns></returns> public PhysicsScene GetPhysicsScene(string physEngineName, string meshEngineName, IConfigSource config, string regionName, Vector3 regionExtent) { if (String.IsNullOrEmpty(physEngineName)) { return PhysicsScene.Null; } if (String.IsNullOrEmpty(meshEngineName)) { return PhysicsScene.Null; } IMesher meshEngine = null; if (_MeshPlugins.ContainsKey(meshEngineName)) { m_log.Info("[PHYSICS]: creating meshing engine " + meshEngineName); meshEngine = _MeshPlugins[meshEngineName].GetMesher(config); } else { m_log.WarnFormat("[PHYSICS]: couldn't find meshingEngine: {0}", meshEngineName); throw new ArgumentException(String.Format("couldn't find meshingEngine: {0}", meshEngineName)); } if (_PhysPlugins.ContainsKey(physEngineName)) { m_log.Info("[PHYSICS]: creating " + physEngineName); PhysicsScene result = _PhysPlugins[physEngineName].GetScene(regionName); result.Initialise(meshEngine, config, regionExtent); return result; } else { m_log.WarnFormat("[PHYSICS]: couldn't find physicsEngine: {0}", physEngineName); throw new ArgumentException(String.Format("couldn't find physicsEngine: {0}", physEngineName)); } } /// <summary> /// Load all plugins in assemblies at the given path /// </summary> /// <param name="pluginsPath"></param> public void LoadPluginsFromAssemblies(string assembliesPath) { // Walk all assemblies (DLLs effectively) and see if they are home // of a plugin that is of interest for us string[] pluginFiles = Directory.GetFiles(assembliesPath, "*.dll"); for (int i = 0; i < pluginFiles.Length; i++) { LoadPluginsFromAssembly(pluginFiles[i]); } } /// <summary> /// Load plugins from an assembly at the given path /// </summary> /// <param name="assemblyPath"></param> public void LoadPluginsFromAssembly(string assemblyPath) { // TODO / NOTE // The assembly named 'OpenSim.Region.Physics.BasicPhysicsPlugin' was loaded from // 'file:///C:/OpenSim/trunk2/bin/Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll' // using the LoadFrom context. The use of this context can result in unexpected behavior // for serialization, casting and dependency resolution. In almost all cases, it is recommended // that the LoadFrom context be avoided. This can be done by installing assemblies in the // Global Assembly Cache or in the ApplicationBase directory and using Assembly. // Load when explicitly loading assemblies. Assembly pluginAssembly = null; Type[] types = null; try { pluginAssembly = Assembly.LoadFrom(assemblyPath); } catch (Exception ex) { m_log.Error("[PHYSICS]: Failed to load plugin from " + assemblyPath, ex); } if (pluginAssembly != null) { try { types = pluginAssembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath + ": " + ex.LoaderExceptions[0].Message, ex); } catch (Exception ex) { m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath, ex); } if (types != null) { foreach (Type pluginType in types) { if (pluginType.IsPublic) { if (!pluginType.IsAbstract) { Type physTypeInterface = pluginType.GetInterface("IPhysicsPlugin", true); if (physTypeInterface != null) { IPhysicsPlugin plug = (IPhysicsPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); plug.Init(); if (!_PhysPlugins.ContainsKey(plug.GetName())) { _PhysPlugins.Add(plug.GetName(), plug); m_log.Info("[PHYSICS]: Added physics engine: " + plug.GetName()); } } Type meshTypeInterface = pluginType.GetInterface("IMeshingPlugin", true); if (meshTypeInterface != null) { IMeshingPlugin plug = (IMeshingPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); if (!_MeshPlugins.ContainsKey(plug.GetName())) { _MeshPlugins.Add(plug.GetName(), plug); m_log.Info("[PHYSICS]: Added meshing engine: " + plug.GetName()); } } physTypeInterface = null; meshTypeInterface = null; } } } } } pluginAssembly = null; } //--- } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Linq; using log4net; namespace Utilities { /// <summary> /// Extension methods for strings. /// </summary> public static class StringUtilities { /// <summary> /// Capitalizes the first letter of a string /// </summary> public static string Capitalize(this string s) { if(char.IsUpper(s[0])) { return s; } else { return char.ToUpper(s[0]) + s.Substring(1); } } /// <summary> /// More generic version of Join, accepting any objects (and calling /// ToString on them to get the string values) to join. /// </summary> public static string Join(IEnumerable items, string separator) { var sb = new StringBuilder(); var addSep = false; foreach(object item in items) { if(addSep) { sb.Append(separator); } sb.Append(item); addSep = true; } return sb.ToString(); } /// <summary> /// Splits a line of text into comma-separated fields. Handles quoted /// fields containing commas. /// </summary> public static string[] SplitCSV(this string line) { return line.SplitQuoted(","); } /// <summary> /// Splits a line of text into space-separated fields. Handles quoted /// fields containing spaces. /// </summary> public static string[] SplitSpaces(this string line) { return line.SplitQuoted(@"\s+"); } /// <summary> /// Splits a line of text into fields on the specified separator. /// Handles quoted fields that contain the separator. /// </summary> public static string[] SplitQuoted(this string line, string separator) { var re = string.Format("{0}(?=(?:[^\"]*\"[^\"]*[\"^{0}]*\")*(?![^\"]*\"))", separator); var fields = Regex.Split(line, re); return fields.Select(f => f.Trim().Trim(new char[] { '"' }) .Replace("\"\"", "\"")).ToArray(); } /// <summary> /// HFM version numbers don't follow the standard version numbering scheme, /// with breaking changes regularly introduced in patch-level updates! To /// handle this, we convert 5-part version specs to Version objects where /// the 4th and 5th numbers are merged into a single Revision number. The /// individual values can be returned using MajorRevision and MinorRevision /// properties. /// </summary> public static Version ToVersion(this string version) { Version ver = null; var re = new Regex(@"^(\d+\.\d+\.\d+).(\d+).?(\d+)?$"); var match = re.Match(version); if(match.Success) { var major = Convert.ToInt32(match.Groups[2].Value); var minor = match.Groups[3].Value != "" ? Convert.ToInt32(match.Groups[3].Value) : 0; ver = new Version(match.Groups[1].Value + "." + ((major << 16) | minor)); } else { ver = new Version(version); } return ver; } public static String FromVersion(Version ver) { return ver.Major + "." + ver.Minor + "." + ver.Build + "." + ver.MajorRevision + "." + ver.MinorRevision; } } /// <summary> /// Utility class providing a collection of static utility methods. /// </summary> public static class FileUtilities { // Reference to class logger private static readonly ILog _log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Converts a pattern containing ? and * characters into a case- /// insensitive regular expression. /// </summary> public static Regex ConvertWildcardPatternToRE(string pattern) { return new Regex("^" + pattern.Replace(@"\", @"\\").Replace(".", @"\.") .Replace("*", ".*").Replace("?", ".") + "$", RegexOptions.IgnoreCase); } /// <summary> /// Given a starting directory and a filename pattern, returns a list /// paths of files that match the name pattern. /// </summary> public static List<string> FindMatchingFiles(string sourceDir, string namePattern, bool includeSubDirs) { _log.TraceFormat("Searching for files like '{0}' {1} {2}", namePattern, includeSubDirs ? "below" : "in", sourceDir); var nameRE = ConvertWildcardPatternToRE(namePattern); return FindMatchingFiles(sourceDir, nameRE, includeSubDirs, 0); } private static List<string> FindMatchingFiles(string sourceDir, Regex nameRE, bool includeSubDirs, int depth) { var files = new List<string>(); foreach(var filePath in Directory.GetFiles(sourceDir)) { var file = Path.GetFileName(filePath); if(nameRE.IsMatch(file)) { _log.DebugFormat("Found file {0}", filePath); files.Add(filePath); } } if(includeSubDirs) { foreach(var dirPath in Directory.GetDirectories(sourceDir)) { var dir = GetDirectoryName(dirPath); _log.DebugFormat("Recursing into {0}", Path.Combine(sourceDir, dir)); files.AddRange(FindMatchingFiles(Path.Combine(sourceDir, dir), nameRE, includeSubDirs, depth + 1)); } } return files; } /// <summary> /// Given a path containing wildcards, returns the file(s) that match /// pattern. /// </summary> public static List<string> GetMatchingFiles(string pathPattern) { var dir = Path.GetDirectoryName(pathPattern); var pattern = Path.GetFileName(pathPattern); return FindMatchingFiles(dir, pattern, false); } /// <summary> /// Checks if the specified path exists, throwing an exception if it /// doesn't. /// </summary> public static void EnsureFileExists(string path) { if(!File.Exists(path)) { throw new FileNotFoundException(string.Format("No file was found at {0}", path)); } } /// <summary> /// Checks if the specified directory exists, throwing an exception if /// it doesn't. /// </summary> public static void EnsureDirExists(string path) { if(!Directory.Exists(path)) { throw new DirectoryNotFoundException(string.Format("No directory was found at {0}", path)); } } /// <summary> /// Checks if the specified path can be written to. /// </summary> public static void EnsureFileWriteable(string path) { using (FileStream s = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { } } /// <summary> /// Returns the name of the directory, given a path to a directory /// </summary> public static string GetDirectoryName(string path) { var di = new DirectoryInfo(path); return di.Name; } /// <summary> /// Returns the part of path2 that is not in path1. /// </summary> public static string PathDifference(string path1, string path2) { string diff = ""; if(path2.Length > path1.Length) { if(path2.Substring(0, path1.Length) != path1) { throw new ArgumentException(string.Format("Path {0} is not a parent path of {1}", path1, path2)); } else { return path2.Substring(path1.Length); } } return diff; } /// <summary> /// Convert a string to a byte array, using ASCII encoding. /// </summary> public static byte[] GetBytes(string str) { return System.Text.Encoding.ASCII.GetBytes(str); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.IO; namespace Retro_Kingdom { public class Main : Game { public const int DEFAULT_RESOLUTION_WIDTH = 1280; public const int DEFAULT_RESOLUTION_HEIGHT = 720; public const int GAME_STATUS_INTRO = 0; public const int GAME_STATUS_MENU = 1; public const int GAME_STATUS_GAME_RTS_RUNNING = 10; public const int GAME_STATUS_GAME_SS_RUNNING = 20; public int GameStatus; public int CurrentGameSelected; GraphicsDeviceManager graphics; GraphicsDevice device; SpriteBatch spriteBatch; KeyboardState oldKBState, currentKBState; MouseState oldMouseState, currentMouseState; GamePadState oldGPStateP1, currentGPStateP1; Intro mainIntro; RTSEngine gameRTS; SideScrollerEngine gameSS; Menu mainMenu; public Main() { Window.Title = "ReTro Kingdom"; this.IsMouseVisible = true; graphics = new GraphicsDeviceManager(this); device = graphics.GraphicsDevice; Content.RootDirectory = "Content"; this.ChangeResolution(DEFAULT_RESOLUTION_WIDTH, DEFAULT_RESOLUTION_HEIGHT); this.LoadOptions(); } protected override void Initialize() { GameSoundEffect.LoadContent(Content); Intro.LoadContent(Content); Sprite.LoadContent(Content); Menu.LoadContent(Content); BarMeter.LoadContent(Content); SideScrollerEngine.LoadContent(Content); mainIntro = new Intro(this); gameRTS = new RTSEngine("World 1", this); gameSS = new SideScrollerEngine("World 1", this); mainMenu = new Menu(this, 0); GameStatus = GAME_STATUS_INTRO; CurrentGameSelected = 0; base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); } protected override void UnloadContent() { this.Content.Unload(); } protected override void Update(GameTime gameTime) { currentKBState = Keyboard.GetState(); currentMouseState = Mouse.GetState(); currentGPStateP1 = GamePad.GetState(PlayerIndex.One); switch (this.GameStatus) { case GAME_STATUS_INTRO: mainIntro.Update(oldKBState, currentKBState, oldMouseState, currentMouseState, oldGPStateP1, currentGPStateP1); break; case GAME_STATUS_MENU: mainMenu.Update(oldKBState, currentKBState, oldMouseState, currentMouseState, oldGPStateP1, currentGPStateP1); break; case GAME_STATUS_GAME_RTS_RUNNING: gameRTS.Update(oldKBState, currentKBState, oldMouseState, currentMouseState, oldGPStateP1, currentGPStateP1); break; case GAME_STATUS_GAME_SS_RUNNING: gameSS.Update(oldKBState, currentKBState, oldMouseState, currentMouseState, oldGPStateP1, currentGPStateP1); break; } oldKBState = currentKBState; oldMouseState = currentMouseState; oldGPStateP1 = currentGPStateP1; base.Update(gameTime); } protected override void Draw(GameTime gameTime) { //GraphicsDevice.Clear(Color.CornflowerBlue); switch (GameStatus) { case GAME_STATUS_INTRO: mainIntro.Draw(spriteBatch); break; case GAME_STATUS_MENU: mainMenu.Draw(spriteBatch); break; case GAME_STATUS_GAME_RTS_RUNNING: gameRTS.Draw(spriteBatch); break; case GAME_STATUS_GAME_SS_RUNNING: gameSS.Draw(spriteBatch); break; } base.Draw(gameTime); } public void OpenMenu() { mainMenu = new Menu(this, this.CurrentGameSelected); this.GameStatus = GAME_STATUS_MENU; } public void RestartGame() { mainIntro = new Intro(this); mainMenu = new Menu(this, 0); gameRTS = new RTSEngine("World 1", this); gameSS = new SideScrollerEngine("World 1", this); GameStatus = GAME_STATUS_INTRO; } public void ToggleFullScreen() { graphics.ToggleFullScreen(); } public void ChangeResolution(int width, int height) { graphics.PreferredBackBufferWidth = width; graphics.PreferredBackBufferHeight = height; graphics.ApplyChanges(); } private void CreateDefaultOptions() { string tmpFile = "options.ini"; using (StreamWriter sw = File.CreateText(tmpFile)) { sw.WriteLine(string.Format("fullscreen={0}", graphics.IsFullScreen.ToString().ToLower())); sw.WriteLine(string.Format("height={0}", graphics.PreferredBackBufferHeight)); sw.WriteLine(string.Format("width={0}", graphics.PreferredBackBufferWidth)); } } private void LoadOptions() { string tmpFile = "options.ini"; List<string> tmpLines = new List<string>(); if (File.Exists(tmpFile)) { using (StreamReader reader = new StreamReader(tmpFile)) { string tmpLine; while ((tmpLine = reader.ReadLine()) != null) { string left = tmpLine.Substring(0, tmpLine.IndexOf("=")); string right = tmpLine.Substring(tmpLine.LastIndexOf('=') + 1); switch (left) { case "fullscreen": graphics.IsFullScreen = Boolean.Parse(right); break; case "height": graphics.PreferredBackBufferHeight = int.Parse(right); break; case "width": graphics.PreferredBackBufferWidth = int.Parse(right); break; } graphics.ApplyChanges(); } } } else { this.CreateDefaultOptions(); } } public void SaveOptions() { string tmpFile = "options.ini"; using (StreamWriter sw = File.CreateText(tmpFile)) { sw.WriteLine(string.Format("fullscreen={0}", graphics.IsFullScreen.ToString().ToLower())); sw.WriteLine(string.Format("height={0}", graphics.PreferredBackBufferHeight)); sw.WriteLine(string.Format("width={0}", graphics.PreferredBackBufferWidth)); } } } }
using System; using System.IO; using K4os.Compression.LZ4; using K4os.Compression.LZ4.Encoders; using ValveResourceFormat.Blocks; using ValveResourceFormat.Compression; using ValveResourceFormat.Serialization.KeyValues; using ValveResourceFormat.Utils; namespace ValveResourceFormat.ResourceTypes { #pragma warning disable CA1001 // Types that own disposable fields should be disposable public class BinaryKV3 : ResourceData #pragma warning restore CA1001 // Types that own disposable fields should be disposable { private BlockType KVBlockType; public override BlockType Type => KVBlockType; private static readonly Guid KV3_ENCODING_BINARY_BLOCK_COMPRESSED = new Guid(new byte[] { 0x46, 0x1A, 0x79, 0x95, 0xBC, 0x95, 0x6C, 0x4F, 0xA7, 0x0B, 0x05, 0xBC, 0xA1, 0xB7, 0xDF, 0xD2 }); private static readonly Guid KV3_ENCODING_BINARY_UNCOMPRESSED = new Guid(new byte[] { 0x00, 0x05, 0x86, 0x1B, 0xD8, 0xF7, 0xC1, 0x40, 0xAD, 0x82, 0x75, 0xA4, 0x82, 0x67, 0xE7, 0x14 }); private static readonly Guid KV3_ENCODING_BINARY_BLOCK_LZ4 = new Guid(new byte[] { 0x8A, 0x34, 0x47, 0x68, 0xA1, 0x63, 0x5C, 0x4F, 0xA1, 0x97, 0x53, 0x80, 0x6F, 0xD9, 0xB1, 0x19 }); //private static readonly Guid KV3_FORMAT_GENERIC = new Guid(new byte[] { 0x7C, 0x16, 0x12, 0x74, 0xE9, 0x06, 0x98, 0x46, 0xAF, 0xF2, 0xE6, 0x3E, 0xB5, 0x90, 0x37, 0xE7 }); public const int MAGIC = 0x03564B56; // VKV3 (3 isn't ascii, its 0x03) public const int MAGIC2 = 0x4B563301; // KV3\x01 public const int MAGIC3 = 0x4B563302; // KV3\x02 public KVObject Data { get; private set; } public Guid Encoding { get; private set; } public Guid Format { get; private set; } private BinaryReader RawBinaryReader; private string[] stringArray; private byte[] typesArray; private BinaryReader uncompressedBlockDataReader; private int[] uncompressedBlockLengthArray; private long currentCompressedBlockIndex; private long currentTypeIndex; private long currentEightBytesOffset; private long currentBinaryBytesOffset = -1; public BinaryKV3() { KVBlockType = BlockType.DATA; } public BinaryKV3(BlockType type) { KVBlockType = type; } public override void Read(BinaryReader reader, Resource resource) { reader.BaseStream.Position = Offset; var outStream = new MemoryStream(); var outWrite = new BinaryWriter(outStream); var outRead = new BinaryReader(outStream); // Why why why why why why why var magic = reader.ReadUInt32(); if (magic == MAGIC2) { ReadVersion2(reader, outWrite, outRead); return; } if (magic == MAGIC3) { RawBinaryReader = reader; ReadVersion3(reader, outWrite, outRead); RawBinaryReader = null; return; } if (magic != MAGIC) { throw new UnexpectedMagicException("Invalid KV3 signature", magic, nameof(magic)); } Encoding = new Guid(reader.ReadBytes(16)); Format = new Guid(reader.ReadBytes(16)); // Valve's implementation lives in LoadKV3Binary() // KV3_ENCODING_BINARY_BLOCK_COMPRESSED calls CBlockCompress::FastDecompress() // and then it proceeds to call LoadKV3BinaryUncompressed, which should be the same routine for KV3_ENCODING_BINARY_UNCOMPRESSED // Old binary with debug symbols for ref: https://users.alliedmods.net/~asherkin/public/bins/dota_symbols/bin/osx64/libmeshsystem.dylib if (Encoding.CompareTo(KV3_ENCODING_BINARY_BLOCK_COMPRESSED) == 0) { BlockCompress.FastDecompress(reader, outWrite, outRead); } else if (Encoding.CompareTo(KV3_ENCODING_BINARY_BLOCK_LZ4) == 0) { DecompressLZ4(reader, outWrite); } else if (Encoding.CompareTo(KV3_ENCODING_BINARY_UNCOMPRESSED) == 0) { reader.BaseStream.CopyTo(outStream); outStream.Position = 0; } else { throw new UnexpectedMagicException("Unrecognised KV3 Encoding", Encoding.ToString(), nameof(Encoding)); } var stringCount = outRead.ReadUInt32(); stringArray = new string[stringCount]; for (var i = 0; i < stringCount; i++) { stringArray[i] = outRead.ReadNullTermString(System.Text.Encoding.UTF8); } Data = ParseBinaryKV3(outRead, null, true); } private void ReadVersion3(BinaryReader reader, BinaryWriter outWrite, BinaryReader outRead) { Format = new Guid(reader.ReadBytes(16)); var compressionMethod = reader.ReadUInt32(); var compressionDictionaryId = reader.ReadUInt16(); var compressionFrameSize = reader.ReadUInt16(); var countOfBinaryBytes = reader.ReadUInt32(); // how many bytes (binary blobs) var countOfIntegers = reader.ReadUInt32(); // how many 4 byte values (ints) var countOfEightByteValues = reader.ReadUInt32(); // how many 8 byte values (doubles) // 8 bytes that help valve preallocate, useless for us var stringAndTypesBufferSize = reader.ReadUInt32(); var b = reader.ReadUInt16(); var c = reader.ReadUInt16(); var uncompressedSize = reader.ReadUInt32(); var compressedSize = reader.ReadInt32(); // uint32 var blockCount = reader.ReadUInt32(); var blockTotalSize = reader.ReadInt32(); // uint32 if (compressionMethod == 0) { if (compressionDictionaryId != 0) { throw new UnexpectedMagicException("Unhandled", compressionDictionaryId, nameof(compressionDictionaryId)); } if (compressionFrameSize != 0) { throw new UnexpectedMagicException("Unhandled", compressionFrameSize, nameof(compressionFrameSize)); } var output = new Span<byte>(new byte[compressedSize]); reader.Read(output); outWrite.Write(output); } else if (compressionMethod == 1) { if (compressionDictionaryId != 0) { throw new UnexpectedMagicException("Unhandled", compressionDictionaryId, nameof(compressionDictionaryId)); } if (compressionFrameSize != 16384) { throw new UnexpectedMagicException("Unhandled", compressionFrameSize, nameof(compressionFrameSize)); } var input = reader.ReadBytes(compressedSize); var output = new Span<byte>(new byte[uncompressedSize]); LZ4Codec.Decode(input, output); outWrite.Write(output); outWrite.BaseStream.Position = 0; } else if (compressionMethod == 2) { if (compressionDictionaryId != 0) { throw new UnexpectedMagicException("Unhandled", compressionDictionaryId, nameof(compressionDictionaryId)); } if (compressionFrameSize != 0) { throw new UnexpectedMagicException("Unhandled", compressionFrameSize, nameof(compressionFrameSize)); } var input = reader.ReadBytes(compressedSize); var zstd = new ZstdSharp.Decompressor(); var output = zstd.Unwrap(input); outWrite.Write(output); outWrite.BaseStream.Position = 0; } else { throw new UnexpectedMagicException("Unknown compression method", compressionMethod, nameof(compressionMethod)); } currentBinaryBytesOffset = 0; outRead.BaseStream.Position = countOfBinaryBytes; if (outRead.BaseStream.Position % 4 != 0) { // Align to % 4 after binary blobs outRead.BaseStream.Position += 4 - (outRead.BaseStream.Position % 4); } var countOfStrings = outRead.ReadInt32(); var kvDataOffset = outRead.BaseStream.Position; // Subtract one integer since we already read it (countOfStrings) outRead.BaseStream.Position += (countOfIntegers - 1) * 4; if (outRead.BaseStream.Position % 8 != 0) { // Align to % 8 for the start of doubles outRead.BaseStream.Position += 8 - (outRead.BaseStream.Position % 8); } currentEightBytesOffset = outRead.BaseStream.Position; outRead.BaseStream.Position += countOfEightByteValues * 8; var stringArrayStartPosition = outRead.BaseStream.Position; stringArray = new string[countOfStrings]; for (var i = 0; i < countOfStrings; i++) { stringArray[i] = outRead.ReadNullTermString(System.Text.Encoding.UTF8); } var typesLength = stringAndTypesBufferSize - (outRead.BaseStream.Position - stringArrayStartPosition); typesArray = new byte[typesLength]; for (var i = 0; i < typesLength; i++) { typesArray[i] = outRead.ReadByte(); } if (blockCount == 0) { var noBlocksTrailer = outRead.ReadUInt32(); if (noBlocksTrailer != 0xFFEEDD00) { throw new UnexpectedMagicException("Invalid trailer", noBlocksTrailer, nameof(noBlocksTrailer)); } // Move back to the start of the KV data for reading. outRead.BaseStream.Position = kvDataOffset; Data = ParseBinaryKV3(outRead, null, true); return; } uncompressedBlockLengthArray = new int[blockCount]; for (var i = 0; i < blockCount; i++) { uncompressedBlockLengthArray[i] = outRead.ReadInt32(); } var trailer = outRead.ReadUInt32(); if (trailer != 0xFFEEDD00) { throw new UnexpectedMagicException("Invalid trailer", trailer, nameof(trailer)); } try { using var uncompressedBlocks = new MemoryStream(blockTotalSize); uncompressedBlockDataReader = new BinaryReader(uncompressedBlocks); if (compressionMethod == 0) { for (var i = 0; i < blockCount; i++) { RawBinaryReader.BaseStream.CopyTo(uncompressedBlocks, uncompressedBlockLengthArray[i]); } } else if (compressionMethod == 1) { // TODO: Do we need to pass blockTotalSize here? using var lz4decoder = new LZ4ChainDecoder(blockTotalSize, 0); for (var i = 0; i < blockCount; i++) { var compressedBlockLength = outRead.ReadUInt16(); var input = new Span<byte>(new byte[compressedBlockLength]); var output = new Span<byte>(new byte[uncompressedBlockLengthArray[i]]); RawBinaryReader.Read(input); lz4decoder.DecodeAndDrain(input, output, out _); uncompressedBlocks.Write(output); } } else if (compressionMethod == 2) { // This is supposed to be a streaming decompress using ZSTD_decompressStream, // but as it turns out, zstd unwrap above already decompressed all of the blocks for us, // so all we need to do is just copy the buffer. // It's possible that Valve's code needs extra decompress because they set ZSTD_d_stableOutBuffer parameter. outRead.BaseStream.CopyTo(uncompressedBlocks); } else { throw new UnexpectedMagicException("Unimplemented compression method in block decoder", compressionMethod, nameof(compressionMethod)); } uncompressedBlocks.Position = 0; // Move back to the start of the KV data for reading. outRead.BaseStream.Position = kvDataOffset; Data = ParseBinaryKV3(outRead, null, true); } finally { uncompressedBlockDataReader.Dispose(); } } private void ReadVersion2(BinaryReader reader, BinaryWriter outWrite, BinaryReader outRead) { Format = new Guid(reader.ReadBytes(16)); var compressionMethod = reader.ReadInt32(); var countOfBinaryBytes = reader.ReadInt32(); // how many bytes (binary blobs) var countOfIntegers = reader.ReadInt32(); // how many 4 byte values (ints) var countOfEightByteValues = reader.ReadInt32(); // how many 8 byte values (doubles) if (compressionMethod == 0) { var length = reader.ReadInt32(); var output = new Span<byte>(new byte[length]); reader.Read(output); outWrite.Write(output); } else if (compressionMethod == 1) { DecompressLZ4(reader, outWrite); } else { throw new UnexpectedMagicException("Unknown compression method", compressionMethod, nameof(compressionMethod)); } currentBinaryBytesOffset = 0; outRead.BaseStream.Position = countOfBinaryBytes; if (outRead.BaseStream.Position % 4 != 0) { // Align to % 4 after binary blobs outRead.BaseStream.Position += 4 - (outRead.BaseStream.Position % 4); } var countOfStrings = outRead.ReadInt32(); var kvDataOffset = outRead.BaseStream.Position; // Subtract one integer since we already read it (countOfStrings) outRead.BaseStream.Position += (countOfIntegers - 1) * 4; if (outRead.BaseStream.Position % 8 != 0) { // Align to % 8 for the start of doubles outRead.BaseStream.Position += 8 - (outRead.BaseStream.Position % 8); } currentEightBytesOffset = outRead.BaseStream.Position; outRead.BaseStream.Position += countOfEightByteValues * 8; stringArray = new string[countOfStrings]; for (var i = 0; i < countOfStrings; i++) { stringArray[i] = outRead.ReadNullTermString(System.Text.Encoding.UTF8); } // bytes after the string table is kv types, minus 4 static bytes at the end var typesLength = outRead.BaseStream.Length - 4 - outRead.BaseStream.Position; typesArray = new byte[typesLength]; for (var i = 0; i < typesLength; i++) { typesArray[i] = outRead.ReadByte(); } // Move back to the start of the KV data for reading. outRead.BaseStream.Position = kvDataOffset; Data = ParseBinaryKV3(outRead, null, true); } private void DecompressLZ4(BinaryReader reader, BinaryWriter outWrite) { var uncompressedSize = reader.ReadUInt32(); var compressedSize = (int)(Size - (reader.BaseStream.Position - Offset)); var input = reader.ReadBytes(compressedSize); var output = new Span<byte>(new byte[uncompressedSize]); LZ4Codec.Decode(input, output); outWrite.Write(output); outWrite.BaseStream.Position = 0; } private (KVType Type, KVFlag Flag) ReadType(BinaryReader reader) { byte databyte; if (typesArray != null) { databyte = typesArray[currentTypeIndex++]; } else { databyte = reader.ReadByte(); } var flagInfo = KVFlag.None; if ((databyte & 0x80) > 0) { databyte &= 0x7F; // Remove the flag bit if (typesArray != null) { flagInfo = (KVFlag)typesArray[currentTypeIndex++]; } else { flagInfo = (KVFlag)reader.ReadByte(); } } return ((KVType)databyte, flagInfo); } private KVObject ParseBinaryKV3(BinaryReader reader, KVObject parent, bool inArray = false) { string name = null; if (!inArray) { var stringID = reader.ReadInt32(); name = (stringID == -1) ? string.Empty : stringArray[stringID]; } var (datatype, flagInfo) = ReadType(reader); return ReadBinaryValue(name, datatype, flagInfo, reader, parent); } private KVObject ReadBinaryValue(string name, KVType datatype, KVFlag flagInfo, BinaryReader reader, KVObject parent) { var currentOffset = reader.BaseStream.Position; switch (datatype) { case KVType.NULL: parent.AddProperty(name, MakeValue(datatype, null, flagInfo)); break; case KVType.BOOLEAN: if (currentBinaryBytesOffset > -1) { reader.BaseStream.Position = currentBinaryBytesOffset; } parent.AddProperty(name, MakeValue(datatype, reader.ReadBoolean(), flagInfo)); if (currentBinaryBytesOffset > -1) { currentBinaryBytesOffset++; reader.BaseStream.Position = currentOffset; } break; case KVType.BOOLEAN_TRUE: parent.AddProperty(name, MakeValue(datatype, true, flagInfo)); break; case KVType.BOOLEAN_FALSE: parent.AddProperty(name, MakeValue(datatype, false, flagInfo)); break; case KVType.INT64_ZERO: parent.AddProperty(name, MakeValue(datatype, 0L, flagInfo)); break; case KVType.INT64_ONE: parent.AddProperty(name, MakeValue(datatype, 1L, flagInfo)); break; case KVType.INT64: if (currentEightBytesOffset > 0) { reader.BaseStream.Position = currentEightBytesOffset; } parent.AddProperty(name, MakeValue(datatype, reader.ReadInt64(), flagInfo)); if (currentEightBytesOffset > 0) { currentEightBytesOffset = reader.BaseStream.Position; reader.BaseStream.Position = currentOffset; } break; case KVType.UINT64: if (currentEightBytesOffset > 0) { reader.BaseStream.Position = currentEightBytesOffset; } parent.AddProperty(name, MakeValue(datatype, reader.ReadUInt64(), flagInfo)); if (currentEightBytesOffset > 0) { currentEightBytesOffset = reader.BaseStream.Position; reader.BaseStream.Position = currentOffset; } break; case KVType.INT32: parent.AddProperty(name, MakeValue(datatype, reader.ReadInt32(), flagInfo)); break; case KVType.UINT32: parent.AddProperty(name, MakeValue(datatype, reader.ReadUInt32(), flagInfo)); break; case KVType.DOUBLE: if (currentEightBytesOffset > 0) { reader.BaseStream.Position = currentEightBytesOffset; } parent.AddProperty(name, MakeValue(datatype, reader.ReadDouble(), flagInfo)); if (currentEightBytesOffset > 0) { currentEightBytesOffset = reader.BaseStream.Position; reader.BaseStream.Position = currentOffset; } break; case KVType.DOUBLE_ZERO: parent.AddProperty(name, MakeValue(datatype, 0.0D, flagInfo)); break; case KVType.DOUBLE_ONE: parent.AddProperty(name, MakeValue(datatype, 1.0D, flagInfo)); break; case KVType.STRING: var id = reader.ReadInt32(); parent.AddProperty(name, MakeValue(datatype, id == -1 ? string.Empty : stringArray[id], flagInfo)); break; case KVType.BINARY_BLOB: if (uncompressedBlockDataReader != null) { var output = uncompressedBlockDataReader.ReadBytes(uncompressedBlockLengthArray[currentCompressedBlockIndex++]); parent.AddProperty(name, MakeValue(datatype, output, flagInfo)); break; } var length = reader.ReadInt32(); if (currentBinaryBytesOffset > -1) { reader.BaseStream.Position = currentBinaryBytesOffset; } parent.AddProperty(name, MakeValue(datatype, reader.ReadBytes(length), flagInfo)); if (currentBinaryBytesOffset > -1) { currentBinaryBytesOffset = reader.BaseStream.Position; reader.BaseStream.Position = currentOffset + 4; } break; case KVType.ARRAY: var arrayLength = reader.ReadInt32(); var array = new KVObject(name, true); for (var i = 0; i < arrayLength; i++) { ParseBinaryKV3(reader, array, true); } parent.AddProperty(name, MakeValue(datatype, array, flagInfo)); break; case KVType.ARRAY_TYPED: var typeArrayLength = reader.ReadInt32(); var (subType, subFlagInfo) = ReadType(reader); var typedArray = new KVObject(name, true); for (var i = 0; i < typeArrayLength; i++) { ReadBinaryValue(name, subType, subFlagInfo, reader, typedArray); } parent.AddProperty(name, MakeValue(datatype, typedArray, flagInfo)); break; case KVType.OBJECT: var objectLength = reader.ReadInt32(); var newObject = new KVObject(name, false); for (var i = 0; i < objectLength; i++) { ParseBinaryKV3(reader, newObject, false); } if (parent == null) { parent = newObject; } else { parent.AddProperty(name, MakeValue(datatype, newObject, flagInfo)); } break; default: throw new UnexpectedMagicException($"Unknown KVType for field '{name}' on byte {reader.BaseStream.Position - 1}", (int)datatype, nameof(datatype)); } return parent; } private static KVType ConvertBinaryOnlyKVType(KVType type) { switch (type) { case KVType.BOOLEAN: case KVType.BOOLEAN_TRUE: case KVType.BOOLEAN_FALSE: return KVType.BOOLEAN; case KVType.INT64: case KVType.INT32: case KVType.INT64_ZERO: case KVType.INT64_ONE: return KVType.INT64; case KVType.UINT64: case KVType.UINT32: return KVType.UINT64; case KVType.DOUBLE: case KVType.DOUBLE_ZERO: case KVType.DOUBLE_ONE: return KVType.DOUBLE; case KVType.ARRAY_TYPED: return KVType.ARRAY; } return type; } private static KVValue MakeValue(KVType type, object data, KVFlag flag) { var realType = ConvertBinaryOnlyKVType(type); if (flag != KVFlag.None) { return new KVFlaggedValue(realType, flag, data); } return new KVValue(realType, data); } public KV3File GetKV3File() { // TODO: Other format guids are not "generic" but strings like "vpc19" return new KV3File(Data, format: $"generic:version{{{Format.ToString()}}}"); } public override void WriteText(IndentedTextWriter writer) { Data.Serialize(writer); } } }
using System; using UnityEngine; /// <summary> /// This trigger is used to set a float material /// property as a reaction to changes in the music. /// </summary> [AddComponentMenu("Visualizer Studio/Triggers/Material Property Trigger")] public class VisMaterialPropertyTrigger : VisBasePropertyTrigger { #region Defaults Static Class /// <summary> /// This internal class holds all of the defaults of the VisMaterialPropertyTrigger class. /// </summary> public static new class Defaults { public const string targetProperty = ""; public const bool setAsProceduralMaterial = false; public const bool rebuildProceduralTexturesImmediately = false; public const bool applyToMaterialIndex = false; public const int materialIndex = 0; } #endregion #region Public Member Variables /// <summary> /// This is the target property to modify on the parent game object. /// As an example of how this works: /// minControllerValue = 0.2 /// maxControllerValue = 0.8 /// minPropertyValue = 2.0 /// maxPropertyValue = 4.0 /// invertValue = false /// /// controllerInputValue = 0.5 -- newPropertyValue = 3.0 /// controllerInputVlaue = 0.35 -- newPropertyValue = 2.5 /// </summary> //[HideInInspector()] public string targetProperty = Defaults.targetProperty; /// <summary> /// This indicates if this material property modifier should treat the target as a procedural /// material and attempt to set the target property as a procedural float. /// </summary> //[HideInInspector()] public bool setAsProceduralMaterial = false; /// <summary> /// This indicates if the procedural textures should immediately be regenerated when setting a float on the target material. /// </summary> //[HideInInspector()] public bool rebuildProceduralTexturesImmediately = false; /// <summary> /// This indicates if this material property modifier should apply /// to a material in a specific index, or the main material. /// </summary> //[HideInInspector()] public bool applyToMaterialIndex = false; /// <summary> /// This is the material index to apply this property change to. /// </summary> //[HideInInspector()] public int materialIndex = 0; #endregion #region Private Members /// <summary> /// This indicates if there was a special target property name entrered for this material property trigger. /// Valid values are ColorR, ColorRed, ColorG, ColorGreen, ColorB, ColorBlue, ColorA, ColorAlpha, and Color. /// </summary> private bool specialTargetProperty = false; #endregion #region Init/Deinit Functions /// <summary> /// This is callled when this commponent is reset. /// </summary> public override void Reset() { base.Reset(); targetProperty = Defaults.targetProperty; setAsProceduralMaterial = Defaults.setAsProceduralMaterial; rebuildProceduralTexturesImmediately = Defaults.rebuildProceduralTexturesImmediately; applyToMaterialIndex = Defaults.applyToMaterialIndex; materialIndex = Defaults.materialIndex; } /// <summary> /// This is called when this component is started. /// </summary> public override void Start() { base.Start(); //check if this is using a special value string lowerCaseTargetProperty = targetProperty.ToLower(); if (lowerCaseTargetProperty == "colorr" || lowerCaseTargetProperty == "colorred" || lowerCaseTargetProperty == "colorg" || lowerCaseTargetProperty == "colorgreen" || lowerCaseTargetProperty == "colorb" || lowerCaseTargetProperty == "colorblue" || lowerCaseTargetProperty == "colora" || lowerCaseTargetProperty == "coloralpha" || lowerCaseTargetProperty == "color") specialTargetProperty = true; else specialTargetProperty = false; } #endregion #region VisBasePropertyTrigger Implementation /// <summary> /// This function is used to call into sub classes of /// VisBasePropertyTrigger, in order for them to set their /// target property to the new value specified. /// </summary> /// <param name="propertyValue">The new value to set the property to.</param> public override void SetProperty(float propertyValue) { //create var to store target material Material targetMaterial = null; Renderer rendererComp = GetComponent<Renderer>(); //get the target material if (setAsProceduralMaterial && applyToMaterialIndex && rendererComp != null && materialIndex >= 0 && materialIndex < rendererComp.sharedMaterials.Length && #if (!UNITY_3_5 && !UNITY_3_4 && !UNITY_3_3 && !UNITY_3_2 && !UNITY_3_1 && !UNITY_3_0_0 && !UNITY_3_0 && !UNITY_2_6_1 && !UNITY_2_6) && (UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_WEBPLAYER || UNITY_EDITOR) rendererComp.sharedMaterials[materialIndex] as ProceduralMaterial) {//get indexed material as procedural material targetMaterial = rendererComp.sharedMaterials[materialIndex]; } #else true) {//can't sure procedural materials on IOS or Android! Debug.LogWarning("Procedural Materials cannot be used on IOS or Android, and also requires Unity 3.4 or later!"); } #endif else if (setAsProceduralMaterial && rendererComp != null && rendererComp.sharedMaterial != null && #if (!UNITY_3_5 && !UNITY_3_4 && !UNITY_3_3 && !UNITY_3_2 && !UNITY_3_1 && !UNITY_3_0_0 && !UNITY_3_0 && !UNITY_2_6_1 && !UNITY_2_6) && (UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_WEBPLAYER || UNITY_EDITOR) rendererComp.sharedMaterial as ProceduralMaterial) {//get main material as procedural material targetMaterial = rendererComp.sharedMaterial; } #else true) {//can't sure procedural materials on IOS or Android! Debug.LogWarning("Procedural Materials cannot be used on IOS or Android, and also requires Unity 3.4 or later!"); } #endif else if (applyToMaterialIndex && rendererComp != null && materialIndex >= 0 && materialIndex < rendererComp.materials.Length) {//get indexed material as normal material targetMaterial = rendererComp.materials[materialIndex]; } else if (rendererComp != null && rendererComp.material != null) {//get main material as procedural material targetMaterial = rendererComp.material; } //make sure a target material was found if (targetMaterial != null) { #if (!UNITY_3_5 && !UNITY_3_4 && !UNITY_3_3 && !UNITY_3_2 && !UNITY_3_1 && !UNITY_3_0_0 && !UNITY_3_0 && !UNITY_2_6_1 && !UNITY_2_6) && (UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_WEBPLAYER || UNITY_EDITOR) //check if this should be set as a procedural material and it actual is on if (setAsProceduralMaterial && targetMaterial as ProceduralMaterial) { //get procedural material ProceduralMaterial procMat = targetMaterial as ProceduralMaterial; //make sure the value has changed float current = procMat.GetProceduralFloat(targetProperty); if (current != propertyValue) { //set float and rebuild texture procMat.SetProceduralFloat(targetProperty, propertyValue); if (rebuildProceduralTexturesImmediately) procMat.RebuildTexturesImmediately(); else procMat.RebuildTextures(); } } else #endif { //check if there is a special target property set if (specialTargetProperty) { //check for special float switch (targetProperty.ToLower()) { case "colorr": case "colorred": float clampedValue = Mathf.Clamp(propertyValue, 0.0f, 1.0f); Color newColor = new Color(clampedValue, targetMaterial.color.g, targetMaterial.color.b, targetMaterial.color.a); targetMaterial.color = newColor; break; case "colorg": case "colorgreen": clampedValue = Mathf.Clamp(propertyValue, 0.0f, 1.0f); newColor = new Color(targetMaterial.color.r, clampedValue, targetMaterial.color.b, targetMaterial.color.a); targetMaterial.color = newColor; break; case "colorb": case "colorblue": clampedValue = Mathf.Clamp(propertyValue, 0.0f, 1.0f); newColor = new Color(targetMaterial.color.r, targetMaterial.color.g, clampedValue, targetMaterial.color.a); targetMaterial.color = newColor; break; case "colora": case "coloralpha": clampedValue = Mathf.Clamp(propertyValue, 0.0f, 1.0f); newColor = new Color(targetMaterial.color.r, targetMaterial.color.g, targetMaterial.color.b, clampedValue); targetMaterial.color = newColor; break; case "color": clampedValue = Mathf.Clamp(propertyValue, 0.0f, 1.0f); newColor = new Color(clampedValue, clampedValue, clampedValue, targetMaterial.color.a); targetMaterial.color = newColor; break; default: //set float targetMaterial.SetFloat(targetProperty, propertyValue); break; } } else { //set float targetMaterial.SetFloat(targetProperty, propertyValue); } } } } #endregion }
using System; namespace KopiLua { public partial class Lua { private static object tag = 0; public static void LuaPushStdCallCFunction (LuaState luaState, LuaNativeFunction function) { LuaPushCFunction (luaState, function); } public static bool LuaLCheckMetatable (LuaState luaState, int index) { bool retVal = false; if (LuaGetMetatable (luaState, index) != 0) { LuaPushLightUserData (luaState, tag); LuaRawGet (luaState, -2); retVal = !LuaIsNil (luaState, -1); LuaSetTop (luaState, -3); } return retVal; } public static LuaTag LuaNetGetTag () { return new LuaTag (tag); } public static void LuaPushLightUserData (LuaState L, LuaTag p) { LuaPushLightUserData (L, p.Tag); } // Starting with 5.1 the auxlib version of checkudata throws an exception if the type isn't right // Instead, we want to run our own version that checks the type and just returns null for failure private static object CheckUserDataRaw (LuaState L, int ud, string tname) { object p = LuaToUserData (L, ud); if (p != null) { /* value is a userdata? */ if (LuaGetMetatable (L, ud) != 0) { bool isEqual; /* does it have a metatable? */ LuaGetField (L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ isEqual = LuaRawEqual (L, -1, -2) != 0; // NASTY - we need our own version of the lua_pop macro // lua_pop(L, 2); /* remove both metatables */ LuaSetTop (L, -(2) - 1); if (isEqual) /* does it have the correct mt? */ return p; } } return null; } public static int LuaNetCheckUData (LuaState luaState, int ud, string tname) { object udata = CheckUserDataRaw (luaState, ud, tname); return udata != null ? FourBytesToInt (udata as byte[]) : -1; } public static int LuaNetToNetObject (LuaState luaState, int index) { byte[] udata; if (LuaType (luaState, index) == LUA_TUSERDATA) { if (LuaLCheckMetatable (luaState, index)) { udata = LuaToUserData (luaState, index) as byte[]; if (udata != null) return FourBytesToInt (udata); } udata = CheckUserDataRaw (luaState, index, "luaNet_class") as byte[]; if (udata != null) return FourBytesToInt (udata); udata = CheckUserDataRaw (luaState, index, "luaNet_searchbase") as byte[]; if (udata != null) return FourBytesToInt (udata); udata = CheckUserDataRaw (luaState, index, "luaNet_function") as byte[]; if (udata != null) return FourBytesToInt (udata); } return -1; } public static void LuaNetNewUData (LuaState luaState, int val) { var userdata = LuaNewUserData (luaState, sizeof(int)) as byte[]; IntToFourBytes (val, userdata); } public static int LuaNetRawNetObj (LuaState luaState, int obj) { byte[] bytes = LuaToUserData (luaState, obj) as byte[]; if (bytes == null) return -1; return FourBytesToInt (bytes); } private static int FourBytesToInt (byte [] bytes) { return bytes [0] + (bytes [1] << 8) + (bytes [2] << 16) + (bytes [3] << 24); } private static void IntToFourBytes (int val, byte [] bytes) { // gfoot: is this really a good idea? bytes [0] = (byte)val; bytes [1] = (byte)(val >> 8); bytes [2] = (byte)(val >> 16); bytes [3] = (byte)(val >> 24); } /* Compatibility functions to allow NLua work with Lua 5.1.5 and Lua 5.2.2 with the same dll interface. * KopiLua methods to match KeraLua API */ public static int LuaNetRegistryIndex () { return LUA_REGISTRYINDEX; } public static void LuaNetPushGlobalTable (LuaState L) { LuaPushValue (L, LUA_GLOBALSINDEX); } public static void LuaNetPopGlobalTable (LuaState L) { LuaReplace (L, LUA_GLOBALSINDEX); } public static void LuaNetSetGlobal (LuaState L, string name) { LuaSetGlobal (L, name); } public static void LuaNetGetGlobal (LuaState L, string name) { LuaGetGlobal (L, name); } public static int LuaNetPCall (LuaState L, int nargs, int nresults, int errfunc) { return LuaPCall (L, nargs, nresults, errfunc); } [CLSCompliantAttribute (false)] public static int LuaNetLoadBuffer (LuaState L, string buff, uint sz, string name) { if (sz == 0) sz = (uint) strlen (buff); return LuaLLoadBuffer (L, buff, sz, name); } [CLSCompliantAttribute (false)] public static int LuaNetLoadBuffer (LuaState L, byte [] buff, uint sz, string name) { return LuaLLoadBuffer (L, buff, sz, name); } public static int LuaNetLoadFile (LuaState L, string file) { return LuaLLoadFile (L, file); } public static double LuaNetToNumber (LuaState L, int idx) { return LuaToNumber (L, idx); } public static int LuaNetEqual (LuaState L, int idx1, int idx2) { return LuaEqual (L, idx1, idx2); } [CLSCompliantAttribute (false)] public static void LuaNetPushLString (LuaState L, string s, uint len) { LuaPushLString (L, s, len); } public static int LuaNetIsStringStrict (LuaState L, int idx) { int t = LuaType (L, idx); return (t == LUA_TSTRING) ? 1 : 0; } public static LuaState LuaNetGetMainState (LuaState L1) { LuaGetField (L1, LUA_REGISTRYINDEX, "main_state"); LuaState main = LuaToThread (L1, -1); LuaPop (L1, 1); return main; } } }
//========================================================================================== // // OpenNETCF.IO.Serial.PortCapabilities // Copyright (c) 2004, OpenNETCF.org // // This library is free software; you can redistribute it and/or modify it under // the terms of the OpenNETCF.org Shared Source License. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License // for more details. // // You should have received a copy of the OpenNETCF.org Shared Source License // along with this library; if not, email licensing@opennetcf.org to request a copy. // // If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please // email licensing@opennetcf.org. // // For general enquiries, email enquiries@opennetcf.org or visit our website at: // http://www.opennetcf.org // //========================================================================================== using System; using System.Runtime.InteropServices; using System.Collections.Specialized; namespace OpenNETCF.IO.Serial { // // Serial provider type. // /// <summary> /// SEP enumerates known serial provider types. Currently SERIALCOMM is the only /// provider in this enumeration. /// </summary> [Flags] public enum SEP { /// <summary> /// SERIALCOMM is the only service provider supported by serial APIs. /// </summary> SEP_SERIALCOMM = 0x00000001 }; // // Provider SubTypes // /// <summary> /// PST enumerates the provider subtypes supported by the WIN32 serial APIs. PST indicates which /// Port is used for serial communication. Ports can either be physical or logical devices. /// </summary> public enum PST { /// <summary> /// no provider subtype specified /// </summary> PST_UNSPECIFIED = 0x00000000, /// <summary> /// RS232 Port /// </summary> PST_RS232 = 0x00000001, /// <summary> /// parallel port /// </summary> PST_PARALLELPORT = 0x00000002, /// <summary> /// RS422 Port /// </summary> PST_RS422 = 0x00000003, /// <summary> /// RS423 Port /// </summary> PST_RS423 = 0x00000004, /// <summary> /// RS449 Port /// </summary> PST_RS449 = 0x00000005, /// <summary> /// Modem /// </summary> PST_MODEM = 0x00000006, /// <summary> /// Fax /// </summary> PST_FAX = 0x00000021, /// <summary> /// Scanner /// </summary> PST_SCANNER = 0x00000022, /// <summary> /// unspecified network bridge /// </summary> PST_NETWORK_BRIDGE = 0x00000100, /// <summary> /// DEC's LAT Port /// </summary> PST_LAT = 0x00000101, /// <summary> /// Telnet connection /// </summary> PST_TCPIP_TELNET = 0x00000102, /// <summary> /// X.25 standard /// </summary> PST_X25 = 0x00000103 }; // // Provider capabilities flags. // /// <summary> /// PCF enumerates the provider capabilites supported by the specified COMx: Port. This enumeration /// is used internaly only. Access to this bitfield information is provided through attributes of the /// CommProp class. /// </summary> [Flags] internal enum PCF { PCF_DTRDSR = 0x0001, PCF_RTSCTS = 0x0002, PCF_RLSD = 0x0004, PCF_PARITY_CHECK = 0x0008, PCF_XONXOFF = 0x0010, PCF_SETXCHAR = 0x0020, PCF_TOTALTIMEOUTS= 0x0040, PCF_INTTIMEOUTS = 0x0080, PCF_SPECIALCHARS = 0x0100, PCF_16BITMODE = 0x0200 }; // // Comm provider settable parameters. // /// <summary> /// SP /// </summary> [Flags] internal enum SP { SP_PARITY = 0x0001, SP_BAUD = 0x0002, SP_DATABITS = 0x0004, SP_STOPBITS = 0x0008, SP_HANDSHAKING = 0x0010, SP_PARITY_CHECK = 0x0020, SP_RLSD = 0x0040 }; // // Settable baud rates in the provider. // /// <summary> /// baud rates settable by Comm API /// </summary> [Flags] public enum BAUD { /// <summary> /// 75 bits per second /// </summary> BAUD_075 = 0x00000001, /// <summary> /// 110 bits per second /// </summary> BAUD_110 = 0x00000002, /// <summary> /// 134.5 bits per second /// </summary> BAUD_134_5 = 0x00000004, /// <summary> /// 150 bits per second /// </summary> BAUD_150 = 0x00000008, /// <summary> /// 300 bits per second /// </summary> BAUD_300 = 0x00000010, /// <summary> /// 600 bits per second /// </summary> BAUD_600 = 0x00000020, /// <summary> /// 1,200 bits per second /// </summary> BAUD_1200 = 0x00000040, /// <summary> /// 1,800 bits per second /// </summary> BAUD_1800 = 0x00000080, /// <summary> /// 2,400 bits per second /// </summary> BAUD_2400 = 0x00000100, /// <summary> /// 4,800 bits per second /// </summary> BAUD_4800 = 0x00000200, /// <summary> /// 7,200 bits per second /// </summary> BAUD_7200 = 0x00000400, /// <summary> /// 9,600 bits per second /// </summary> BAUD_9600 = 0x00000800, /// <summary> /// 14,400 bits per second /// </summary> BAUD_14400 = 0x00001000, /// <summary> /// 19,200 bits per second /// </summary> BAUD_19200 = 0x00002000, /// <summary> /// 38,400 bits per second /// </summary> BAUD_38400 = 0x00004000, /// <summary> /// 56 Kbits per second /// </summary> BAUD_56K = 0x00008000, /// <summary> /// 129 Kbits per second /// </summary> BAUD_128K = 0x00010000, /// <summary> /// 115,200 bits per second /// </summary> BAUD_115200 = 0x00020000, /// <summary> /// 57,600 bits per second /// </summary> BAUD_57600 = 0x00040000, /// <summary> /// User defined bitrates /// </summary> BAUD_USER = 0x10000000 }; // // Settable Data Bits // [Flags] internal enum DB { DATABITS_5 = 0x0001, DATABITS_6 = 0x0002, DATABITS_7 = 0x0004, DATABITS_8 = 0x0008, DATABITS_16 = 0x0010, DATABITS_16X = 0x0020 }; // // Settable Stop and Parity bits. // [Flags] internal enum SB { STOPBITS_10 = 0x00010000, STOPBITS_15 = 0x00020000, STOPBITS_20 = 0x00040000, PARITY_NONE = 0x01000000, PARITY_ODD = 0x02000000, PARITY_EVEN = 0x04000000, PARITY_MARK = 0x08000000, PARITY_SPACE = 0x10000000 }; // // Set dwProvSpec1 to COMMPROP_INITIALIZED to indicate that wPacketLength // is valid when calling GetCommProperties(). // [Flags] internal enum CPS:uint { COMMPROP_INITIALIZED= 0xE73CF52E }; /// <summary> /// Container for all available information on port's capabilties /// </summary> [StructLayout(LayoutKind.Sequential)] public class CommCapabilities { private UInt16 wPacketLength; private UInt16 wPacketVersion; /// <summary> /// Indicates which services are supported by the port. SP_SERIALCOMM is specified for communication /// providers, including modem providers. /// </summary> public IO.Serial.SEP dwServiceMask; private UInt32 dwReserved1; /// <summary> /// Specifies the maximum size, in bytes, of the driver's internal output buffer. A value of zero /// indicates that no maximum value is imposed by the driver. /// </summary> [CLSCompliant(false)] public UInt32 dwMaxTxQueue; /// <summary> /// Specifies the maximum size, in bytes, of the driver's internal input buffer. A value of zero /// indicates that no maximum value is imposed by the driver. /// </summary> [CLSCompliant(false)] public UInt32 dwMaxRxQueue; /// <summary> /// Specifies the maximum baud rate, in bits per second (bps). /// </summary> public IO.Serial.BAUD dwMaxBaud; /// <summary> /// Specifies the communication provider type. /// </summary> public IO.Serial.PST dwProvSubType; private BitVector32 dwProvCapabilities; private BitVector32 dwSettableParams; private BitVector32 dwSettableBaud; private BitVector32 dwSettableStopParityData; /// <summary> /// Specifies the size, in bytes, of the driver's internal output buffer. A value of zero indicates /// that the value is unavailable. /// </summary> [CLSCompliant(false)] public UInt32 dwCurrentTxQueue; /// <summary> /// Specifies the size, in bytes, of the driver's internal input buffer. A value of zero indicates /// that the value is unavailable. /// </summary> [CLSCompliant(false)] public UInt32 dwCurrentRxQueue; private IO.Serial.CPS dwProvSpec1; private UInt32 dwProvSpec2; private UInt16 wcProvChar; internal CommCapabilities() { this.wPacketLength=(ushort)Marshal.SizeOf(this); this.dwProvSpec1=CPS.COMMPROP_INITIALIZED; dwProvCapabilities=new BitVector32(0); dwSettableParams=new BitVector32(0); dwSettableBaud=new BitVector32(0); dwSettableStopParityData=new BitVector32(0); } // // We need to have to define reserved fields in the CommCapabilties class definition // to preserve the size of the // underlying structure to match the Win32 structure when it is // marshaled. Use these fields to suppress compiler warnings. // internal void _SuppressCompilerWarnings() { wPacketVersion +=0; dwReserved1 +=0; dwProvSpec1 +=0; dwProvSpec2 +=0; wcProvChar +=0; } // Provider Capabilties /// <summary> /// Port supports special 16-bit mode /// </summary> public bool Supports16BitMode { get { return dwProvCapabilities[(int)PCF.PCF_16BITMODE]; } } /// <summary> /// Port supports DTR (Data Terminal ready) and DSR (Data Set Ready) flow control /// </summary> public bool SupportsDtrDts { get { return dwProvCapabilities[(int)PCF.PCF_DTRDSR]; } } /// <summary> /// Port supports interval timeouts /// </summary> public bool SupportsIntTimeouts { get { return dwProvCapabilities[(int)PCF.PCF_INTTIMEOUTS]; } } /// <summary> /// Port supports parity checking /// </summary> public bool SupportsParityCheck { get { return dwProvCapabilities[(int)PCF.PCF_PARITY_CHECK]; } } /// <summary> /// Port supports RLSD (Receive Line Signal Detect) /// </summary> public bool SupportsRlsd { get { return dwProvCapabilities[(int)PCF.PCF_RLSD]; } } /// <summary> /// Port supports RTS (Request To Send) and CTS (Clear To Send) flowcontrol /// </summary> public bool SupportsRtsCts { get { return dwProvCapabilities[(int)PCF.PCF_RTSCTS]; } } /// <summary> /// Port supports user definded characters for XON and XOFF /// </summary> public bool SupportsSetXChar { get { return dwProvCapabilities[(int)PCF.PCF_SETXCHAR]; } } /// <summary> /// Port supports special characters /// </summary> public bool SupportsSpecialChars { get { return dwProvCapabilities[(int)PCF.PCF_SPECIALCHARS]; } } /// <summary> /// Port supports total and elapsed time-outs /// </summary> public bool SupportsTotalTimeouts { get { return dwProvCapabilities[(int)PCF.PCF_TOTALTIMEOUTS]; } } /// <summary> /// Port supports XON/XOFF flow control /// </summary> public bool SupportsXonXoff { get { return dwProvCapabilities[(int)PCF.PCF_XONXOFF]; } } // Settable Params /// <summary> /// Baud rate can be set /// </summary> public bool SettableBaud { get { return dwSettableParams[(int)SP.SP_BAUD]; } } /// <summary> /// Number of data bits can be set /// </summary> public bool SettableDataBits { get { return dwSettableParams[(int)SP.SP_DATABITS]; } } /// <summary> /// Handshake protocol can be set /// </summary> public bool SettableHandShaking { get { return dwSettableParams[(int)SP.SP_HANDSHAKING]; } } /// <summary> /// Number of parity bits can be set /// </summary> public bool SettableParity { get { return dwSettableParams[(int)SP.SP_PARITY]; } } /// <summary> /// Parity check can be enabled/disabled /// </summary> public bool SettableParityCheck { get { return dwSettableParams[(int)SP.SP_PARITY_CHECK]; } } /// <summary> /// Receive Line Signal detect can be enabled/disabled /// </summary> public bool SettableRlsd { get { return dwSettableParams[(int)SP.SP_RLSD]; } } /// <summary> /// Number of stop bits can be set /// </summary> public bool SettableStopBits { get { return dwSettableParams[(int)SP.SP_STOPBITS]; } } // Settable Databits /// <summary> /// Port supports 5 data bits /// </summary> public bool Supports5DataBits { get { return dwSettableStopParityData[(int)DB.DATABITS_5]; } } /// <summary> /// Port supports 6 data bits /// </summary> public bool Supports6DataBits { get { return dwSettableStopParityData[(int)DB.DATABITS_6]; } } /// <summary> /// Port supports 7 data bits /// </summary> public bool Supports7DataBits { get { return dwSettableStopParityData[(int)DB.DATABITS_7]; } } /// <summary> /// Port supports 8 data bits /// </summary> public bool Supports8DataBits { get { return dwSettableStopParityData[(int)DB.DATABITS_8]; } } /// <summary> /// Port supports 16 data bits /// </summary> public bool Supports16DataBits { get { return dwSettableStopParityData[(int)DB.DATABITS_16]; } } /// <summary> /// Port supports special wide data path through serial hardware lines /// </summary> public bool Supports16XDataBits { get { return dwSettableStopParityData[(int)DB.DATABITS_16X]; } } // Settable Stop /// <summary> /// Port supports even parity /// </summary> public bool SupportsParityEven { get { return dwSettableStopParityData[(int)SB.PARITY_EVEN]; } } /// <summary> /// Port supports mark parity /// </summary> public bool SupportsParityMark { get { return dwSettableStopParityData[(int)SB.PARITY_MARK]; } } /// <summary> /// Port supports none parity /// </summary> public bool SupportsParityNone { get { return dwSettableStopParityData[(int)SB.PARITY_NONE]; } } /// <summary> /// Port supports odd parity /// </summary> public bool SupportsParityOdd { get { return dwSettableStopParityData[(int)SB.PARITY_ODD]; } } /// <summary> /// Port supports space parity /// </summary> public bool SupportsParitySpace { get { return dwSettableStopParityData[(int)SB.PARITY_SPACE]; } } /// <summary> /// Port supports 1 stop bit /// </summary> public bool SupportsStopBits10 { get { return dwSettableStopParityData[(int)SB.STOPBITS_10]; } } /// <summary> /// Port supports 1.5 stop bits /// </summary> public bool SupportsStopBits15 { get { return dwSettableStopParityData[(int)SB.STOPBITS_15]; } } /// <summary> /// Port supports 2 stop bits /// </summary> public bool SupportsStopBits20 { get { return dwSettableStopParityData[(int)SB.STOPBITS_20]; } } // settable Baud Rates /// <summary> /// Port can be set to 75 bits per second /// </summary> public bool HasBaud75 { get { return dwSettableBaud[(int)BAUD.BAUD_075];} } /// <summary> /// Port can be set to 110 bits per second /// </summary> public bool HasBaud110 { get { return dwSettableBaud[(int)BAUD.BAUD_110];} } /// <summary> /// Port can be set to 134.5 bits per second /// </summary> public bool HasBaud134_5 { get { return dwSettableBaud[(int)BAUD.BAUD_134_5];} } /// <summary> /// Port can be set to 150 bits per second /// </summary> public bool HasBaud150 { get { return dwSettableBaud[(int)BAUD.BAUD_150];} } /// <summary> /// Port can be set to 300 bits per second /// </summary> public bool HasBaud300 { get { return dwSettableBaud[(int)BAUD.BAUD_300];} } /// <summary> /// Port can be set to 600 bits per second /// </summary> public bool HasBaud600 { get { return dwSettableBaud[(int)BAUD.BAUD_600];} } /// <summary> /// Port can be set to 1,200 bits per second /// </summary> public bool HasBaud1200 { get { return dwSettableBaud[(int)BAUD.BAUD_1200];} } /// <summary> /// Port can be set to 2,400 bits per second /// </summary> public bool HasBaud2400 { get { return dwSettableBaud[(int)BAUD.BAUD_2400];} } /// <summary> /// Port can be set to 4,800 bits per second /// </summary> public bool HasBaud4800 { get { return dwSettableBaud[(int)BAUD.BAUD_4800];} } /// <summary> /// Port can be set to 7,200 bits per second /// </summary> public bool HasBaud7200 { get { return dwSettableBaud[(int)BAUD.BAUD_7200];} } /// <summary> /// Port can be set to 9,600 bits per second /// </summary> public bool HasBaud9600 { get { return dwSettableBaud[(int)BAUD.BAUD_9600];} } /// <summary> /// Port can be set to 14,400 bits per second /// </summary> public bool HasBaud14400 { get { return dwSettableBaud[(int)BAUD.BAUD_14400];} } /// <summary> /// Port can be set to 19,200 bits per second /// </summary> public bool HasBaud19200 { get { return dwSettableBaud[(int)BAUD.BAUD_19200];} } /// <summary> /// Port can be set to 38,400 bits per second /// </summary> public bool HasBaud38400 { get { return dwSettableBaud[(int)BAUD.BAUD_38400];} } /// <summary> /// Port can be set to 56 Kbits per second /// </summary> public bool HasBaud56K { get { return dwSettableBaud[(int)BAUD.BAUD_56K];} } /// <summary> /// Port can be set to 128 Kbits per second /// </summary> public bool HasBaud128K { get { return dwSettableBaud[(int)BAUD.BAUD_128K];} } /// <summary> /// Port can be set to 115,200 bits per second /// </summary> public bool HasBaud115200 { get { return dwSettableBaud[(int)BAUD.BAUD_115200];} } /// <summary> /// Port can be set to 57,600 bits per second /// </summary> public bool HasBaud57600 { get { return dwSettableBaud[(int)BAUD.BAUD_57600];} } /// <summary> /// Port can be set to user defined bit rate /// </summary> public bool HasBaudUser { get { return dwSettableBaud[(int)BAUD.BAUD_USER];} } }; }
#region Copyright /* Copyright 2014 Cluster Reply s.r.l. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion /// ----------------------------------------------------------------------------------------------------------- /// Module : FtpAdapterInboundHandler.cs /// Description : This class implements an interface for listening or polling for data. /// ----------------------------------------------------------------------------------------------------------- /// #region Using Directives using System; using System.Collections.Generic; using System.Text; using Microsoft.ServiceModel.Channels.Common; using System.Threading; using System.Collections.Concurrent; using System.IO; using System.Net.FtpClient; using System.Net; using Reply.Cluster.Mercury.Adapters.Helpers; using System.ServiceModel.Channels; #endregion namespace Reply.Cluster.Mercury.Adapters.Ftp { public class FtpAdapterInboundHandler : FtpAdapterHandlerBase, IInboundHandler { private class FileItem { public FileItem(FtpClient client, string path, Stream stream) { Client = client; Path = path; Stream = stream; } public FtpClient Client { get; private set; } public string Path { get; private set; } public Stream Stream { get; private set; } } /// <summary> /// Initializes a new instance of the FtpAdapterInboundHandler class /// </summary> public FtpAdapterInboundHandler(FtpAdapterConnection connection , MetadataLookup metadataLookup) : base(connection, metadataLookup) { connectionUri = connection.ConnectionFactory.ConnectionUri; filter = new Wildcard(connectionUri.FileName); pollingType = connection.ConnectionFactory.Adapter.PollingType; if (pollingType == PollingType.Simple) { pollingInterval = connection.ConnectionFactory.Adapter.PollingInterval; pollingTimer = new Timer(new TimerCallback(t => GetFiles())); } else scheduleName = connection.ConnectionFactory.Adapter.ScheduleName; } #region Private Fields private FtpAdapterConnectionUri connectionUri; private Wildcard filter; private PollingType pollingType; private int pollingInterval; private Timer pollingTimer; private string scheduleName; private BlockingCollection<FileItem> queue = new BlockingCollection<FileItem>(); private CancellationTokenSource cancelSource = new CancellationTokenSource(); #endregion Private Fields #region IInboundHandler Members /// <summary> /// Start the listener /// </summary> public void StartListener(string[] actions, TimeSpan timeout) { if (pollingType == PollingType.Simple) pollingTimer.Change(0, pollingInterval * 1000); else ScheduleHelper.RegisterEvent(scheduleName, () => GetFiles()); } /// <summary> /// Stop the listener /// </summary> public void StopListener(TimeSpan timeout) { if (pollingType == PollingType.Simple) pollingTimer.Change(Timeout.Infinite, Timeout.Infinite); else ScheduleHelper.CancelEvent(scheduleName); queue.CompleteAdding(); cancelSource.Cancel(); } /// <summary> /// Tries to receive a message within a specified interval of time. /// </summary> public bool TryReceive(TimeSpan timeout, out System.ServiceModel.Channels.Message message, out IInboundReply reply) { reply = null; message = null; if (queue.IsCompleted) return false; FileItem item = null; bool result = queue.TryTake(out item, (int)Math.Min(timeout.TotalMilliseconds, (long)int.MaxValue), cancelSource.Token); if (result) { Uri originalUri = connectionUri.Uri; message = ByteStreamMessage.CreateMessage(item.Stream); message.Headers.Action = new UriBuilder(originalUri.Scheme, originalUri.Host, originalUri.Port, item.Path).Uri.ToString(); reply = new FtpAdapterInboundReply(item.Client, item.Path, item.Stream); } return result; } /// <summary> /// Returns a value that indicates whether a message has arrived within a specified interval of time. /// </summary> public bool WaitForMessage(TimeSpan timeout) { return true; } #endregion IInboundHandler Members #region Private Members private void GetFiles() { var client = Connection.Client; var files = client.GetListing(connectionUri.Path); foreach (var file in files) if (filter.IsMatch(file.Name)) { string path = file.FullName; try { var stream = client.OpenRead(path); queue.Add(new FileItem(client, path, stream)); } catch (FtpException) { } } } #endregion } internal class FtpAdapterInboundReply : InboundReply { private FtpClient client; private Stream stream; private string path; public FtpAdapterInboundReply(FtpClient client, string path, Stream stream) { this.client = client; this.path = path; this.stream = stream; } #region InboundReply Members /// <summary> /// Abort the inbound reply call /// </summary> public override void Abort() { stream.Close(); } /// <summary> /// Reply message implemented /// </summary> public override void Reply(System.ServiceModel.Channels.Message message , TimeSpan timeout) { client.DeleteFile(path); stream.Close(); } #endregion InboundReply Members } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using Trisoft.ISHRemote.HelperClasses; namespace Trisoft.ISHRemote.Objects { /// <summary> /// <para type="description">Contains all enumerations and conversion required for this client library</para> /// </summary> public class Enumerations { /// <summary> /// <para type="description">Which card or table level should the field be present on. The int assignment allows sorting so Logical before Version before Language.</para> /// </summary> public enum Level { [StringValue("none")] None = 100, [StringValue("logical")] Logical = 200, [StringValue("version")] Version = 210, [StringValue("lng")] Lng = 220, [StringValue("progress")] Progress = 300, [StringValue("detail")] Detail = 310, [StringValue("data")] Data = 320, [StringValue("task")] Task = 400, [StringValue("history")] History = 410, [StringValue("annotation")] Annotation = 500, [StringValue("reply")] Reply = 510 } /// <summary> /// <para type="description">Which data type to retrieve from the database for the specified field</para> /// </summary> public enum ValueType { /// <summary> /// The value of the ishfield. /// </summary> [StringValue("value")] Value, /// <summary> /// The GUID of the ishfield. /// </summary> [StringValue("element")] Element, /// <summary> /// The Id of the ishfield. /// </summary> [StringValue("id")] Id, /// <summary> /// All is used when the valuetype is irrelevant. /// For example when a field needs to be removed and you do not want to loop all different value types. /// </summary> /// TODO [Must] IshTypeFieldSetup - Remove confuzing value 'All' for ValueType usage, can be done once IshSession.IshTypeFieldSetup is implemented (see [ISHREMOTE-017]) [StringValue("")] All } /// <summary> /// <para type="description">Allows tuning client-side metadata handling/warning since the IshTypeFieldSetup introduction.</para> /// </summary> public enum StrictMetadataPreference { /// <summary> /// Client-side silent filtering of nonexisting and unallowed fields. (e.g Nice for repository folder syncing with mismatching metadata setup) /// </summary> [StringValue("silentlycontinue")] SilentlyContinue, /// <summary> /// Client-side filtering of nonexisting and unallowed fields displaying a Write-Verbose message but still continues. /// </summary> [StringValue("continue")] Continue, /// <summary> /// Client-side filtering of nonexisting and unallowed fields is turned off. No handling but simply executes the API call, most /// likely resulting in a Write-Error. This allows api/pester tests like IshUser PASSWORD field should not allowed to be read. /// </summary> [StringValue("off")] Off } /// <summary> /// <para type="description">Allows tuning client-side object enrichment like no wrapping (off) or PSObject-with-PSNoteProperty wrapping.</para> /// </summary> public enum PipelineObjectPreference { /// <summary> /// Wrap every possible pipeline object with PSObject and add PSNoteProperty for all IshFields /// </summary> [StringValue("psobjectnoteproperty")] PSObjectNoteProperty, /// <summary> /// Deprecated legacy behavior (0.6 and earlier), so no pipeline PSObject wrapping /// </summary> [StringValue("off")] Off } public enum RequestedMetadataGroup { /// <summary> /// performance-optimized, only primary keys /// </summary> [StringValue("descriptive")] Descriptive, /// <summary> /// user friendly fields used in tables /// </summary> [StringValue("basic")] Basic, // <summary> // not performant, tech fields only // </summary> //[StringValue("system")] //System, /// <summary> /// not performant /// </summary> [StringValue("all")] All } /// <summary> /// <para type="description">List of value like Events can be hidden upon Find/Retrieval with these filters</para> /// </summary> public enum ActivityFilter { [StringValue("none")] None, [StringValue("active")] Active, [StringValue("inactive")] Inactive } /// <summary> /// <para type="description">When filtering information having certain value(s), you need operators per field</para> /// </summary> public enum FilterOperator { [StringValue("equal")] Equal, [StringValue("notequal")] NotEqual, [StringValue("in")] In, [StringValue("notin")] NotIn, [StringValue("like")] Like, [StringValue("greaterthan")] GreaterThan, [StringValue("lessthan")] LessThan, [StringValue("greaterthanorequal")] GreaterThanOrEqual, [StringValue("lessthanorequal")] LessThanOrEqual, [StringValue("between")] Between, [StringValue("empty")] Empty, [StringValue("notempty")] NotEmpty } /// <summary> /// <para type="description">If two fields should be first, should the second value overwrite the first or prepend/append it</para> /// </summary> public enum ValueAction { [StringValue("overwrite")] Overwrite, [StringValue("prepend")] Prepend, [StringValue("append")] Append } /// <summary> /// <para type="description">Used by RemoveSystemFields to know which fields to filter. E.g. at creation time of a user PASSWORD is allowed, but not at retrieval time.</para> /// </summary> public enum ActionMode { Create, Read, Update, Delete, Find, Search } /// <summary> /// <para type="description">Used by IshObject/IshEvent/IshBackgroundTask to set all reference types on a card</para> /// </summary> public enum ReferenceType { [StringValue("ishlogicalref")] Logical, [StringValue("ishversionref")] Version, [StringValue("ishlngref")] Lng, [StringValue("ishbaselineref")] Baseline, [StringValue("ishoutputformatref")] OutputFormat, [StringValue("ishusergroupref")] UserGroup, [StringValue("ishuserref")] User, [StringValue("ishuserroleref")] UserRole, [StringValue("ishedtref")] EDT, [StringValue("ishprogressref")] EventProgress, [StringValue("ishdetailref")] EventDetail, [StringValue("ishtaskref")] BackgroundTask, [StringValue("ishhistoryref")] BackgroundTaskHistory, [StringValue("ishannotationref")] Annotation, [StringValue("ishreplyref")] AnnotationReply } /// <summary> /// <para type="description">Enumeration of all possible object types.</para> /// </summary> public enum ISHType { /// <summary> /// Initial value...we don't know what the ISHType is. /// </summary> ISHNone, /// <summary> /// The object does not exists /// </summary> ISHNotFound, /// <summary> /// InfoShare Module/IMAP-Map/DITA-Topic /// </summary> ISHModule, /// <summary> /// InfoShare MasterDocument/IMAP-Master/DITA-(Book)Map/DocumentOutline /// </summary> ISHMasterDoc, /// <summary> /// InfoShare Library /// </summary> ISHLibrary, /// <summary> /// InfoShare Template /// </summary> ISHTemplate, /// <summary> /// InfoShare Illustration/Image/Graphic /// </summary> ISHIllustration, /// <summary> /// InfoShare publication object /// </summary> ISHPublication, /// <summary> /// InfoShare user /// </summary> ISHUser, /// <summary> /// InfoShare usergroup (new name for department) /// </summary> ISHUserGroup, /// <summary> /// InfoShare user role /// </summary> ISHUserRole, /// <summary> /// The baseline /// </summary> ISHBaseline, /// <summary> /// InfoShare output format object /// </summary> ISHOutputFormat, /// <summary> /// Electronic Document Type /// </summary> ISHEDT, /// <summary> /// Folder/Directory /// </summary> ISHFolder, /// <summary> /// Translation job /// </summary> ISHTranslationJob, /// <summary> /// Configuration card /// </summary> ISHConfiguration, /// <summary> /// Electronic document/ED/Revision /// </summary> ISHRevision, /// <summary> /// Conditional Context, available on FISHCONTEXT (used to be saved on CTCONTEXT card type) /// </summary> ISHFeatures, /// <summary> /// Background Task table /// </summary> ISHBackgroundTask, /// <summary> /// Event Monitor table /// </summary> ISHEvent, /// <summary> /// Annotations /// </summary> ISHAnnotation } /// <summary> /// <para type="description">Enumeration of folder types.</para> /// </summary> public enum IshFolderType { /// <summary> /// In this folder no objects allowed except subfolders /// </summary> ISHNone, /// <summary> /// Folder with InfoShare Module/IMAP-Map/DITA-Topic /// </summary> ISHModule, /// <summary> /// Folder with InfoShare MasterDocument/IMAP-Master/DITA-(Book)Map/DocumentOutline /// </summary> ISHMasterDoc, /// <summary> /// Folder with InfoShare Library /// </summary> ISHLibrary, /// <summary> /// Folder with InfoShare Template /// </summary> ISHTemplate, /// <summary> /// Folder with InfoShare Illustration/Image/Graphic /// </summary> ISHIllustration, /// <summary> /// Folder with InfoShare publication object /// </summary> ISHPublication, /// <summary> /// Folder with Document references /// </summary> ISHReference, /// <summary> /// Query Folders /// </summary> ISHQuery } /// <summary> /// /// <para type="description">Enumerations for controlled date types, used by IshTypeFieldDefinition. Holding base types like number, long, etc</para> /// </summary> public enum DataType { /// <summary> /// The field data type is a reference field pointing to a List Of Values (DOMAIN) /// </summary> ISHLov, /// <summary> /// The field data type is a reference field pointing to another ISHType (CARD REFERENCE) /// </summary> ISHType, /// <summary> /// The field data type is a simple text type, preferred for shorting string values with the most API operators /// </summary> String, /// <summary> /// The field data type is a simple text type, preferred for longer string values with less API operators (only empty/notempty) /// </summary> LongText, /// <summary> /// The field data type is a simple controlled decimal type /// </summary> Number, /// <summary> /// The field data type is a simple controlled date time type /// </summary> DateTime, /// <summary> /// The field data type used to describe metadata bound fields /// </summary> ISHMetadataBinding } /// <summary> /// <para type="description">Enumerations of basefolders</para> /// </summary> public enum BaseFolder { /// <summary> /// Indicates the Data folder as starting point. Also known as 'General', 'ISREPROOT', normal repository content,... /// </summary> Data, /// <summary> /// Indicates the System folder as starting point /// </summary> System, /// <summary> /// Indicates the User's favorite folder as starting point /// </summary> Favorites, /// <summary> /// Indicates the 'Editor Template' folder as starting point /// </summary> EditorTemplate, } /// <summary> /// <para type="description">Enumeration matching the API status filters for IshObjects</para> /// </summary> public enum StatusFilter { /// <summary> /// Released states only /// </summary> ISHReleasedStates, /// <summary> /// Released or Draft states /// </summary> ISHReleasedOrDraftStates, /// <summary> /// Out of date or Released states /// </summary> ISHOutOfDateOrReleasedStates, /// <summary> /// No status filter /// </summary> ISHNoStatusFilter } /// <summary> /// <para type="description">BackgroundTask Status Filter</para> /// </summary> public enum BackgroundTaskStatusFilter { /// <summary> /// Filtering on the status Busy will return all with status: VBACKGROUNDTASKSTATUSEXECUTING, VBACKGROUNDTASKSTATUSPENDING /// </summary> Busy, /// <summary> /// Filtering on the status Success will return all with status: VBACKGROUNDTASKSTATUSSUCCESS, VBACKGROUNDTASKSTATUSSKIPPED /// </summary> Success, /// <summary> /// Filtering on the status Failed will return all with status: VBACKGROUNDTASKSTATUSFAILED, VBACKGROUNDTASKSTATUSABORTED (NotUsedIn-13.0.1), VBACKGROUNDTASKSTATUSCANCELPENDING (NotUsedIn-13.0.1), VBACKGROUNDTASKSTATUSCANCELLED (NotUsedIn-13.0.1) /// </summary> Failed, /// <summary> /// No filtering on the status is applied /// </summary> All } /// <summary> /// <para type="description">EventMonitor Events Status Filter</para> /// </summary> public enum ProgressStatusFilter { /// <summary> /// Filtering on the status Busy will return all events which are still busy /// </summary> Busy, /// <summary> /// Filtering on the status Success will return all events which are completed successfully /// </summary> Success, /// <summary> /// Filtering on the status Success will return all events with warnings /// </summary> Warning, /// <summary> /// Filtering on the status Failed will return all failed events /// </summary> Failed, /// <summary> /// No filtering on the status is applied /// </summary> All } /// <summary> /// <para type="description">EventMonitor Events User Filter</para> /// </summary> public enum UserFilter { /// <summary> /// Used to indicate that only the events of the current user should be returned /// </summary> Current, /// <summary> /// Used to indicate that all events should be returned /// </summary> All } /// <summary> /// <para type="description">Possible values for the level of an event detail</para> /// </summary> public enum EventLevel { /// <summary> /// Indicates that the event detail contains an error /// </summary> Exception, /// <summary> /// Indicates that the event detail contains a noncritical problem /// </summary> Warning, /// <summary> /// Indicates that the event detail contains a configuration message /// </summary> Configuration, /// <summary> /// Indicates that the event detail contains an informational message /// </summary> Information, /// <summary> /// Indicates that the event detail contains a verbose message /// </summary> Verbose, /// <summary> /// Indicates that the event detail contains a debug message /// </summary> Debug } /// <summary> /// <para type="description">Possible values for the source enumeration of a baseline entry</para> /// </summary> public enum BaselineSourceEnumeration { SaveManual, SaveLatestAvailable, SaveLatestReleased, SaveByBaseline, SaveCandidate, SaveFirstVersion, SaveCopy, Manual, ExpandNone, ExpandLatestAvailable, ExpandLatestReleased, ExpandByBaseline, ExpandCandidate, ExpandFirstVersion, } /// <summary> /// Unique descriptive identifier of an IshTypeFieldDefinition concatenating type, level (respecting log/version/lng), and field name /// </summary> internal static string Key(Enumerations.ISHType ishType, Enumerations.Level level, string fieldName) { return ishType + "=" + (int)level + level + "=" + fieldName; } /// <summary> /// Extracts the TriDK CardType level from input like USER, CTMAPL,... /// </summary> internal static Level ToLevelFromCardType(string cardType) { switch (cardType) { case "CTMASTER": case "CTMAP": case "CTIMG": case "CTTEMPLATE": case "CTLIB": case "CTREUSEOBJ": // obsolete card type, but added for completeness case "CTPUBLICATION": return Level.Logical; case "CTMASTERV": case "CTMAPV": case "CTIMGV": case "CTTEMPLATEV": case "CTLIBV": case "CTREUSEOBJV": // obsolete card type, but added for completeness case "CTPUBLICATIONV": return Level.Version; case "CTMASTERL": case "CTMAPL": case "CTIMGL": case "CTTEMPLATEL": case "CTLIBL": case "CTREUSEOBJL": // obsolete card type, but added for completeness case "CTPUBLICATIONOUTPUT": return Level.Lng; default: return Level.None; } } /// <summary> /// Extracts the TriDK CardType type from input like USER, CTMAPL,... /// </summary> internal static ISHType ToIshTypeFromCardType(string cardType) { switch (cardType) { case "CTMASTER": case "CTMASTERV": case "CTMASTERL": return ISHType.ISHMasterDoc; case "CTMAP": case "CTMAPV": case "CTMAPL": return ISHType.ISHModule; case "CTIMG": case "CTIMGV": case "CTIMGL": return ISHType.ISHIllustration; case "CTTEMPLATE": case "CTTEMPLATEV": case "CTTEMPLATEL": return ISHType.ISHTemplate; case "CTLIB": case "CTLIBV": case "CTLIBL": return ISHType.ISHLibrary; case "CTPUBLICATION": case "CTPUBLICATIONV": case "CTPUBLICATIONOUTPUT": return ISHType.ISHPublication; case "USER": return ISHType.ISHUser; case "CTUSERROLE": return ISHType.ISHUserRole; case "CTUSERGROUP": return ISHType.ISHUserGroup; case "ELECTRONIC DOCUMENT": return ISHType.ISHRevision; case "CTDOCMAP": return ISHType.ISHFolder; case "CTCONFIGURATION": return ISHType.ISHConfiguration; case "EDT": return ISHType.ISHEDT; case "CTOUTPUTFORMAT": return ISHType.ISHOutputFormat; case "CTBASELINE": return ISHType.ISHBaseline; case "CTCONTEXT": // obsolete card type, but added for completeness return ISHType.ISHFeatures; case "CTTRANSJOB": return ISHType.ISHTranslationJob; case "CTREUSEOBJ": // obsolete card type, but added for completeness case "CTREUSEOBJV": // obsolete card type, but added for completeness case "CTREUSEOBJL": // obsolete card type, but added for completeness default: return ISHType.ISHNotFound; } } /// <summary> /// Extracts the baseline source enumeration /// </summary> internal static BaselineSourceEnumeration ToBaselineSourceEnumeration(string source) { switch (source) { case "save:Manual": return BaselineSourceEnumeration.SaveManual; case "save:LatestAvailable": return BaselineSourceEnumeration.SaveLatestAvailable; case "save:LatestReleased": return BaselineSourceEnumeration.SaveLatestReleased; case "save:ByBaseline": return BaselineSourceEnumeration.SaveByBaseline; case "save:Candidate": return BaselineSourceEnumeration.SaveCandidate; case "save:FirstVersion": return BaselineSourceEnumeration.SaveFirstVersion; case "save:Copy": return BaselineSourceEnumeration.SaveCopy; case "Manual": return BaselineSourceEnumeration.Manual; case "expand:None": return BaselineSourceEnumeration.ExpandNone; case "expand:LatestAvailable": return BaselineSourceEnumeration.ExpandLatestAvailable; case "expand:LatestReleased": return BaselineSourceEnumeration.ExpandLatestReleased; case "expand:ByBaseline": return BaselineSourceEnumeration.ExpandByBaseline; case "expand:Candidate": return BaselineSourceEnumeration.ExpandCandidate; case "expand:FirstVersion": return BaselineSourceEnumeration.ExpandFirstVersion; default: return BaselineSourceEnumeration.Manual; } } } }
//----------------------------------------------------------------------- // <copyright file="FilePublisher.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading.Tasks; using Akka.Actor; using Akka.Event; using Akka.IO; using Akka.Streams.Actors; using Akka.Streams.IO; #pragma warning disable 1587 namespace Akka.Streams.Implementation.IO { /// <summary> /// INTERNAL API /// </summary> internal class FilePublisher : Actors.ActorPublisher<ByteString> { /// <summary> /// TBD /// </summary> /// <param name="f">TBD</param> /// <param name="completionPromise">TBD</param> /// <param name="chunkSize">TBD</param> /// <param name="startPosition">TBD</param> /// <param name="initialBuffer">TBD</param> /// <param name="maxBuffer">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when one of the following conditions is met. /// /// <ul> /// <li>The specified <paramref name="chunkSize"/> is less than or equal to zero.</li> /// <li>The specified <paramref name="startPosition"/> is less than zero</li> /// <li>The specified <paramref name="initialBuffer"/> is less than or equal to zero.</li> /// <li>The specified <paramref name="maxBuffer"/> is less than the specified <paramref name="initialBuffer"/>.</li> /// </ul> /// </exception> /// <returns>TBD</returns> public static Props Props(FileInfo f, TaskCompletionSource<IOResult> completionPromise, int chunkSize, long startPosition, int initialBuffer, int maxBuffer) { if (chunkSize <= 0) throw new ArgumentException($"chunkSize must be > 0 (was {chunkSize})", nameof(chunkSize)); if(startPosition < 0) throw new ArgumentException($"startPosition must be >= 0 (was {startPosition})", nameof(startPosition)); if (initialBuffer <= 0) throw new ArgumentException($"initialBuffer must be > 0 (was {initialBuffer})", nameof(initialBuffer)); if (maxBuffer < initialBuffer) throw new ArgumentException($"maxBuffer must be >= initialBuffer (was {maxBuffer})", nameof(maxBuffer)); return Actor.Props.Create(() => new FilePublisher(f, completionPromise, chunkSize, startPosition, maxBuffer)) .WithDeploy(Deploy.Local); } private struct Continue : IDeadLetterSuppression { public static readonly Continue Instance = new Continue(); } private readonly FileInfo _f; private readonly TaskCompletionSource<IOResult> _completionPromise; private readonly int _chunkSize; private readonly long _startPosition; private readonly int _maxBuffer; private readonly byte[] _buffer; private readonly ILoggingAdapter _log; private long _eofReachedAtOffset = long.MinValue; private long _readBytesTotal; private IImmutableList<ByteString> _availableChunks = ImmutableList<ByteString>.Empty; private FileStream _chan; /// <summary> /// TBD /// </summary> /// <param name="f">TBD</param> /// <param name="completionPromise">TBD</param> /// <param name="chunkSize">TBD</param> /// <param name="startPosition">TBD</param> /// <param name="maxBuffer">TBD</param> public FilePublisher(FileInfo f, TaskCompletionSource<IOResult> completionPromise, int chunkSize, long startPosition, int maxBuffer) { _f = f; _completionPromise = completionPromise; _chunkSize = chunkSize; _startPosition = startPosition; _maxBuffer = maxBuffer; _log = Context.GetLogger(); _buffer = new byte[chunkSize]; } private bool EofEncountered => _eofReachedAtOffset != long.MinValue; /// <summary> /// TBD /// </summary> protected override void PreStart() { try { _chan = _f.Open(FileMode.Open, FileAccess.Read); if (_startPosition > 0) _chan.Position = _startPosition; } catch (Exception ex) { _completionPromise.TrySetResult(IOResult.Failed(0, ex)); OnErrorThenStop(ex); } base.PreStart(); } /// <summary> /// TBD /// </summary> /// <param name="message">TBD</param> /// <returns>TBD</returns> protected override bool Receive(object message) => message.Match() .With<Request>(() => ReadAndSignal(_maxBuffer)) .With<Continue>(() => ReadAndSignal(_maxBuffer)) .With<Cancel>(() => Context.Stop(Self)) .WasHandled; private void ReadAndSignal(int maxReadAhead) { if (IsActive) { // Write previously buffered, then refill buffer _availableChunks = ReadAhead(maxReadAhead, SignalOnNexts(_availableChunks)); if (TotalDemand > 0 && IsActive) Self.Tell(Continue.Instance); } } private IImmutableList<ByteString> SignalOnNexts(IImmutableList<ByteString> chunks) { if (chunks.Count != 0 && TotalDemand > 0) { OnNext(chunks.First()); return SignalOnNexts(chunks.RemoveAt(0)); } if (chunks.Count == 0 && EofEncountered) OnCompleteThenStop(); return chunks; } //BLOCKING IO READ private IImmutableList<ByteString> ReadAhead(int maxChunks, IImmutableList<ByteString> chunks) { if (chunks.Count <= maxChunks && IsActive) { try { var readBytes = _chan.Read(_buffer, 0, _chunkSize); if (readBytes == 0) { //EOF _eofReachedAtOffset = _chan.Position; _log.Debug($"No more bytes available to read (got 0 from read), marking final bytes of file @ {_eofReachedAtOffset}"); return chunks; } _readBytesTotal += readBytes; var newChunks = chunks.Add(ByteString.CopyFrom(_buffer, 0, readBytes)); return ReadAhead(maxChunks, newChunks); } catch (Exception ex) { OnErrorThenStop(ex); //read failed, we're done here return ImmutableList<ByteString>.Empty; } } return chunks; } /// <summary> /// TBD /// </summary> protected override void PostStop() { base.PostStop(); try { _chan?.Dispose(); } catch (Exception ex) { _completionPromise.TrySetResult(IOResult.Failed(_readBytesTotal, ex)); } _completionPromise.TrySetResult(IOResult.Success(_readBytesTotal)); } } }
//#define ASTAR_NO_JSON using System; using UnityEngine; using Pathfinding.Serialization.JsonFx; using System.Collections.Generic; namespace Pathfinding.Serialization { public class UnityObjectConverter : JsonConverter { public override bool CanConvert (Type type) { return typeof(UnityEngine.Object).IsAssignableFrom (type); } public override object ReadJson ( Type objectType, Dictionary<string,object> values) { if (values == null) return null; //int instanceID = (int)values["InstanceID"]; string name = (string)values["Name"]; string typename = (string)values["Type"]; Type type = Type.GetType (typename); if (System.Type.Equals (type, null)) { Debug.LogError ("Could not find type '"+typename+"'. Cannot deserialize Unity reference"); return null; } if (values.ContainsKey ("GUID")) { string guid = (string)values["GUID"]; UnityReferenceHelper[] helpers = UnityEngine.Object.FindObjectsOfType(typeof(UnityReferenceHelper)) as UnityReferenceHelper[]; for (int i=0;i<helpers.Length;i++) { if (helpers[i].GetGUID () == guid) { if (System.Type.Equals ( type, typeof(GameObject) )) { return helpers[i].gameObject; } else { return helpers[i].GetComponent (type); } } } } //Try to load from resources UnityEngine.Object[] objs = Resources.LoadAll (name,type); for (int i=0;i<objs.Length;i++) { if (objs[i].name == name || objs.Length == 1) { return objs[i]; } } return null; } public override Dictionary<string,object> WriteJson (Type type, object value) { UnityEngine.Object obj = (UnityEngine.Object)value; Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add ("InstanceID",obj.GetInstanceID()); dict.Add ("Name",obj.name); dict.Add ("Type",obj.GetType().AssemblyQualifiedName); //Write scene path if the object is a Component or GameObject Component component = value as Component; GameObject go = value as GameObject; if (component != null || go != null) { if (component != null && go == null) { go = component.gameObject; } UnityReferenceHelper helper = go.GetComponent<UnityReferenceHelper>(); if (helper == null) { Debug.Log ("Adding UnityReferenceHelper to Unity Reference '"+obj.name+"'"); helper = go.AddComponent<UnityReferenceHelper>(); } //Make sure it has a unique GUID helper.Reset (); dict.Add ("GUID",helper.GetGUID ()); } return dict; } } public class GuidConverter : JsonConverter { public override bool CanConvert (Type type) { return System.Type.Equals ( type, typeof(Pathfinding.Util.Guid) ); } public override object ReadJson ( Type objectType, Dictionary<string,object> values) { string s = (string)values["value"]; return new Pathfinding.Util.Guid(s); } public override Dictionary<string,object> WriteJson (Type type, object value) { Pathfinding.Util.Guid m = (Pathfinding.Util.Guid)value; return new Dictionary<string, object>() {{"value",m.ToString()}}; } } public class MatrixConverter : JsonConverter { public override bool CanConvert (Type type) { return System.Type.Equals ( type, typeof(Matrix4x4) ); } public override object ReadJson ( Type objectType, Dictionary<string,object> values) { Matrix4x4 m = new Matrix4x4(); Array arr = (Array)values["values"]; if (arr.Length != 16) { Debug.LogError ("Number of elements in matrix was not 16 (got "+arr.Length+")"); return m; } for (int i=0;i<16;i++) m[i] = System.Convert.ToSingle (arr.GetValue(new int[] {i})); return m; } /** Just a temporary array of 16 floats. * Stores the elements of the matrices temporarily */ float[] values = new float[16]; public override Dictionary<string,object> WriteJson (Type type, object value) { Matrix4x4 m = (Matrix4x4)value; for (int i=0;i<values.Length;i++) values[i] = m[i]; return new Dictionary<string, object>() { {"values",values} }; } } public class BoundsConverter : JsonConverter { public override bool CanConvert (Type type) { return System.Type.Equals ( type, typeof(Bounds) ); } public override object ReadJson ( Type objectType, Dictionary<string,object> values) { Bounds b = new Bounds(); b.center = new Vector3( CastFloat(values["cx"]),CastFloat(values["cy"]),CastFloat(values["cz"])); b.extents = new Vector3(CastFloat(values["ex"]),CastFloat(values["ey"]),CastFloat(values["ez"])); return b; } public override Dictionary<string,object> WriteJson (Type type, object value) { Bounds b = (Bounds)value; return new Dictionary<string, object>() { {"cx",b.center.x}, {"cy",b.center.y}, {"cz",b.center.z}, {"ex",b.extents.x}, {"ey",b.extents.y}, {"ez",b.extents.z} }; } } public class LayerMaskConverter : JsonConverter { public override bool CanConvert (Type type) { return System.Type.Equals ( type, typeof(LayerMask) ); } public override object ReadJson (Type type, Dictionary<string,object> values) { return (LayerMask)(int)values["value"]; } public override Dictionary<string,object> WriteJson (Type type, object value) { return new Dictionary<string, object>() {{"value",((LayerMask)value).value}}; } } public class VectorConverter : JsonConverter { public override bool CanConvert (Type type) { return System.Type.Equals ( type, typeof(Vector2) ) || System.Type.Equals ( type, typeof(Vector3) )||System.Type.Equals ( type, typeof(Vector4) ); } public override object ReadJson (Type type, Dictionary<string,object> values) { if (System.Type.Equals ( type, typeof(Vector2) )) { return new Vector2(CastFloat(values["x"]),CastFloat(values["y"])); } else if (System.Type.Equals ( type, typeof(Vector3) )) { return new Vector3(CastFloat(values["x"]),CastFloat(values["y"]),CastFloat(values["z"])); } else if (System.Type.Equals ( type, typeof(Vector4) )) { return new Vector4(CastFloat(values["x"]),CastFloat(values["y"]),CastFloat(values["z"]),CastFloat(values["w"])); } else { throw new System.NotImplementedException ("Can only read Vector2,3,4. Not objects of type "+type); } } public override Dictionary<string,object> WriteJson (Type type, object value) { if (System.Type.Equals ( type, typeof(Vector2) )) { Vector2 v = (Vector2)value; return new Dictionary<string, object>() { {"x",v.x}, {"y",v.y} }; } else if (System.Type.Equals ( type, typeof(Vector3) )) { Vector3 v = (Vector3)value; return new Dictionary<string, object>() { {"x",v.x}, {"y",v.y}, {"z",v.z} }; } else if (System.Type.Equals ( type, typeof(Vector4) )) { Vector4 v = (Vector4)value; return new Dictionary<string, object>() { {"x",v.x}, {"y",v.y}, {"z",v.z}, {"w",v.w} }; } throw new System.NotImplementedException ("Can only write Vector2,3,4. Not objects of type "+type); } } /** Enables json serialization of dictionaries with integer keys. */ public class IntKeyDictionaryConverter : JsonConverter { public override bool CanConvert (Type type) { return ( System.Type.Equals (type, typeof(Dictionary<int,int>)) || System.Type.Equals (type, typeof(SortedDictionary<int,int>)) ); } public override object ReadJson (Type type, Dictionary<string,object> values) { Dictionary<int, int> holder = new Dictionary<int, int>(); foreach ( KeyValuePair<string, object> val in values ) { holder.Add( System.Convert.ToInt32(val.Key), System.Convert.ToInt32(val.Value) ); } return holder; } public override Dictionary<string,object> WriteJson (Type type, object value ) { Dictionary<string, object> holder = new Dictionary<string, object>(); Dictionary<int, int> d = (Dictionary<int,int>)value; foreach ( KeyValuePair<int, int> val in d ) { holder.Add( val.Key.ToString(), val.Value ); } return holder; } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Threading; namespace System.Linq.Expressions { /// <summary> /// Represents a block that contains a sequence of expressions where variables can be defined. /// </summary> [DebuggerTypeProxy(typeof(Expression.BlockExpressionProxy))] public class BlockExpression : Expression { /// <summary> /// Gets the expressions in this block. /// </summary> public ReadOnlyCollection<Expression> Expressions { get { return GetOrMakeExpressions(); } } /// <summary> /// Gets the variables defined in this block. /// </summary> public ReadOnlyCollection<ParameterExpression> Variables { get { return GetOrMakeVariables(); } } /// <summary> /// Gets the last expression in this block. /// </summary> public Expression Result { get { Debug.Assert(ExpressionCount > 0); return GetExpression(ExpressionCount - 1); } } internal BlockExpression() { } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitBlock(this); } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Block; } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public override Type Type { get { return GetExpression(ExpressionCount - 1).Type; } } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="variables">The <see cref="Variables" /> property of the result.</param> /// <param name="expressions">The <see cref="Expressions" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public BlockExpression Update(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { if (variables == Variables && expressions == Expressions) { return this; } return Expression.Block(Type, variables, expressions); } [ExcludeFromCodeCoverage] // Unreachable internal virtual Expression GetExpression(int index) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable internal virtual int ExpressionCount { get { throw ContractUtils.Unreachable; } } [ExcludeFromCodeCoverage] // Unreachable internal virtual ReadOnlyCollection<Expression> GetOrMakeExpressions() { throw ContractUtils.Unreachable; } internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() { return EmptyReadOnlyCollection<ParameterExpression>.Instance; } /// <summary> /// Makes a copy of this node replacing the parameters/args with the provided values. The /// shape of the parameters/args needs to match the shape of the current block - in other /// words there should be the same # of parameters and args. /// /// parameters can be null in which case the existing parameters are used. /// /// This helper is provided to allow re-writing of nodes to not depend on the specific optimized /// subclass of BlockExpression which is being used. /// </summary> [ExcludeFromCodeCoverage] // Unreachable internal virtual BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { throw ContractUtils.Unreachable; } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is similar to the ReturnReadOnly which only takes a single argument. This version /// supports nodes which hold onto 5 Expressions and puts all of the arguments into the /// ReadOnlyCollection. /// /// Ultimately this means if we create the readonly collection we will be slightly more wasteful as we'll /// have a readonly collection + some fields in the type. The DLR internally avoids accessing anything /// which would force the readonly collection to be created. /// /// This is used by BlockExpression5 and MethodCallExpression5. /// </summary> internal static ReadOnlyCollection<Expression> ReturnReadOnlyExpressions(BlockExpression provider, ref object collection) { Expression tObj = collection as Expression; if (tObj != null) { // otherwise make sure only one readonly collection ever gets exposed Interlocked.CompareExchange( ref collection, new ReadOnlyCollection<Expression>(new BlockExpressionList(provider, tObj)), tObj ); } // and return what is not guaranteed to be a readonly collection return (ReadOnlyCollection<Expression>)collection; } } #region Specialized Subclasses internal sealed class Block2 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd argument. internal Block2(Expression arg0, Expression arg1) { _arg0 = arg0; _arg1 = arg1; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; default: throw Error.ArgumentOutOfRange("index"); } } internal override int ExpressionCount { get { return 2; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 2); Debug.Assert(variables == null || variables.Count == 0); return new Block2(args[0], args[1]); } } internal sealed class Block3 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1, _arg2; // storage for the 2nd and 3rd arguments. internal Block3(Expression arg0, Expression arg1, Expression arg2) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; default: throw Error.ArgumentOutOfRange("index"); } } internal override int ExpressionCount { get { return 3; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 3); Debug.Assert(variables == null || variables.Count == 0); return new Block3(args[0], args[1], args[2]); } } internal sealed class Block4 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1, _arg2, _arg3; // storarg for the 2nd, 3rd, and 4th arguments. internal Block4(Expression arg0, Expression arg1, Expression arg2, Expression arg3) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; case 3: return _arg3; default: throw Error.ArgumentOutOfRange("index"); } } internal override int ExpressionCount { get { return 4; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 4); Debug.Assert(variables == null || variables.Count == 0); return new Block4(args[0], args[1], args[2], args[3]); } } internal sealed class Block5 : BlockExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args. internal Block5(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; case 3: return _arg3; case 4: return _arg4; default: throw Error.ArgumentOutOfRange("index"); } } internal override int ExpressionCount { get { return 5; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _arg0); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(args != null); Debug.Assert(args.Length == 5); Debug.Assert(variables == null || variables.Count == 0); return new Block5(args[0], args[1], args[2], args[3], args[4]); } } internal class BlockN : BlockExpression { private IList<Expression> _expressions; // either the original IList<Expression> or a ReadOnlyCollection if the user has accessed it. internal BlockN(IList<Expression> expressions) { Debug.Assert(expressions.Count != 0); _expressions = expressions; } internal override Expression GetExpression(int index) { Debug.Assert(index >= 0 && index < _expressions.Count); return _expressions[index]; } internal override int ExpressionCount { get { return _expressions.Count; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnly(ref _expressions); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { Debug.Assert(variables == null || variables.Count == 0); Debug.Assert(args != null); return new BlockN(args); } } internal class ScopeExpression : BlockExpression { private IList<ParameterExpression> _variables; // list of variables or ReadOnlyCollection if the user has accessed the readonly collection internal ScopeExpression(IList<ParameterExpression> variables) { _variables = variables; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeVariables() { return ReturnReadOnly(ref _variables); } protected IList<ParameterExpression> VariablesList { get { return _variables; } } // Used for rewrite of the nodes to either reuse existing set of variables if not rewritten. internal IList<ParameterExpression> ReuseOrValidateVariables(ReadOnlyCollection<ParameterExpression> variables) { if (variables != null && variables != VariablesList) { // Need to validate the new variables (uniqueness, not byref) ValidateVariables(variables, "variables"); return variables; } else { return VariablesList; } } } internal sealed class Scope1 : ScopeExpression { private object _body; internal Scope1(IList<ParameterExpression> variables, Expression body) : this(variables, (object)body) { } private Scope1(IList<ParameterExpression> variables, object body) : base(variables) { _body = body; } internal override Expression GetExpression(int index) { switch (index) { case 0: return ReturnObject<Expression>(_body); default: throw Error.ArgumentOutOfRange("index"); } } internal override int ExpressionCount { get { return 1; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnlyExpressions(this, ref _body); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { if (args == null) { Debug.Assert(variables.Count == Variables.Count); ValidateVariables(variables, "variables"); return new Scope1(variables, _body); } Debug.Assert(args.Length == 1); Debug.Assert(variables == null || variables.Count == Variables.Count); return new Scope1(ReuseOrValidateVariables(variables), args[0]); } } internal class ScopeN : ScopeExpression { private IList<Expression> _body; internal ScopeN(IList<ParameterExpression> variables, IList<Expression> body) : base(variables) { _body = body; } protected IList<Expression> Body { get { return _body; } } internal override Expression GetExpression(int index) { return _body[index]; } internal override int ExpressionCount { get { return _body.Count; } } internal override ReadOnlyCollection<Expression> GetOrMakeExpressions() { return ReturnReadOnly(ref _body); } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { if (args == null) { Debug.Assert(variables.Count == Variables.Count); ValidateVariables(variables, "variables"); return new ScopeN(variables, _body); } Debug.Assert(args.Length == ExpressionCount); Debug.Assert(variables == null || variables.Count == Variables.Count); return new ScopeN(ReuseOrValidateVariables(variables), args); } } internal class ScopeWithType : ScopeN { private readonly Type _type; internal ScopeWithType(IList<ParameterExpression> variables, IList<Expression> expressions, Type type) : base(variables, expressions) { _type = type; } public sealed override Type Type { get { return _type; } } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { if (args == null) { Debug.Assert(variables.Count == Variables.Count); ValidateVariables(variables, "variables"); return new ScopeWithType(variables, Body, _type); } Debug.Assert(args.Length == ExpressionCount); Debug.Assert(variables == null || variables.Count == Variables.Count); return new ScopeWithType(ReuseOrValidateVariables(variables), args, _type); } } #endregion #region Block List Classes /// <summary> /// Provides a wrapper around an IArgumentProvider which exposes the argument providers /// members out as an IList of Expression. This is used to avoid allocating an array /// which needs to be stored inside of a ReadOnlyCollection. Instead this type has /// the same amount of overhead as an array without duplicating the storage of the /// elements. This ensures that internally we can avoid creating and copying arrays /// while users of the Expression trees also don't pay a size penalty for this internal /// optimization. See IArgumentProvider for more general information on the Expression /// tree optimizations being used here. /// </summary> internal class BlockExpressionList : IList<Expression> { private readonly BlockExpression _block; private readonly Expression _arg0; internal BlockExpressionList(BlockExpression provider, Expression arg0) { _block = provider; _arg0 = arg0; } #region IList<Expression> Members public int IndexOf(Expression item) { if (_arg0 == item) { return 0; } for (int i = 1; i < _block.ExpressionCount; i++) { if (_block.GetExpression(i) == item) { return i; } } return -1; } [ExcludeFromCodeCoverage] // Unreachable public void Insert(int index, Expression item) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable public void RemoveAt(int index) { throw ContractUtils.Unreachable; } public Expression this[int index] { get { if (index == 0) { return _arg0; } return _block.GetExpression(index); } [ExcludeFromCodeCoverage] // Unreachable set { throw ContractUtils.Unreachable; } } #endregion #region ICollection<Expression> Members [ExcludeFromCodeCoverage] // Unreachable public void Add(Expression item) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable public void Clear() { throw ContractUtils.Unreachable; } public bool Contains(Expression item) { return IndexOf(item) != -1; } public void CopyTo(Expression[] array, int arrayIndex) { array[arrayIndex++] = _arg0; for (int i = 1; i < _block.ExpressionCount; i++) { array[arrayIndex++] = _block.GetExpression(i); } } public int Count { get { return _block.ExpressionCount; } } [ExcludeFromCodeCoverage] // Unreachable public bool IsReadOnly { get { throw ContractUtils.Unreachable; } } [ExcludeFromCodeCoverage] // Unreachable public bool Remove(Expression item) { throw ContractUtils.Unreachable; } #endregion #region IEnumerable<Expression> Members public IEnumerator<Expression> GetEnumerator() { yield return _arg0; for (int i = 1; i < _block.ExpressionCount; i++) { yield return _block.GetExpression(i); } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } #endregion public partial class Expression { /// <summary> /// Creates a <see cref="BlockExpression"/> that contains two expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1) { RequiresCanRead(arg0, "arg0"); RequiresCanRead(arg1, "arg1"); return new Block2(arg0, arg1); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains three expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2) { RequiresCanRead(arg0, "arg0"); RequiresCanRead(arg1, "arg1"); RequiresCanRead(arg2, "arg2"); return new Block3(arg0, arg1, arg2); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains four expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <param name="arg3">The fourth expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3) { RequiresCanRead(arg0, "arg0"); RequiresCanRead(arg1, "arg1"); RequiresCanRead(arg2, "arg2"); RequiresCanRead(arg3, "arg3"); return new Block4(arg0, arg1, arg2, arg3); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains five expressions and has no variables. /// </summary> /// <param name="arg0">The first expression in the block.</param> /// <param name="arg1">The second expression in the block.</param> /// <param name="arg2">The third expression in the block.</param> /// <param name="arg3">The fourth expression in the block.</param> /// <param name="arg4">The fifth expression in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { RequiresCanRead(arg0, "arg0"); RequiresCanRead(arg1, "arg1"); RequiresCanRead(arg2, "arg2"); RequiresCanRead(arg3, "arg3"); RequiresCanRead(arg4, "arg4"); return new Block5(arg0, arg1, arg2, arg3, arg4); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables. /// </summary> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(params Expression[] expressions) { ContractUtils.RequiresNotNull(expressions, "expressions"); return GetOptimizedBlockExpression(expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables. /// </summary> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<Expression> expressions) { return Block(EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, params Expression[] expressions) { ContractUtils.RequiresNotNull(expressions, "expressions"); return Block(type, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<Expression> expressions) { return Block(type, EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<ParameterExpression> variables, params Expression[] expressions) { return Block(variables, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, params Expression[] expressions) { return Block(type, variables, (IEnumerable<Expression>)expressions); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { ContractUtils.RequiresNotNull(expressions, "expressions"); var variableList = variables.ToReadOnly(); if (variableList.Count == 0) { return GetOptimizedBlockExpression(expressions as IReadOnlyList<Expression> ?? expressions.ToReadOnly()); } var expressionList = expressions.ToReadOnly(); return BlockCore(null, variableList, expressionList); } /// <summary> /// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions. /// </summary> /// <param name="type">The result type of the block.</param> /// <param name="variables">The variables in the block.</param> /// <param name="expressions">The expressions in the block.</param> /// <returns>The created <see cref="BlockExpression"/>.</returns> public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions) { ContractUtils.RequiresNotNull(type, "type"); ContractUtils.RequiresNotNull(expressions, "expressions"); var expressionList = expressions.ToReadOnly(); var variableList = variables.ToReadOnly(); if (variableList.Count == 0 && expressionList.Count != 0) { var expressionCount = expressionList.Count; if (expressionCount != 0) { var lastExpression = expressionList[expressionCount - 1]; if (lastExpression == null) { throw Error.ArgumentNull("expressions"); } if (lastExpression.Type == type) { return GetOptimizedBlockExpression(expressionList); } } } return BlockCore(type, variableList, expressionList); } private static BlockExpression BlockCore(Type type, ReadOnlyCollection<ParameterExpression> variableList, ReadOnlyCollection<Expression> expressionList) { RequiresCanRead(expressionList, "expressions"); ValidateVariables(variableList, "variables"); if (type != null) { if (expressionList.Count == 0) { if (type != typeof(void)) { throw Error.ArgumentTypesMustMatch(); } return new ScopeWithType(variableList, expressionList, type); } Expression last = expressionList.Last(); if (type != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(type, last.Type)) { throw Error.ArgumentTypesMustMatch(); } } if (!TypeUtils.AreEquivalent(type, last.Type)) { return new ScopeWithType(variableList, expressionList, type); } } switch (expressionList.Count) { case 0: return new ScopeWithType(variableList, expressionList, typeof(void)); case 1: return new Scope1(variableList, expressionList[0]); default: return new ScopeN(variableList, expressionList); } } // Checks that all variables are non-null, not byref, and unique. internal static void ValidateVariables(ReadOnlyCollection<ParameterExpression> varList, string collectionName) { if (varList.Count == 0) { return; } int count = varList.Count; var set = new Set<ParameterExpression>(count); for (int i = 0; i < count; i++) { ParameterExpression v = varList[i]; if (v == null) { throw new ArgumentNullException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}[{1}]", collectionName, set.Count)); } if (v.IsByRef) { throw Error.VariableMustNotBeByRef(v, v.Type); } if (set.Contains(v)) { throw Error.DuplicateVariable(v); } set.Add(v); } } private static BlockExpression GetOptimizedBlockExpression(IReadOnlyList<Expression> expressions) { RequiresCanRead(expressions, "expressions"); switch (expressions.Count) { case 0: return BlockCore(typeof(void), EmptyReadOnlyCollection<ParameterExpression>.Instance, EmptyReadOnlyCollection<Expression>.Instance); case 2: return new Block2(expressions[0], expressions[1]); case 3: return new Block3(expressions[0], expressions[1], expressions[2]); case 4: return new Block4(expressions[0], expressions[1], expressions[2], expressions[3]); case 5: return new Block5(expressions[0], expressions[1], expressions[2], expressions[3], expressions[4]); default: return new BlockN(expressions as ReadOnlyCollection<Expression> ?? (IList<Expression>)expressions.ToArray()); } } } }
//------------------------------------------------------------------------------ // <copyright file="Logging.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Collections; using System.IO; using System.Threading; using System.Diagnostics; using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Globalization; using Microsoft.Win32; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; [FriendAccessAllowed] internal class Logging { private static volatile bool s_LoggingEnabled = true; private static volatile bool s_LoggingInitialized; private static volatile bool s_AppDomainShutdown; private const int DefaultMaxDumpSize = 1024; private const bool DefaultUseProtocolTextOnly = false; private const string AttributeNameMaxSize = "maxdatasize"; private const string AttributeNameTraceMode = "tracemode"; private static readonly string[] SupportedAttributes = new string[] { AttributeNameMaxSize, AttributeNameTraceMode }; private const string AttributeValueProtocolOnly = "protocolonly"; //private const string AttributeValueIncludeHex = "includehex"; private const string TraceSourceWebName = "System.Net"; private const string TraceSourceHttpListenerName = "System.Net.HttpListener"; private const string TraceSourceSocketsName = "System.Net.Sockets"; private const string TraceSourceWebSocketsName = "System.Net.WebSockets"; private const string TraceSourceCacheName = "System.Net.Cache"; private const string TraceSourceHttpName = "System.Net.Http"; private static TraceSource s_WebTraceSource; private static TraceSource s_HttpListenerTraceSource; private static TraceSource s_SocketsTraceSource; private static TraceSource s_WebSocketsTraceSource; private static TraceSource s_CacheTraceSource; private static TraceSource s_TraceSourceHttpName; private Logging() { } private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object o = new Object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } [FriendAccessAllowed] internal static bool On { get { if (!s_LoggingInitialized) { InitializeLogging(); } return s_LoggingEnabled; } } internal static bool IsVerbose(TraceSource traceSource) { return ValidateSettings(traceSource, TraceEventType.Verbose); } internal static TraceSource Web { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_WebTraceSource; } } [FriendAccessAllowed] internal static TraceSource Http { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_TraceSourceHttpName; } } internal static TraceSource HttpListener { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_HttpListenerTraceSource; } } internal static TraceSource Sockets { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_SocketsTraceSource; } } internal static TraceSource RequestCache { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_CacheTraceSource; } } internal static TraceSource WebSockets { get { if (!s_LoggingInitialized) { InitializeLogging(); } if (!s_LoggingEnabled) { return null; } return s_WebSocketsTraceSource; } } private static bool GetUseProtocolTextSetting(TraceSource traceSource) { bool useProtocolTextOnly = DefaultUseProtocolTextOnly; if (traceSource.Attributes[AttributeNameTraceMode] == AttributeValueProtocolOnly) { useProtocolTextOnly = true; } return useProtocolTextOnly; } private static int GetMaxDumpSizeSetting(TraceSource traceSource) { int maxDumpSize = DefaultMaxDumpSize; if (traceSource.Attributes.ContainsKey(AttributeNameMaxSize)) { try { maxDumpSize = Int32.Parse(traceSource.Attributes[AttributeNameMaxSize], NumberFormatInfo.InvariantInfo); } catch (Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } traceSource.Attributes[AttributeNameMaxSize] = maxDumpSize.ToString(NumberFormatInfo.InvariantInfo); } } return maxDumpSize; } /// <devdoc> /// <para>Sets up internal config settings for logging. (MUST be called under critsec) </para> /// </devdoc> private static void InitializeLogging() { lock(InternalSyncObject) { if (!s_LoggingInitialized) { bool loggingEnabled = false; s_WebTraceSource = new NclTraceSource(TraceSourceWebName); s_HttpListenerTraceSource = new NclTraceSource(TraceSourceHttpListenerName); s_SocketsTraceSource = new NclTraceSource(TraceSourceSocketsName); s_WebSocketsTraceSource = new NclTraceSource(TraceSourceWebSocketsName); s_CacheTraceSource = new NclTraceSource(TraceSourceCacheName); s_TraceSourceHttpName = new NclTraceSource(TraceSourceHttpName); GlobalLog.Print("Initalizating tracing"); try { loggingEnabled = (s_WebTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_HttpListenerTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_SocketsTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_WebSocketsTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_CacheTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_TraceSourceHttpName.Switch.ShouldTrace(TraceEventType.Critical)); } catch (SecurityException) { // These may throw if the caller does not have permission to hook up trace listeners. // We treat this case as though logging were disabled. Close(); loggingEnabled = false; } if (loggingEnabled) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); currentDomain.DomainUnload += new EventHandler(AppDomainUnloadEvent); currentDomain.ProcessExit += new EventHandler(ProcessExitEvent); } s_LoggingEnabled = loggingEnabled; s_LoggingInitialized = true; } } } [SuppressMessage("Microsoft.Security","CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Logging functions must work in partial trust mode")] private static void Close() { if (s_WebTraceSource != null) s_WebTraceSource.Close(); if (s_HttpListenerTraceSource != null) s_HttpListenerTraceSource.Close(); if (s_SocketsTraceSource != null) s_SocketsTraceSource.Close(); if (s_WebSocketsTraceSource != null) s_WebSocketsTraceSource.Close(); if (s_CacheTraceSource != null) s_CacheTraceSource.Close(); if (s_TraceSourceHttpName != null) s_TraceSourceHttpName.Close(); } /// <devdoc> /// <para>Logs any unhandled exception through this event handler</para> /// </devdoc> private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception) args.ExceptionObject; Exception(Web, sender, "UnhandledExceptionHandler", e); } private static void ProcessExitEvent(object sender, EventArgs e) { Close(); s_AppDomainShutdown = true; } /// <devdoc> /// <para>Called when the system is shutting down, used to prevent additional logging post-shutdown</para> /// </devdoc> private static void AppDomainUnloadEvent(object sender, EventArgs e) { Close(); s_AppDomainShutdown = true; } /// <devdoc> /// <para>Confirms logging is enabled, given current logging settings</para> /// </devdoc> private static bool ValidateSettings(TraceSource traceSource, TraceEventType traceLevel) { if (!s_LoggingEnabled) { return false; } if (!s_LoggingInitialized) { InitializeLogging(); } if (traceSource == null || !traceSource.Switch.ShouldTrace(traceLevel)) { return false; } if (s_AppDomainShutdown) { return false; } return true; } /// <devdoc> /// <para>Converts an object to a normalized string that can be printed /// takes System.Net.ObjectNamedFoo and coverts to ObjectNamedFoo, /// except IPAddress, IPEndPoint, and Uri, which return ToString() /// </para> /// </devdoc> private static string GetObjectName(object obj) { if (obj is Uri || obj is System.Net.IPAddress || obj is System.Net.IPEndPoint) { return obj.ToString(); } else { return obj.GetType().Name; } } internal static uint GetThreadId() { uint threadId = UnsafeNclNativeMethods.GetCurrentThreadId(); if (threadId == 0) { threadId = (uint)Thread.CurrentThread.GetHashCode(); } return threadId; } internal static void PrintLine(TraceSource traceSource, TraceEventType eventType, int id, string msg) { string logHeader = "["+GetThreadId().ToString("d4", CultureInfo.InvariantCulture)+"] " ; traceSource.TraceEvent(eventType, id, logHeader + msg); } /// <devdoc> /// <para>Indicates that two objects are getting used with one another</para> /// </devdoc> [FriendAccessAllowed] internal static void Associate(TraceSource traceSource, object objA, object objB) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } string lineA = GetObjectName(objA) + "#" + ValidationHelper.HashString(objA); string lineB = GetObjectName(objB) + "#" + ValidationHelper.HashString(objB); PrintLine(traceSource, TraceEventType.Information, 0, "Associating " + lineA + " with " + lineB); } /// <devdoc> /// <para>Logs entrance to a function</para> /// </devdoc> [FriendAccessAllowed] internal static void Enter(TraceSource traceSource, object obj, string method, string param) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Enter(traceSource, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj), method, param); } /// <devdoc> /// <para>Logs entrance to a function</para> /// </devdoc> [FriendAccessAllowed] internal static void Enter(TraceSource traceSource, object obj, string method, object paramObject) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Enter(traceSource, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj), method, paramObject); } /// <devdoc> /// <para>Logs entrance to a function</para> /// </devdoc> internal static void Enter(TraceSource traceSource, string obj, string method, string param) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Enter(traceSource, obj +"::"+method+"("+param+")"); } /// <devdoc> /// <para>Logs entrance to a function</para> /// </devdoc> internal static void Enter(TraceSource traceSource, string obj, string method, object paramObject) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } string paramObjectValue = ""; if (paramObject != null) { paramObjectValue = GetObjectName(paramObject) + "#" + ValidationHelper.HashString(paramObject); } Enter(traceSource, obj +"::"+method+"("+paramObjectValue+")"); } /// <devdoc> /// <para>Logs entrance to a function, indents and points that out</para> /// </devdoc> internal static void Enter(TraceSource traceSource, string method, string parameters) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Enter(traceSource, method+"("+parameters+")"); } /// <devdoc> /// <para>Logs entrance to a function, indents and points that out</para> /// </devdoc> internal static void Enter(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } // Trace.CorrelationManager.StartLogicalOperation(); PrintLine(traceSource, TraceEventType.Verbose, 0, msg); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> [FriendAccessAllowed] internal static void Exit(TraceSource traceSource, object obj, string method, object retObject) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } string retValue = ""; if (retObject != null) { retValue = GetObjectName(retObject)+ "#" + ValidationHelper.HashString(retObject); } Exit(traceSource, obj, method, retValue); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> internal static void Exit(TraceSource traceSource, string obj, string method, object retObject) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } string retValue = ""; if (retObject != null) { retValue = GetObjectName(retObject) + "#" + ValidationHelper.HashString(retObject); } Exit(traceSource, obj, method, retValue); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> [FriendAccessAllowed] internal static void Exit(TraceSource traceSource, object obj, string method, string retValue) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Exit(traceSource, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj), method, retValue); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> internal static void Exit(TraceSource traceSource, string obj, string method, string retValue) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } if (!ValidationHelper.IsBlankString(retValue)) { retValue = "\t-> " + retValue; } Exit(traceSource, obj+"::"+method+"() "+retValue); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> internal static void Exit(TraceSource traceSource, string method, string parameters) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } Exit(traceSource, method+"() "+parameters); } /// <devdoc> /// <para>Logs exit from a function</para> /// </devdoc> internal static void Exit(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } PrintLine(traceSource, TraceEventType.Verbose, 0, "Exiting "+msg); // Trace.CorrelationManager.StopLogicalOperation(); } /// <devdoc> /// <para>Logs Exception, restores indenting</para> /// </devdoc> [FriendAccessAllowed] internal static void Exception(TraceSource traceSource, object obj, string method, Exception e) { if (!ValidateSettings(traceSource, TraceEventType.Error)) { return; } string infoLine = SR.GetString(SR.net_log_exception, GetObjectLogHash(obj), method, e.Message); if (!ValidationHelper.IsBlankString(e.StackTrace)) { infoLine += "\r\n" + e.StackTrace; } PrintLine(traceSource, TraceEventType.Error, 0, infoLine); } /// <devdoc> /// <para>Logs an Info line</para> /// </devdoc> internal static void PrintInfo(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } PrintLine(traceSource, TraceEventType.Information, 0, msg); } /// <devdoc> /// <para>Logs an Info line</para> /// </devdoc> [FriendAccessAllowed] internal static void PrintInfo(TraceSource traceSource, object obj, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } PrintLine(traceSource, TraceEventType.Information, 0, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +" - "+msg); } /// <devdoc> /// <para>Logs an Info line</para> /// </devdoc> internal static void PrintInfo(TraceSource traceSource, object obj, string method, string param) { if (!ValidateSettings(traceSource, TraceEventType.Information)) { return; } PrintLine(traceSource, TraceEventType.Information, 0, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +"::"+method+"("+param+")"); } /// <devdoc> /// <para>Logs a Warning line</para> /// </devdoc> [FriendAccessAllowed] internal static void PrintWarning(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Warning)) { return; } PrintLine(traceSource, TraceEventType.Warning, 0, msg); } /// <devdoc> /// <para>Logs a Warning line</para> /// </devdoc> internal static void PrintWarning(TraceSource traceSource, object obj, string method, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Warning)) { return; } PrintLine(traceSource, TraceEventType.Warning, 0, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +"::"+method+"() - "+msg); } /// <devdoc> /// <para>Logs an Error line</para> /// </devdoc> [FriendAccessAllowed] internal static void PrintError(TraceSource traceSource, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Error)) { return; } PrintLine(traceSource, TraceEventType.Error, 0, msg); } /// <devdoc> /// <para>Logs an Error line</para> /// </devdoc> [FriendAccessAllowed] internal static void PrintError(TraceSource traceSource, object obj, string method, string msg) { if (!ValidateSettings(traceSource, TraceEventType.Error)) { return; } PrintLine(traceSource, TraceEventType.Error, 0, GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +"::"+method+"() - "+msg); } [FriendAccessAllowed] internal static string GetObjectLogHash(object obj) { return GetObjectName(obj) + "#" + ValidationHelper.HashString(obj); } /// <devdoc> /// <para>Marhsalls a buffer ptr to an array and then dumps the byte array to the log</para> /// </devdoc> internal static void Dump(TraceSource traceSource, object obj, string method, IntPtr bufferPtr, int length) { if (!ValidateSettings(traceSource, TraceEventType.Verbose) || bufferPtr == IntPtr.Zero || length < 0) { return; } byte [] buffer = new byte[length]; Marshal.Copy(bufferPtr, buffer, 0, length); Dump(traceSource, obj, method, buffer, 0, length); } /// <devdoc> /// <para>Dumps a byte array to the log</para> /// </devdoc> internal static void Dump(TraceSource traceSource, object obj, string method, byte[] buffer, int offset, int length) { if (!ValidateSettings(traceSource, TraceEventType.Verbose)) { return; } if (buffer == null) { PrintLine(traceSource, TraceEventType.Verbose, 0, "(null)"); return; } if (offset > buffer.Length) { PrintLine(traceSource, TraceEventType.Verbose, 0, "(offset out of range)"); return; } PrintLine(traceSource, TraceEventType.Verbose, 0, "Data from "+GetObjectName(obj)+"#"+ValidationHelper.HashString(obj) +"::"+method); int maxDumpSize = GetMaxDumpSizeSetting(traceSource); if (length > maxDumpSize) { PrintLine(traceSource, TraceEventType.Verbose, 0, "(printing " + maxDumpSize.ToString(NumberFormatInfo.InvariantInfo) + " out of " + length.ToString(NumberFormatInfo.InvariantInfo) + ")"); length = maxDumpSize; } if ((length < 0) || (length > buffer.Length - offset)) { length = buffer.Length - offset; } if (GetUseProtocolTextSetting(traceSource)) { string output = "<<" + WebHeaderCollection.HeaderEncoding.GetString(buffer, offset, length) + ">>"; PrintLine(traceSource, TraceEventType.Verbose, 0, output); return; } do { int n = Math.Min(length, 16); string disp = String.Format(CultureInfo.CurrentCulture, "{0:X8} : ", offset); for (int i = 0; i < n; ++i) { disp += String.Format(CultureInfo.CurrentCulture, "{0:X2}", buffer[offset + i]) + ((i == 7) ? '-' : ' '); } for (int i = n; i < 16; ++i) { disp += " "; } disp += ": "; for (int i = 0; i < n; ++i) { disp += ((buffer[offset + i] < 0x20) || (buffer[offset + i] > 0x7e)) ? '.' : (char)(buffer[offset + i]); } PrintLine(traceSource, TraceEventType.Verbose, 0, disp); offset += n; length -= n; } while (length > 0); } private class NclTraceSource : TraceSource { internal NclTraceSource(string name) : base(name) { } protected internal override string[] GetSupportedAttributes() { return Logging.SupportedAttributes; } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Web; using System.Web.Hosting; using System.Web.Configuration; using System.Xml; using Umbraco.Core; using Umbraco.Core.Configuration; using umbraco.BusinessLogic; using umbraco.DataLayer; using Umbraco.Core.IO; namespace umbraco { /// <summary> /// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings /// </summary> public class GlobalSettings { /// <summary> /// Gets the reserved urls from web.config. /// </summary> /// <value>The reserved urls.</value> public static string ReservedUrls { get { return Umbraco.Core.Configuration.GlobalSettings.ReservedUrls; } } /// <summary> /// Gets the reserved paths from web.config /// </summary> /// <value>The reserved paths.</value> public static string ReservedPaths { get { return Umbraco.Core.Configuration.GlobalSettings.ReservedPaths; } } /// <summary> /// Gets the name of the content XML file. /// </summary> /// <value>The content XML.</value> public static string ContentXML { get { return Umbraco.Core.Configuration.GlobalSettings.ContentXmlFile; } } /// <summary> /// Gets the path to the storage directory (/data by default). /// </summary> /// <value>The storage directory.</value> public static string StorageDirectory { get { return Umbraco.Core.Configuration.GlobalSettings.StorageDirectory; } } /// <summary> /// Gets the path to umbraco's root directory (/umbraco by default). /// </summary> /// <value>The path.</value> public static string Path { get { return Umbraco.Core.Configuration.GlobalSettings.Path; } } /// <summary> /// Gets the path to umbraco's client directory (/umbraco_client by default). /// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco' /// folder since the CSS paths to images depend on it. /// </summary> /// <value>The path.</value> public static string ClientPath { get { return Umbraco.Core.Configuration.GlobalSettings.ClientPath; } } /// <summary> /// Gets the database connection string /// </summary> /// <value>The database connection string.</value> [Obsolete("Use System.ConfigurationManager.ConnectionStrings to get the connection with the key Umbraco.Core.Configuration.GlobalSettings.UmbracoConnectionName instead")] public static string DbDSN { get { return Umbraco.Core.Configuration.GlobalSettings.DbDsn; } set { Umbraco.Core.Configuration.GlobalSettings.DbDsn = value; } } /// <summary> /// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance. /// </summary> /// <value>The configuration status.</value> public static string ConfigurationStatus { get { return Umbraco.Core.Configuration.GlobalSettings.ConfigurationStatus; } set { Umbraco.Core.Configuration.GlobalSettings.ConfigurationStatus = value; } } public static AspNetHostingPermissionLevel ApplicationTrustLevel { get { return Umbraco.Core.SystemUtilities.GetCurrentTrustLevel(); } } /// <summary> /// Saves a setting into the configuration file. /// </summary> /// <param name="key">Key of the setting to be saved.</param> /// <param name="value">Value of the setting to be saved.</param> protected static void SaveSetting(string key, string value) { Umbraco.Core.Configuration.GlobalSettings.SaveSetting(key, value); } /// <summary> /// Gets the full path to root. /// </summary> /// <value>The fullpath to root.</value> public static string FullpathToRoot { get { return Umbraco.Core.Configuration.GlobalSettings.FullpathToRoot; } } /// <summary> /// Gets a value indicating whether umbraco is running in [debug mode]. /// </summary> /// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value> public static bool DebugMode { get { return Umbraco.Core.Configuration.GlobalSettings.DebugMode; } } /// <summary> /// Gets a value indicating whether the current version of umbraco is configured. /// </summary> /// <value><c>true</c> if configured; otherwise, <c>false</c>.</value> [Obsolete("Do not use this, it is no longer in use and will be removed from the codebase in future versions")] public static bool Configured { get { return Umbraco.Core.Configuration.GlobalSettings.Configured; } } /// <summary> /// Gets the time out in minutes. /// </summary> /// <value>The time out in minutes.</value> public static int TimeOutInMinutes { get { return Umbraco.Core.Configuration.GlobalSettings.TimeOutInMinutes; } } /// <summary> /// Gets a value indicating whether umbraco uses directory urls. /// </summary> /// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value> public static bool UseDirectoryUrls { get { return Umbraco.Core.Configuration.GlobalSettings.UseDirectoryUrls; } } /// <summary> /// Returns a string value to determine if umbraco should skip version-checking. /// </summary> /// <value>The version check period in days (0 = never).</value> public static int VersionCheckPeriod { get { return Umbraco.Core.Configuration.GlobalSettings.VersionCheckPeriod; } } /// <summary> /// Gets the URL forbitten characters. /// </summary> /// <value>The URL forbitten characters.</value> [Obsolete("This property is no longer used and will be removed in future versions")] public static string UrlForbittenCharacters { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoUrlForbittenCharacters") ? ConfigurationManager.AppSettings["umbracoUrlForbittenCharacters"] : string.Empty; } } /// <summary> /// Gets the URL space character. /// </summary> /// <value>The URL space character.</value> [Obsolete("This property is no longer used and will be removed in future versions")] public static string UrlSpaceCharacter { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoUrlSpaceCharacter") ? ConfigurationManager.AppSettings["umbracoUrlSpaceCharacter"] : string.Empty; } } /// <summary> /// Gets the SMTP server IP-address or hostname. /// </summary> /// <value>The SMTP server.</value> [Obsolete("This property is no longer used and will be removed in future versions")] public static string SmtpServer { get { try { var mailSettings = ConfigurationManager.GetSection("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup; if (mailSettings != null) return mailSettings.Smtp.Network.Host; else return ConfigurationManager.AppSettings["umbracoSmtpServer"]; } catch { return ""; } } } /// <summary> /// Returns a string value to determine if umbraco should disbable xslt extensions /// </summary> /// <value><c>"true"</c> if version xslt extensions are disabled, otherwise, <c>"false"</c></value> [Obsolete("This is no longer used and will be removed from the codebase in future releases")] public static string DisableXsltExtensions { get { return Umbraco.Core.Configuration.GlobalSettings.DisableXsltExtensions; } } /// <summary> /// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor /// </summary> /// <value><c>"true"</c> if Xhtml mode is enable, otherwise, <c>"false"</c></value> [Obsolete("This is no longer used and will be removed from the codebase in future releases")] public static string EditXhtmlMode { get { return Umbraco.Core.Configuration.GlobalSettings.EditXhtmlMode; } } /// <summary> /// Gets the default UI language. /// </summary> /// <value>The default UI language.</value> public static string DefaultUILanguage { get { return Umbraco.Core.Configuration.GlobalSettings.DefaultUILanguage; } } /// <summary> /// Gets the profile URL. /// </summary> /// <value>The profile URL.</value> public static string ProfileUrl { get { return Umbraco.Core.Configuration.GlobalSettings.ProfileUrl; } } /// <summary> /// Gets a value indicating whether umbraco should hide top level nodes from generated urls. /// </summary> /// <value> /// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>. /// </value> public static bool HideTopLevelNodeFromPath { get { return Umbraco.Core.Configuration.GlobalSettings.HideTopLevelNodeFromPath; } } /// <summary> /// Gets the current version. /// </summary> /// <value>The current version.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static string CurrentVersion { get { return UmbracoVersion.Current.ToString(3); } } /// <summary> /// Gets the major version number. /// </summary> /// <value>The major version number.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static int VersionMajor { get { return UmbracoVersion.Current.Major; } } /// <summary> /// Gets the minor version number. /// </summary> /// <value>The minor version number.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static int VersionMinor { get { return UmbracoVersion.Current.Minor; } } /// <summary> /// Gets the patch version number. /// </summary> /// <value>The patch version number.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static int VersionPatch { get { return UmbracoVersion.Current.Build; } } /// <summary> /// Gets the version comment (like beta or RC). /// </summary> /// <value>The version comment.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static string VersionComment { get { return UmbracoVersion.CurrentComment; } } /// <summary> /// Requests the is in umbraco application directory structure. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public static bool RequestIsInUmbracoApplication(HttpContext context) { return Umbraco.Core.Configuration.GlobalSettings.RequestIsInUmbracoApplication(context); } /// <summary> /// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice. /// </summary> /// <value><c>true</c> if [use SSL]; otherwise, <c>false</c>.</value> public static bool UseSSL { get { return Umbraco.Core.Configuration.GlobalSettings.UseSSL; } } /// <summary> /// Gets the umbraco license. /// </summary> /// <value>The license.</value> public static string License { get { return Umbraco.Core.Configuration.GlobalSettings.License; } } /// <summary> /// Developer method to test if configuration settings are loaded properly. /// </summary> /// <value><c>true</c> if succesfull; otherwise, <c>false</c>.</value> [Obsolete("This method is no longer used and will be removed in future versions")] public static bool test { get { var databaseSettings = ConfigurationManager.ConnectionStrings[Umbraco.Core.Configuration.GlobalSettings.UmbracoConnectionName]; var dataHelper = DataLayerHelper.CreateSqlHelper(databaseSettings.ConnectionString, false); if (HttpContext.Current != null) { HttpContext.Current.Response.Write("ContentXML :" + ContentXML + "\n"); HttpContext.Current.Response.Write("DbDSN :" + dataHelper.ConnectionString + "\n"); HttpContext.Current.Response.Write("DebugMode :" + DebugMode + "\n"); HttpContext.Current.Response.Write("DefaultUILanguage :" + DefaultUILanguage + "\n"); HttpContext.Current.Response.Write("VersionCheckPeriod :" + VersionCheckPeriod + "\n"); HttpContext.Current.Response.Write("DisableXsltExtensions :" + DisableXsltExtensions + "\n"); HttpContext.Current.Response.Write("EditXhtmlMode :" + EditXhtmlMode + "\n"); HttpContext.Current.Response.Write("HideTopLevelNodeFromPath :" + HideTopLevelNodeFromPath + "\n"); HttpContext.Current.Response.Write("Path :" + Path + "\n"); HttpContext.Current.Response.Write("ProfileUrl :" + ProfileUrl + "\n"); HttpContext.Current.Response.Write("ReservedPaths :" + ReservedPaths + "\n"); HttpContext.Current.Response.Write("ReservedUrls :" + ReservedUrls + "\n"); HttpContext.Current.Response.Write("StorageDirectory :" + StorageDirectory + "\n"); HttpContext.Current.Response.Write("TimeOutInMinutes :" + TimeOutInMinutes + "\n"); //HttpContext.Current.Response.Write("UrlForbittenCharacters :" + UrlForbittenCharacters + "\n"); //HttpContext.Current.Response.Write("UrlSpaceCharacter :" + UrlSpaceCharacter + "\n"); HttpContext.Current.Response.Write("UseDirectoryUrls :" + UseDirectoryUrls + "\n"); return true; } return false; } } /// <summary> /// Determines whether the specified URL is reserved or is inside a reserved path. /// </summary> /// <param name="url">The URL to check.</param> /// <returns> /// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>. /// </returns> public static bool IsReservedPathOrUrl(string url) { return Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url); } } /// <summary> /// Structure that checks in logarithmic time /// if a given string starts with one of the added keys. /// </summary> [Obsolete("Use Umbraco.Core.Configuration.GlobalSettings.StartsWithContainer container instead")] public class StartsWithContainer { /// <summary>Internal sorted list of keys.</summary> public SortedList<string, string> _list = new SortedList<string, string>(StartsWithComparator.Instance); /// <summary> /// Adds the specified new key. /// </summary> /// <param name="newKey">The new key.</param> public void Add(string newKey) { // if the list already contains an element that begins with newKey, return if (String.IsNullOrEmpty(newKey) || StartsWith(newKey)) return; // create a new collection, so the old one can still be accessed SortedList<string, string> newList = new SortedList<string, string>(_list.Count + 1, StartsWithComparator.Instance); // add only keys that don't already start with newKey, others are unnecessary foreach (string key in _list.Keys) if (!key.StartsWith(newKey)) newList.Add(key, null); // add the new key newList.Add(newKey, null); // update the list (thread safe, _list was never in incomplete state) _list = newList; } /// <summary> /// Checks if the given string starts with any of the added keys. /// </summary> /// <param name="target">The target.</param> /// <returns>true if a key is found that matches the start of target</returns> /// <remarks> /// Runs in O(s*log(n)), with n the number of keys and s the length of target. /// </remarks> public bool StartsWith(string target) { return _list.ContainsKey(target); } /// <summary>Comparator that tests if a string starts with another.</summary> /// <remarks>Not a real comparator, since it is not reflexive. (x==y does not imply y==x)</remarks> private sealed class StartsWithComparator : IComparer<string> { /// <summary>Default string comparer.</summary> private readonly static Comparer<string> _stringComparer = Comparer<string>.Default; /// <summary>Gets an instance of the StartsWithComparator.</summary> public static readonly StartsWithComparator Instance = new StartsWithComparator(); /// <summary> /// Tests if whole begins with all characters of part. /// </summary> /// <param name="part">The part.</param> /// <param name="whole">The whole.</param> /// <returns> /// Returns 0 if whole starts with part, otherwise performs standard string comparison. /// </returns> public int Compare(string part, string whole) { // let the default string comparer deal with null or when part is not smaller then whole if (part == null || whole == null || part.Length >= whole.Length) return _stringComparer.Compare(part, whole); // loop through all characters that part and whole have in common int pos = 0; bool match; do { match = (part[pos] == whole[pos]); } while (match && ++pos < part.Length); // return result of last comparison return match ? 0 : (part[pos] < whole[pos] ? -1 : 1); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Storage; namespace Microsoft.WindowsAzure.Management.Storage { /// <summary> /// The Service Management API provides programmatic access to much of the /// functionality available through the Management Portal. The Service /// Management API is a REST API. All API operations are performed over /// SSL and are mutually authenticated using X.509 v3 certificates. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for /// more information) /// </summary> public partial class StorageManagementClient : ServiceClient<StorageManagementClient>, Microsoft.WindowsAzure.Management.Storage.IStorageManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IStorageAccountOperations _storageAccounts; /// <summary> /// The Service Management API includes operations for managing the /// storage accounts beneath your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460790.aspx /// for more information) /// </summary> public virtual IStorageAccountOperations StorageAccounts { get { return this._storageAccounts; } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> private StorageManagementClient() : base() { this._storageAccounts = new StorageAccountOperations(this); this._apiVersion = "2014-10-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Required. Gets the URI used as the base for all cloud service /// requests. /// </param> public StorageManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public StorageManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> private StorageManagementClient(HttpClient httpClient) : base(httpClient) { this._storageAccounts = new StorageAccountOperations(this); this._apiVersion = "2014-10-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Required. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public StorageManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public StorageManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// StorageManagementClient instance /// </summary> /// <param name='client'> /// Instance of StorageManagementClient to clone to /// </param> protected override void Clone(ServiceClient<StorageManagementClient> client) { base.Clone(client); if (client is StorageManagementClient) { StorageManagementClient clonedClient = ((StorageManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx /// for more information) /// </summary> /// <param name='requestId'> /// Required. The request ID for the request you wish to track. The /// request ID is returned in the x-ms-request-id response header for /// every request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken) { // Validate if (requestId == null) { throw new ArgumentNullException("requestId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("requestId", requestId); Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/operations/" + requestId.Trim(); string baseUrl = this.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure")); if (operationElement != null) { XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Text; using UnityEngine; using KSP.Localization; namespace KERBALISM.Planner { ///<summary> Class for the Planner used in the VAB/SPH, it is used to predict resource production/consumption and /// provide information on life support, radiation, comfort and other relevant factors. </summary> public static class Planner { #region CONSTRUCTORS_DESTRUCTORS ///<summary> Initializes the Planner for use </summary> internal static void Initialize() { // set the ui styles SetStyles(); // set default body index to home body_index = FlightGlobals.GetHomeBodyIndex(); // resource panels // - add all resources defined in the Profiles Supply configs except EC Profile.supplies.FindAll(k => k.resource != "ElectricCharge").ForEach(k => supplies.Add(k.resource)); // special panels // - stress & radiation panels require that a rule using the living_space/radiation modifier exist (current limitation) if (Features.LivingSpace && Profile.rules.Find(k => k.modifiers.Contains("living_space")) != null) panel_special.Add("qol"); if (Features.Radiation && Profile.rules.Find(k => k.modifiers.Contains("radiation")) != null) panel_special.Add("radiation"); if (Features.Reliability) panel_special.Add("reliability"); // environment panels if (Features.Pressure || Features.Poisoning) panel_environment.Add("habitat"); panel_environment.Add("environment"); } ///<summary> Sets the styles for the panels UI </summary> private static void SetStyles() { // left menu style leftmenu_style = new GUIStyle(HighLogic.Skin.label) { richText = true }; leftmenu_style.normal.textColor = new Color(0.0f, 0.0f, 0.0f, 1.0f); leftmenu_style.fixedWidth = Styles.ScaleWidthFloat(80.0f); // Fixed to avoid that the sun icon moves around for different planet name lengths leftmenu_style.stretchHeight = true; leftmenu_style.fontSize = Styles.ScaleInteger(10); leftmenu_style.alignment = TextAnchor.MiddleLeft; // right menu style rightmenu_style = new GUIStyle(leftmenu_style) { alignment = TextAnchor.MiddleRight }; // quote style quote_style = new GUIStyle(HighLogic.Skin.label) { richText = true }; quote_style.normal.textColor = Color.black; quote_style.stretchWidth = true; quote_style.stretchHeight = true; quote_style.fontSize = Styles.ScaleInteger(11); quote_style.alignment = TextAnchor.LowerCenter; // center icon style icon_style = new GUIStyle { alignment = TextAnchor.MiddleCenter }; // debug header style devbuild_style = new GUIStyle(); devbuild_style.normal.textColor = Color.white; devbuild_style.stretchHeight = true; devbuild_style.fontSize = Styles.ScaleInteger(12); devbuild_style.alignment = TextAnchor.MiddleCenter; } #endregion #region EVENTS ///<summary> Method called when the vessel in the editor has been modified </summary> internal static void EditorShipModifiedEvent(ShipConstruct sc) => RefreshPlanner(); #endregion #region METHODS ///<summary> Call this to trigger a planner update</summary> internal static void RefreshPlanner() => update_counter = 0; ///<summary> Run simulators and update the planner UI sub-panels </summary> internal static void Update() { // get vessel crew manifest VesselCrewManifest manifest = KSP.UI.CrewAssignmentDialog.Instance.GetManifest(); if (manifest == null) return; // check for number of crew change if (vessel_analyzer.crew_count != manifest.CrewCount) enforceUpdate = true; // only update when we need to, repeat update a number of times to allow the simulators to catch up if (!enforceUpdate && update_counter++ > 3) return; // clear the panel panel.Clear(); // if there is something in the editor if (EditorLogic.RootPart != null) { // get parts recursively List<Part> parts = Lib.GetPartsRecursively(EditorLogic.RootPart); // analyze using the settings from the panels user input env_analyzer.Analyze(FlightGlobals.Bodies[body_index], altitude_mults[situation_index], sunlight); vessel_analyzer.Analyze(parts, resource_sim, env_analyzer); resource_sim.Analyze(parts, env_analyzer, vessel_analyzer); // add ec panel AddSubPanelEC(panel); // get vessel resources panel_resource.Clear(); foreach (string res in supplies) if (resource_sim.Resource(res).capacity > 0.0) panel_resource.Add(res); // reset current panel if necessary if (resource_index >= panel_resource.Count) resource_index = 0; // add resource panel if (panel_resource.Count > 0) AddSubPanelResource(panel, panel_resource[resource_index]); // add special panel if (panel_special.Count > 0) { switch (panel_special[special_index]) { case "qol": AddSubPanelStress(panel); break; case "radiation": AddSubPanelRadiation(panel); break; case "reliability": AddSubPanelReliability(panel); break; } } // add environment panel switch (panel_environment[environment_index]) { case "habitat": AddSubPanelHabitat(panel); break; case "environment": AddSubPanelEnvironment(panel); break; } } enforceUpdate = false; } ///<summary> Planner panel UI width </summary> internal static float Width() { return Styles.ScaleWidthFloat(280.0f); } ///<summary> Planner panel UI height </summary> internal static float Height() { if (EditorLogic.RootPart != null) return Styles.ScaleFloat(Lib.IsDevBuild ? 45.0f : 30.0f) + panel.Height(); // header + ui content + dev build header if present else return Styles.ScaleFloat(66.0f); // quote-only } ///<summary> Render planner UI panel </summary> internal static void Render() { // if there is something in the editor if (EditorLogic.RootPart != null) { if (Lib.IsDevBuild) { GUILayout.BeginHorizontal(Styles.title_container); GUILayout.Label(new GUIContent("KERBALISM DEV BUILD " + Lib.KerbalismDevBuild), devbuild_style); GUILayout.EndHorizontal(); } // start header GUILayout.BeginHorizontal(Styles.title_container); // body selector GUILayout.Label(new GUIContent(FlightGlobals.Bodies[body_index].name, Local.Planner_Targetbody), leftmenu_style);//"Target body" if (Lib.IsClicked()) { body_index = (body_index + 1) % FlightGlobals.Bodies.Count; if (body_index == 0) ++body_index; enforceUpdate = true; } else if (Lib.IsClicked(1)) { body_index = (body_index - 1) % FlightGlobals.Bodies.Count; if (body_index == 0) body_index = FlightGlobals.Bodies.Count - 1; enforceUpdate = true; } // sunlight selector switch (sunlight) { case SunlightState.SunlightNominal: GUILayout.Label(new GUIContent(Textures.sun_white, Local.Planner_SunlightNominal), icon_style); break;//"In sunlight\n<b>Nominal</b> solar panel output" case SunlightState.SunlightSimulated: GUILayout.Label(new GUIContent(Textures.solar_panel, Local.Planner_SunlightSimulated), icon_style); break;//"In sunlight\n<b>Estimated</b> solar panel output\n<i>Sunlight direction : look at the shadows !</i>" case SunlightState.Shadow: GUILayout.Label(new GUIContent(Textures.sun_black, Local.Planner_Shadow), icon_style); break;//"In shadow" } if (Lib.IsClicked()) { sunlight = (SunlightState)(((int)sunlight + 1) % Enum.GetValues(typeof(SunlightState)).Length); enforceUpdate = true; } // situation selector GUILayout.Label(new GUIContent(situations[situation_index], Local.Planner_Targetsituation), rightmenu_style);//"Target situation" if (Lib.IsClicked()) { situation_index = (situation_index + 1) % situations.Length; enforceUpdate = true; } else if (Lib.IsClicked(1)) { situation_index = (situation_index == 0 ? situations.Length : situation_index) - 1; enforceUpdate = true; } // end header GUILayout.EndHorizontal(); // render panel panel.Render(); } // if there is nothing in the editor else { // render quote GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.Label("<i>"+Local.Planner_RenderQuote +"</i>", quote_style);//In preparing for space, I have always found that\nplans are useless but planning is indispensable.\nWernher von Kerman GUILayout.EndHorizontal(); GUILayout.Space(Styles.ScaleFloat(10.0f)); } } ///<summary> Add environment sub-panel, including tooltips </summary> private static void AddSubPanelEnvironment(Panel p) { string flux_tooltip = Lib.BuildString ( "<align=left />" + String.Format("<b>{0,-14}\t{1,-15}\t{2}</b>\n", Local.Planner_Source, Local.Planner_Flux, Local.Planner_Temp),//"Source""Flux""Temp" String.Format("{0,-14}\t{1,-15}\t{2}\n", Local.Planner_solar, env_analyzer.solar_flux > 0.0 ? Lib.HumanReadableFlux(env_analyzer.solar_flux) : Local.Generic_NONE, Lib.HumanReadableTemp(Sim.BlackBodyTemperature(env_analyzer.solar_flux))),//"solar""none" String.Format("{0,-14}\t{1,-15}\t{2}\n", Local.Planner_albedo, env_analyzer.albedo_flux > 0.0 ? Lib.HumanReadableFlux(env_analyzer.albedo_flux) : Local.Generic_NONE, Lib.HumanReadableTemp(Sim.BlackBodyTemperature(env_analyzer.albedo_flux))),//"albedo""none" String.Format("{0,-14}\t{1,-15}\t{2}\n", Local.Planner_body, env_analyzer.body_flux > 0.0 ? Lib.HumanReadableFlux(env_analyzer.body_flux) : Local.Generic_NONE, Lib.HumanReadableTemp(Sim.BlackBodyTemperature(env_analyzer.body_flux))),//"body""none" String.Format("{0,-14}\t{1,-15}\t{2}\n", Local.Planner_background, Lib.HumanReadableFlux(Sim.BackgroundFlux()), Lib.HumanReadableTemp(Sim.BlackBodyTemperature(Sim.BackgroundFlux()))),//"background" String.Format("{0,-14}\t\t{1,-15}\t{2}", Local.Planner_total, Lib.HumanReadableFlux(env_analyzer.total_flux), Lib.HumanReadableTemp(Sim.BlackBodyTemperature(env_analyzer.total_flux)))//"total" ); string atmosphere_tooltip = Lib.BuildString ( "<align=left />", String.Format("{0,-14}\t<b>{1}</b>\n", Local.BodyInfo_breathable, Sim.Breathable(env_analyzer.body) ? Local.BodyInfo_breathable_yes : Local.BodyInfo_breathable_no),//"breathable""yes""no" String.Format("{0,-14}\t<b>{1}</b>\n", Local.Planner_pressure, Lib.HumanReadablePressure(env_analyzer.body.atmospherePressureSeaLevel)),//"pressure" String.Format("{0,-14}\t<b>{1}</b>\n", Local.BodyInfo_lightabsorption, Lib.HumanReadablePerc(1.0 - env_analyzer.atmo_factor)),//"light absorption" String.Format("{0,-14}\t<b>{1}</b>", Local.BodyInfo_gammaabsorption, Lib.HumanReadablePerc(1.0 - Sim.GammaTransparency(env_analyzer.body, 0.0)))//"gamma absorption" ); string shadowtime_str = Lib.HumanReadableDuration(env_analyzer.shadow_period) + " (" + (env_analyzer.shadow_time * 100.0).ToString("F0") + "%)"; p.AddSection(Local.TELEMETRY_ENVIRONMENT, string.Empty,//"ENVIRONMENT" () => { p.Prev(ref environment_index, panel_environment.Count); enforceUpdate = true; }, () => { p.Next(ref environment_index, panel_environment.Count); enforceUpdate = true; }); p.AddContent(Local.Planner_temperature, Lib.HumanReadableTemp(env_analyzer.temperature), env_analyzer.body.atmosphere && env_analyzer.landed ? Local.Planner_atmospheric : flux_tooltip);//"temperature""atmospheric" p.AddContent(Local.Planner_difference, Lib.HumanReadableTemp(env_analyzer.temp_diff), Local.Planner_difference_desc);//"difference""difference between external and survival temperature" p.AddContent(Local.Planner_atmosphere, env_analyzer.body.atmosphere ? Local.Planner_atmosphere_yes : Local.Planner_atmosphere_no, atmosphere_tooltip);//"atmosphere""yes""no" p.AddContent(Local.Planner_shadowtime, shadowtime_str, Local.Planner_shadowtime_desc);//"shadow time""the time in shadow\nduring the orbit" } ///<summary> Add electric charge sub-panel, including tooltips </summary> private static void AddSubPanelEC(Panel p) { // get simulated resource SimulatedResource res = resource_sim.Resource("ElectricCharge"); // create tooltip string tooltip = res.Tooltip(); // render the panel section p.AddSection(Local.Planner_ELECTRICCHARGE);//"ELECTRIC CHARGE" p.AddContent(Local.Planner_storage, Lib.HumanReadableAmount(res.storage), tooltip);//"storage" p.AddContent(Local.Planner_consumed, Lib.HumanReadableRate(res.consumed), tooltip);//"consumed" p.AddContent(Local.Planner_produced, Lib.HumanReadableRate(res.produced), tooltip);//"produced" p.AddContent(Local.Planner_duration, Lib.HumanReadableDuration(res.Lifetime()));//"duration" } ///<summary> Add supply resource sub-panel, including tooltips </summary> ///<remarks> /// does not include electric charge /// does not include special resources like waste atmosphere /// restricted to resources that are configured explicitly in the profile as supplies ///</remarks> private static void AddSubPanelResource(Panel p, string res_name) { // get simulated resource SimulatedResource res = resource_sim.Resource(res_name); // create tooltip string tooltip = res.Tooltip(); var resource = PartResourceLibrary.Instance.resourceDefinitions[res_name]; // render the panel section p.AddSection(Lib.SpacesOnCaps(resource.displayName).ToUpper(), string.Empty, () => { p.Prev(ref resource_index, panel_resource.Count); enforceUpdate = true; }, () => { p.Next(ref resource_index, panel_resource.Count); enforceUpdate = true; }); p.AddContent(Local.Planner_storage, Lib.HumanReadableAmount(res.storage), tooltip);//"storage" p.AddContent(Local.Planner_consumed, Lib.HumanReadableRate(res.consumed), tooltip);//"consumed" p.AddContent(Local.Planner_produced, Lib.HumanReadableRate(res.produced), tooltip);//"produced" p.AddContent(Local.Planner_duration, Lib.HumanReadableDuration(res.Lifetime()));//"duration" } ///<summary> Add stress sub-panel, including tooltips </summary> private static void AddSubPanelStress(Panel p) { // get first living space rule // - guaranteed to exist, as this panel is not rendered if it doesn't // - even without crew, it is safe to evaluate the modifiers that use it Rule rule = Profile.rules.Find(k => k.modifiers.Contains("living_space")); // render title p.AddSection(Local.Planner_STRESS, string.Empty,//"STRESS" () => { p.Prev(ref special_index, panel_special.Count); enforceUpdate = true; }, () => { p.Next(ref special_index, panel_special.Count); enforceUpdate = true; }); // render living space data // generate details tooltips string living_space_tooltip = Lib.BuildString ( Local.Planner_volumepercapita ,"<b>\t", Lib.HumanReadableVolume(vessel_analyzer.volume / Math.Max(vessel_analyzer.crew_count, 1)), "</b>\n",//"volume per-capita: Local.Planner_ideallivingspace ,"<b>\t", Lib.HumanReadableVolume(PreferencesComfort.Instance.livingSpace), "</b>"//"ideal living space: ); p.AddContent(Local.Planner_livingspace, Habitat.Living_space_to_string(vessel_analyzer.living_space), living_space_tooltip);//"living space" // render comfort data if (rule.modifiers.Contains("comfort")) { p.AddContent(Local.Planner_comfort, vessel_analyzer.comforts.Summary(), vessel_analyzer.comforts.Tooltip());//"comfort" } else { p.AddContent(Local.Planner_comfort, "n/a");//"comfort" } // render pressure data if (rule.modifiers.Contains("pressure")) { string pressure_tooltip = vessel_analyzer.pressurized ? Local.Planner_analyzerpressurized1//"Free roaming in a pressurized environment is\nvastly superior to living in a suit." : Local.Planner_analyzerpressurized2;//"Being forced inside a suit all the time greatly\nreduces the crews quality of life.\nThe worst part is the diaper." p.AddContent(Local.Planner_pressurized, vessel_analyzer.pressurized ? Local.Planner_pressurized_yes : Local.Planner_pressurized_no, pressure_tooltip);//"pressurized""yes""no" } else { p.AddContent(Local.Planner_pressurized, "n/a");//"pressurized" } // render life estimate double mod = Modifiers.Evaluate(env_analyzer, vessel_analyzer, resource_sim, rule.modifiers); p.AddContent(Local.Planner_lifeestimate, Lib.HumanReadableDuration(rule.fatal_threshold / (rule.degeneration * mod)));//"duration" } ///<summary> Add radiation sub-panel, including tooltips </summary> private static void AddSubPanelRadiation(Panel p) { // get first radiation rule // - guaranteed to exist, as this panel is not rendered if it doesn't // - even without crew, it is safe to evaluate the modifiers that use it Rule rule = Profile.rules.Find(k => k.modifiers.Contains("radiation")); // detect if it use shielding bool use_shielding = rule.modifiers.Contains("shielding"); // calculate various radiation levels double[] levels = new[] { Math.Max(Radiation.Nominal, (env_analyzer.surface_rad + vessel_analyzer.emitted)), // surface Math.Max(Radiation.Nominal, (env_analyzer.magnetopause_rad + vessel_analyzer.emitted)), // inside magnetopause Math.Max(Radiation.Nominal, (env_analyzer.inner_rad + vessel_analyzer.emitted)), // inside inner belt Math.Max(Radiation.Nominal, (env_analyzer.outer_rad + vessel_analyzer.emitted)), // inside outer belt Math.Max(Radiation.Nominal, (env_analyzer.heliopause_rad + vessel_analyzer.emitted)), // interplanetary Math.Max(Radiation.Nominal, (env_analyzer.extern_rad + vessel_analyzer.emitted)), // interstellar Math.Max(Radiation.Nominal, (env_analyzer.storm_rad + vessel_analyzer.emitted)) // storm }; // evaluate modifiers (except radiation) List<string> modifiers_except_radiation = new List<string>(); foreach (string s in rule.modifiers) { if (s != "radiation") modifiers_except_radiation.Add(s); } double mod = Modifiers.Evaluate(env_analyzer, vessel_analyzer, resource_sim, modifiers_except_radiation); // calculate life expectancy at various radiation levels double[] estimates = new double[7]; for (int i = 0; i < 7; ++i) { estimates[i] = rule.fatal_threshold / (rule.degeneration * mod * levels[i]); } // generate tooltip RadiationModel mf = Radiation.Info(env_analyzer.body).model; string tooltip = Lib.BuildString ( "<align=left />", String.Format("{0,-20}\t<b>{1}</b>\n", Local.Planner_surface, Lib.HumanReadableDuration(estimates[0])),//"surface" mf.has_pause ? String.Format("{0,-20}\t<b>{1}</b>\n", Local.Planner_magnetopause, Lib.HumanReadableDuration(estimates[1])) : "",//"magnetopause" mf.has_inner ? String.Format("{0,-20}\t<b>{1}</b>\n", Local.Planner_innerbelt, Lib.HumanReadableDuration(estimates[2])) : "",//"inner belt" mf.has_outer ? String.Format("{0,-20}\t<b>{1}</b>\n", Local.Planner_outerbelt, Lib.HumanReadableDuration(estimates[3])) : "",//"outer belt" String.Format("{0,-20}\t<b>{1}</b>\n", Local.Planner_interplanetary, Lib.HumanReadableDuration(estimates[4])),//"interplanetary" String.Format("{0,-20}\t<b>{1}</b>\n", Local.Planner_interstellar, Lib.HumanReadableDuration(estimates[5])),//"interstellar" String.Format("{0,-20}\t<b>{1}</b>", Local.Planner_storm, Lib.HumanReadableDuration(estimates[6]))//"storm" ); // render the panel p.AddSection(Local.Planner_RADIATION, string.Empty,//"RADIATION" () => { p.Prev(ref special_index, panel_special.Count); enforceUpdate = true; }, () => { p.Next(ref special_index, panel_special.Count); enforceUpdate = true; }); p.AddContent(Local.Planner_surface, Lib.HumanReadableRadiation(env_analyzer.surface_rad + vessel_analyzer.emitted), tooltip);//"surface" p.AddContent(Local.Planner_orbit, Lib.HumanReadableRadiation(env_analyzer.magnetopause_rad), tooltip);//"orbit" if (vessel_analyzer.emitted >= 0.0) p.AddContent(Local.Planner_emission, Lib.HumanReadableRadiation(vessel_analyzer.emitted), tooltip);//"emission" else p.AddContent(Local.Planner_activeshielding, Lib.HumanReadableRadiation(-vessel_analyzer.emitted), tooltip);//"active shielding" p.AddContent(Local.Planner_shielding, rule.modifiers.Contains("shielding") ? Habitat.Shielding_to_string(vessel_analyzer.shielding) : "N/A", tooltip);//"shielding" } ///<summary> Add reliability sub-panel, including tooltips </summary> private static void AddSubPanelReliability(Panel p) { // evaluate redundancy metric // - 0: no redundancy // - 0.5: all groups have 2 elements // - 1.0: all groups have 3 or more elements double redundancy_metric = 0.0; foreach (KeyValuePair<string, int> pair in vessel_analyzer.redundancy) { switch (pair.Value) { case 1: break; case 2: redundancy_metric += 0.5 / vessel_analyzer.redundancy.Count; break; default: redundancy_metric += 1.0 / vessel_analyzer.redundancy.Count; break; } } // traduce the redundancy metric to string string redundancy_str = string.Empty; if (redundancy_metric <= 0.1) redundancy_str = Local.Planner_none;//"none" else if (redundancy_metric <= 0.33) redundancy_str = Local.Planner_poor;//"poor" else if (redundancy_metric <= 0.66) redundancy_str = Local.Planner_okay;//"okay" else redundancy_str = Local.Planner_great;//"great" // generate redundancy tooltip string redundancy_tooltip = string.Empty; if (vessel_analyzer.redundancy.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, int> pair in vessel_analyzer.redundancy) { if (sb.Length > 0) sb.Append("\n"); sb.Append(Lib.Color(pair.Value.ToString(), pair.Value == 1 ? Lib.Kolor.Red : pair.Value == 2 ? Lib.Kolor.Yellow : Lib.Kolor.Green, true)); sb.Append("\t"); sb.Append(pair.Key); } redundancy_tooltip = Lib.BuildString("<align=left />", sb.ToString()); } // generate repair string and tooltip string repair_str = Local.Planner_none;//"none" string repair_tooltip = string.Empty; if (vessel_analyzer.crew_engineer) { repair_str = "engineer"; repair_tooltip = Local.Planner_engineer_tip;//"The engineer on board should\nbe able to handle all repairs" } else if (vessel_analyzer.crew_capacity == 0) { repair_str = "safemode"; repair_tooltip = Local.Planner_safemode_tip;//"We have a chance of repairing\nsome of the malfunctions remotely" } // render panel p.AddSection(Local.Planner_RELIABILITY, string.Empty,//"RELIABILITY" () => { p.Prev(ref special_index, panel_special.Count); enforceUpdate = true; }, () => { p.Next(ref special_index, panel_special.Count); enforceUpdate = true; }); p.AddContent(Local.Planner_malfunctions, Lib.HumanReadableAmount(vessel_analyzer.failure_year, "/y"), Local.Planner_malfunctions_tip);//"malfunctions""average case estimate\nfor the whole vessel" p.AddContent(Local.Planner_highquality, Lib.HumanReadablePerc(vessel_analyzer.high_quality), Local.Planner_highquality_tip);//"high quality""percentage of high quality components" p.AddContent(Local.Planner_redundancy, redundancy_str, redundancy_tooltip);//"redundancy" p.AddContent(Local.Planner_repair, repair_str, repair_tooltip);//"repair" } ///<summary> Add habitat sub-panel, including tooltips </summary> private static void AddSubPanelHabitat(Panel p) { SimulatedResource atmo_res = resource_sim.Resource("Atmosphere"); SimulatedResource waste_res = resource_sim.Resource("WasteAtmosphere"); // generate tooltips string atmo_tooltip = atmo_res.Tooltip(); string waste_tooltip = waste_res.Tooltip(true); // generate status string for scrubbing string waste_status = !Features.Poisoning //< feature disabled ? "n/a" : waste_res.produced <= double.Epsilon //< unnecessary ? Local.Planner_scrubbingunnecessary//"not required" : waste_res.consumed <= double.Epsilon //< no scrubbing ? Lib.Color(Local.Planner_noscrubbing, Lib.Kolor.Orange)//"none" : waste_res.produced > waste_res.consumed * 1.001 //< insufficient scrubbing ? Lib.Color(Local.Planner_insufficientscrubbing, Lib.Kolor.Yellow)//"inadequate" : Lib.Color(Local.Planner_sufficientscrubbing, Lib.Kolor.Green);//"good" //< sufficient scrubbing // generate status string for pressurization string atmo_status = !Features.Pressure //< feature disabled ? "n/a" : atmo_res.consumed <= double.Epsilon //< unnecessary ? Local.Planner_pressurizationunnecessary//"not required" : atmo_res.produced <= double.Epsilon //< no pressure control ? Lib.Color(Local.Planner_nopressurecontrol, Lib.Kolor.Orange)//"none" : atmo_res.consumed > atmo_res.produced * 1.001 //< insufficient pressure control ? Lib.Color(Local.Planner_insufficientpressurecontrol, Lib.Kolor.Yellow)//"inadequate" : Lib.Color(Local.Planner_sufficientpressurecontrol, Lib.Kolor.Green);//"good" //< sufficient pressure control p.AddSection(Local.Planner_HABITAT, string.Empty,//"HABITAT" () => { p.Prev(ref environment_index, panel_environment.Count); enforceUpdate = true; }, () => { p.Next(ref environment_index, panel_environment.Count); enforceUpdate = true; }); p.AddContent(Local.Planner_volume, Lib.HumanReadableVolume(vessel_analyzer.volume), Local.Planner_volume_tip);//"volume""volume of enabled habitats" p.AddContent(Local.Planner_habitatssurface, Lib.HumanReadableSurface(vessel_analyzer.surface), Local.Planner_habitatssurface_tip);//"surface""surface of enabled habitats" p.AddContent(Local.Planner_scrubbing, waste_status, waste_tooltip);//"scrubbing" p.AddContent(Local.Planner_pressurization, atmo_status, atmo_tooltip);//"pressurization" } #endregion #region FIELDS_PROPERTIES // store situations and altitude multipliers private static readonly string[] situations = { "Landed", "Low Orbit", "Orbit", "High Orbit" }; private static readonly double[] altitude_mults = { 0.0, 0.33, 1.0, 3.0 }; // styles private static GUIStyle devbuild_style; private static GUIStyle leftmenu_style; private static GUIStyle rightmenu_style; private static GUIStyle quote_style; private static GUIStyle icon_style; // analyzers private static ResourceSimulator resource_sim = new ResourceSimulator(); private static EnvironmentAnalyzer env_analyzer = new EnvironmentAnalyzer(); private static VesselAnalyzer vessel_analyzer = new VesselAnalyzer(); // panel arrays private static List<string> supplies = new List<string>(); private static List<string> panel_resource = new List<string>(); private static List<string> panel_special = new List<string>(); private static List<string> panel_environment = new List<string>(); // body/situation/sunlight indexes private static int body_index; private static int situation_index = 2; // orbit public enum SunlightState { SunlightNominal = 0, SunlightSimulated = 1, Shadow = 2 } private static SunlightState sunlight = SunlightState.SunlightSimulated; public static SunlightState Sunlight => sunlight; // panel indexes private static int resource_index; private static int special_index; private static int environment_index; // panel ui private static Panel panel = new Panel(); private static bool enforceUpdate = false; private static int update_counter = 0; #endregion } } // KERBALISM